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",
2441 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2442 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2445 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2446 btf_ext_data->d_size);
2447 if (IS_ERR(obj->btf_ext)) {
2448 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2449 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
2450 obj->btf_ext = NULL;
2455 if (err && libbpf_needs_btf(obj)) {
2456 pr_warn("BTF is required, but is missing or corrupted.\n");
2462 static int bpf_object__finalize_btf(struct bpf_object *obj)
2469 err = btf__finalize_data(obj, obj->btf);
2471 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2478 static inline bool libbpf_prog_needs_vmlinux_btf(struct bpf_program *prog)
2480 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2481 prog->type == BPF_PROG_TYPE_LSM)
2484 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2485 * also need vmlinux BTF
2487 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2493 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj)
2495 bool need_vmlinux_btf = false;
2496 struct bpf_program *prog;
2499 /* CO-RE relocations need kernel BTF */
2500 if (obj->btf_ext && obj->btf_ext->field_reloc_info.len)
2501 need_vmlinux_btf = true;
2503 bpf_object__for_each_program(prog, obj) {
2506 if (libbpf_prog_needs_vmlinux_btf(prog)) {
2507 need_vmlinux_btf = true;
2512 if (!need_vmlinux_btf)
2515 obj->btf_vmlinux = libbpf_find_kernel_btf();
2516 if (IS_ERR(obj->btf_vmlinux)) {
2517 err = PTR_ERR(obj->btf_vmlinux);
2518 pr_warn("Error loading vmlinux BTF: %d\n", err);
2519 obj->btf_vmlinux = NULL;
2525 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2527 struct btf *kern_btf = obj->btf;
2528 bool btf_mandatory, sanitize;
2534 sanitize = btf_needs_sanitization(obj);
2536 const void *raw_data;
2539 /* clone BTF to sanitize a copy and leave the original intact */
2540 raw_data = btf__get_raw_data(obj->btf, &sz);
2541 kern_btf = btf__new(raw_data, sz);
2542 if (IS_ERR(kern_btf))
2543 return PTR_ERR(kern_btf);
2545 bpf_object__sanitize_btf(obj, kern_btf);
2548 err = btf__load(kern_btf);
2551 /* move fd to libbpf's BTF */
2552 btf__set_fd(obj->btf, btf__fd(kern_btf));
2553 btf__set_fd(kern_btf, -1);
2555 btf__free(kern_btf);
2558 btf_mandatory = kernel_needs_btf(obj);
2559 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2560 btf_mandatory ? "BTF is mandatory, can't proceed."
2561 : "BTF is optional, ignoring.");
2568 static int bpf_object__elf_collect(struct bpf_object *obj)
2570 Elf *elf = obj->efile.elf;
2571 GElf_Ehdr *ep = &obj->efile.ehdr;
2572 Elf_Data *btf_ext_data = NULL;
2573 Elf_Data *btf_data = NULL;
2574 Elf_Scn *scn = NULL;
2575 int idx = 0, err = 0;
2577 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2578 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2579 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2580 return -LIBBPF_ERRNO__FORMAT;
2583 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2589 if (gelf_getshdr(scn, &sh) != &sh) {
2590 pr_warn("failed to get section(%d) header from %s\n",
2592 return -LIBBPF_ERRNO__FORMAT;
2595 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2597 pr_warn("failed to get section(%d) name from %s\n",
2599 return -LIBBPF_ERRNO__FORMAT;
2602 data = elf_getdata(scn, 0);
2604 pr_warn("failed to get section(%d) data from %s(%s)\n",
2605 idx, name, obj->path);
2606 return -LIBBPF_ERRNO__FORMAT;
2608 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2609 idx, name, (unsigned long)data->d_size,
2610 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2613 if (strcmp(name, "license") == 0) {
2614 err = bpf_object__init_license(obj,
2619 } else if (strcmp(name, "version") == 0) {
2620 err = bpf_object__init_kversion(obj,
2625 } else if (strcmp(name, "maps") == 0) {
2626 obj->efile.maps_shndx = idx;
2627 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2628 obj->efile.btf_maps_shndx = idx;
2629 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2631 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2632 btf_ext_data = data;
2633 } else if (sh.sh_type == SHT_SYMTAB) {
2634 if (obj->efile.symbols) {
2635 pr_warn("bpf: multiple SYMTAB in %s\n",
2637 return -LIBBPF_ERRNO__FORMAT;
2639 obj->efile.symbols = data;
2640 obj->efile.symbols_shndx = idx;
2641 obj->efile.strtabidx = sh.sh_link;
2642 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2643 if (sh.sh_flags & SHF_EXECINSTR) {
2644 if (strcmp(name, ".text") == 0)
2645 obj->efile.text_shndx = idx;
2646 err = bpf_object__add_program(obj, data->d_buf,
2650 char errmsg[STRERR_BUFSIZE];
2653 cp = libbpf_strerror_r(-err, errmsg,
2655 pr_warn("failed to alloc program %s (%s): %s",
2656 name, obj->path, cp);
2659 } else if (strcmp(name, DATA_SEC) == 0) {
2660 obj->efile.data = data;
2661 obj->efile.data_shndx = idx;
2662 } else if (strcmp(name, RODATA_SEC) == 0) {
2663 obj->efile.rodata = data;
2664 obj->efile.rodata_shndx = idx;
2665 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2666 obj->efile.st_ops_data = data;
2667 obj->efile.st_ops_shndx = idx;
2669 pr_debug("skip section(%d) %s\n", idx, name);
2671 } else if (sh.sh_type == SHT_REL) {
2672 int nr_sects = obj->efile.nr_reloc_sects;
2673 void *sects = obj->efile.reloc_sects;
2674 int sec = sh.sh_info; /* points to other section */
2676 /* Only do relo for section with exec instructions */
2677 if (!section_have_execinstr(obj, sec) &&
2678 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
2679 strcmp(name, ".rel" MAPS_ELF_SEC)) {
2680 pr_debug("skip relo %s(%d) for section(%d)\n",
2685 sects = reallocarray(sects, nr_sects + 1,
2686 sizeof(*obj->efile.reloc_sects));
2688 pr_warn("reloc_sects realloc failed\n");
2692 obj->efile.reloc_sects = sects;
2693 obj->efile.nr_reloc_sects++;
2695 obj->efile.reloc_sects[nr_sects].shdr = sh;
2696 obj->efile.reloc_sects[nr_sects].data = data;
2697 } else if (sh.sh_type == SHT_NOBITS &&
2698 strcmp(name, BSS_SEC) == 0) {
2699 obj->efile.bss = data;
2700 obj->efile.bss_shndx = idx;
2702 pr_debug("skip section(%d) %s\n", idx, name);
2706 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2707 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2708 return -LIBBPF_ERRNO__FORMAT;
2710 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2713 static bool sym_is_extern(const GElf_Sym *sym)
2715 int bind = GELF_ST_BIND(sym->st_info);
2716 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2717 return sym->st_shndx == SHN_UNDEF &&
2718 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2719 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2722 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2724 const struct btf_type *t;
2725 const char *var_name;
2731 n = btf__get_nr_types(btf);
2732 for (i = 1; i <= n; i++) {
2733 t = btf__type_by_id(btf, i);
2738 var_name = btf__name_by_offset(btf, t->name_off);
2739 if (strcmp(var_name, ext_name))
2742 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2751 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
2752 const struct btf_var_secinfo *vs;
2753 const struct btf_type *t;
2759 n = btf__get_nr_types(btf);
2760 for (i = 1; i <= n; i++) {
2761 t = btf__type_by_id(btf, i);
2763 if (!btf_is_datasec(t))
2766 vs = btf_var_secinfos(t);
2767 for (j = 0; j < btf_vlen(t); j++, vs++) {
2768 if (vs->type == ext_btf_id)
2776 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
2779 const struct btf_type *t;
2782 t = skip_mods_and_typedefs(btf, id, NULL);
2783 name = btf__name_by_offset(btf, t->name_off);
2787 switch (btf_kind(t)) {
2788 case BTF_KIND_INT: {
2789 int enc = btf_int_encoding(t);
2791 if (enc & BTF_INT_BOOL)
2792 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
2794 *is_signed = enc & BTF_INT_SIGNED;
2797 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2798 return KCFG_UNKNOWN;
2803 return KCFG_UNKNOWN;
2804 if (strcmp(name, "libbpf_tristate"))
2805 return KCFG_UNKNOWN;
2806 return KCFG_TRISTATE;
2807 case BTF_KIND_ARRAY:
2808 if (btf_array(t)->nelems == 0)
2809 return KCFG_UNKNOWN;
2810 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
2811 return KCFG_UNKNOWN;
2812 return KCFG_CHAR_ARR;
2814 return KCFG_UNKNOWN;
2818 static int cmp_externs(const void *_a, const void *_b)
2820 const struct extern_desc *a = _a;
2821 const struct extern_desc *b = _b;
2823 if (a->type != b->type)
2824 return a->type < b->type ? -1 : 1;
2826 if (a->type == EXT_KCFG) {
2827 /* descending order by alignment requirements */
2828 if (a->kcfg.align != b->kcfg.align)
2829 return a->kcfg.align > b->kcfg.align ? -1 : 1;
2830 /* ascending order by size, within same alignment class */
2831 if (a->kcfg.sz != b->kcfg.sz)
2832 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
2835 /* resolve ties by name */
2836 return strcmp(a->name, b->name);
2839 static int find_int_btf_id(const struct btf *btf)
2841 const struct btf_type *t;
2844 n = btf__get_nr_types(btf);
2845 for (i = 1; i <= n; i++) {
2846 t = btf__type_by_id(btf, i);
2848 if (btf_is_int(t) && btf_int_bits(t) == 32)
2855 static int bpf_object__collect_externs(struct bpf_object *obj)
2857 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
2858 const struct btf_type *t;
2859 struct extern_desc *ext;
2861 const char *ext_name, *sec_name;
2865 if (!obj->efile.symbols)
2868 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2870 return -LIBBPF_ERRNO__FORMAT;
2871 if (gelf_getshdr(scn, &sh) != &sh)
2872 return -LIBBPF_ERRNO__FORMAT;
2873 n = sh.sh_size / sh.sh_entsize;
2875 pr_debug("looking for externs among %d symbols...\n", n);
2876 for (i = 0; i < n; i++) {
2879 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2880 return -LIBBPF_ERRNO__FORMAT;
2881 if (!sym_is_extern(&sym))
2883 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2885 if (!ext_name || !ext_name[0])
2889 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2893 ext = &ext[obj->nr_extern];
2894 memset(ext, 0, sizeof(*ext));
2897 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2898 if (ext->btf_id <= 0) {
2899 pr_warn("failed to find BTF for extern '%s': %d\n",
2900 ext_name, ext->btf_id);
2903 t = btf__type_by_id(obj->btf, ext->btf_id);
2904 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2906 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2908 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
2909 if (ext->sec_btf_id <= 0) {
2910 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
2911 ext_name, ext->btf_id, ext->sec_btf_id);
2912 return ext->sec_btf_id;
2914 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
2915 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
2917 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
2919 ext->type = EXT_KCFG;
2920 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
2921 if (ext->kcfg.sz <= 0) {
2922 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
2923 ext_name, ext->kcfg.sz);
2924 return ext->kcfg.sz;
2926 ext->kcfg.align = btf__align_of(obj->btf, t->type);
2927 if (ext->kcfg.align <= 0) {
2928 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
2929 ext_name, ext->kcfg.align);
2932 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
2933 &ext->kcfg.is_signed);
2934 if (ext->kcfg.type == KCFG_UNKNOWN) {
2935 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
2938 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
2939 const struct btf_type *vt;
2942 ext->type = EXT_KSYM;
2944 vt = skip_mods_and_typedefs(obj->btf, t->type, NULL);
2945 if (!btf_is_void(vt)) {
2946 pr_warn("extern (ksym) '%s' is not typeless (void)\n", ext_name);
2950 pr_warn("unrecognized extern section '%s'\n", sec_name);
2954 pr_debug("collected %d externs total\n", obj->nr_extern);
2956 if (!obj->nr_extern)
2959 /* sort externs by type, for kcfg ones also by (align, size, name) */
2960 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2962 /* for .ksyms section, we need to turn all externs into allocated
2963 * variables in BTF to pass kernel verification; we do this by
2964 * pretending that each extern is a 8-byte variable
2967 /* find existing 4-byte integer type in BTF to use for fake
2968 * extern variables in DATASEC
2970 int int_btf_id = find_int_btf_id(obj->btf);
2972 for (i = 0; i < obj->nr_extern; i++) {
2973 ext = &obj->externs[i];
2974 if (ext->type != EXT_KSYM)
2976 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
2977 i, ext->sym_idx, ext->name);
2982 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
2983 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2984 struct btf_type *vt;
2986 vt = (void *)btf__type_by_id(obj->btf, vs->type);
2987 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
2988 ext = find_extern_by_name(obj, ext_name);
2990 pr_warn("failed to find extern definition for BTF var '%s'\n",
2994 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2995 vt->type = int_btf_id;
2997 vs->size = sizeof(int);
3004 /* for kcfg externs calculate their offsets within a .kconfig map */
3006 for (i = 0; i < obj->nr_extern; i++) {
3007 ext = &obj->externs[i];
3008 if (ext->type != EXT_KCFG)
3011 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3012 off = ext->kcfg.data_off + ext->kcfg.sz;
3013 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3014 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3018 for (i = 0; i < n; i++) {
3019 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3021 t = btf__type_by_id(obj->btf, vs->type);
3022 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3023 ext = find_extern_by_name(obj, ext_name);
3025 pr_warn("failed to find extern definition for BTF var '%s'\n",
3029 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3030 vs->offset = ext->kcfg.data_off;
3036 static struct bpf_program *
3037 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
3039 struct bpf_program *prog;
3042 for (i = 0; i < obj->nr_programs; i++) {
3043 prog = &obj->programs[i];
3044 if (prog->idx == idx)
3050 struct bpf_program *
3051 bpf_object__find_program_by_title(const struct bpf_object *obj,
3054 struct bpf_program *pos;
3056 bpf_object__for_each_program(pos, obj) {
3057 if (pos->section_name && !strcmp(pos->section_name, title))
3063 struct bpf_program *
3064 bpf_object__find_program_by_name(const struct bpf_object *obj,
3067 struct bpf_program *prog;
3069 bpf_object__for_each_program(prog, obj) {
3070 if (!strcmp(prog->name, name))
3076 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3079 return shndx == obj->efile.data_shndx ||
3080 shndx == obj->efile.bss_shndx ||
3081 shndx == obj->efile.rodata_shndx;
3084 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3087 return shndx == obj->efile.maps_shndx ||
3088 shndx == obj->efile.btf_maps_shndx;
3091 static enum libbpf_map_type
3092 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3094 if (shndx == obj->efile.data_shndx)
3095 return LIBBPF_MAP_DATA;
3096 else if (shndx == obj->efile.bss_shndx)
3097 return LIBBPF_MAP_BSS;
3098 else if (shndx == obj->efile.rodata_shndx)
3099 return LIBBPF_MAP_RODATA;
3100 else if (shndx == obj->efile.symbols_shndx)
3101 return LIBBPF_MAP_KCONFIG;
3103 return LIBBPF_MAP_UNSPEC;
3106 static int bpf_program__record_reloc(struct bpf_program *prog,
3107 struct reloc_desc *reloc_desc,
3108 __u32 insn_idx, const char *name,
3109 const GElf_Sym *sym, const GElf_Rel *rel)
3111 struct bpf_insn *insn = &prog->insns[insn_idx];
3112 size_t map_idx, nr_maps = prog->obj->nr_maps;
3113 struct bpf_object *obj = prog->obj;
3114 __u32 shdr_idx = sym->st_shndx;
3115 enum libbpf_map_type type;
3116 struct bpf_map *map;
3118 /* sub-program call relocation */
3119 if (insn->code == (BPF_JMP | BPF_CALL)) {
3120 if (insn->src_reg != BPF_PSEUDO_CALL) {
3121 pr_warn("incorrect bpf_call opcode\n");
3122 return -LIBBPF_ERRNO__RELOC;
3124 /* text_shndx can be 0, if no default "main" program exists */
3125 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3126 pr_warn("bad call relo against section %u\n", shdr_idx);
3127 return -LIBBPF_ERRNO__RELOC;
3129 if (sym->st_value % 8) {
3130 pr_warn("bad call relo offset: %zu\n",
3131 (size_t)sym->st_value);
3132 return -LIBBPF_ERRNO__RELOC;
3134 reloc_desc->type = RELO_CALL;
3135 reloc_desc->insn_idx = insn_idx;
3136 reloc_desc->sym_off = sym->st_value;
3137 obj->has_pseudo_calls = true;
3141 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
3142 pr_warn("invalid relo for insns[%d].code 0x%x\n",
3143 insn_idx, insn->code);
3144 return -LIBBPF_ERRNO__RELOC;
3147 if (sym_is_extern(sym)) {
3148 int sym_idx = GELF_R_SYM(rel->r_info);
3149 int i, n = obj->nr_extern;
3150 struct extern_desc *ext;
3152 for (i = 0; i < n; i++) {
3153 ext = &obj->externs[i];
3154 if (ext->sym_idx == sym_idx)
3158 pr_warn("extern relo failed to find extern for sym %d\n",
3160 return -LIBBPF_ERRNO__RELOC;
3162 pr_debug("found extern #%d '%s' (sym %d) for insn %u\n",
3163 i, ext->name, ext->sym_idx, insn_idx);
3164 reloc_desc->type = RELO_EXTERN;
3165 reloc_desc->insn_idx = insn_idx;
3166 reloc_desc->sym_off = i; /* sym_off stores extern index */
3170 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3171 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
3173 return -LIBBPF_ERRNO__RELOC;
3176 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3178 /* generic map reference relocation */
3179 if (type == LIBBPF_MAP_UNSPEC) {
3180 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3181 pr_warn("bad map relo against section %u\n",
3183 return -LIBBPF_ERRNO__RELOC;
3185 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3186 map = &obj->maps[map_idx];
3187 if (map->libbpf_type != type ||
3188 map->sec_idx != sym->st_shndx ||
3189 map->sec_offset != sym->st_value)
3191 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
3192 map_idx, map->name, map->sec_idx,
3193 map->sec_offset, insn_idx);
3196 if (map_idx >= nr_maps) {
3197 pr_warn("map relo failed to find map for sec %u, off %zu\n",
3198 shdr_idx, (size_t)sym->st_value);
3199 return -LIBBPF_ERRNO__RELOC;
3201 reloc_desc->type = RELO_LD64;
3202 reloc_desc->insn_idx = insn_idx;
3203 reloc_desc->map_idx = map_idx;
3204 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3208 /* global data map relocation */
3209 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3210 pr_warn("bad data relo against section %u\n", shdr_idx);
3211 return -LIBBPF_ERRNO__RELOC;
3213 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3214 map = &obj->maps[map_idx];
3215 if (map->libbpf_type != type)
3217 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3218 map_idx, map->name, map->sec_idx, map->sec_offset,
3222 if (map_idx >= nr_maps) {
3223 pr_warn("data relo failed to find map for sec %u\n",
3225 return -LIBBPF_ERRNO__RELOC;
3228 reloc_desc->type = RELO_DATA;
3229 reloc_desc->insn_idx = insn_idx;
3230 reloc_desc->map_idx = map_idx;
3231 reloc_desc->sym_off = sym->st_value;
3236 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
3237 Elf_Data *data, struct bpf_object *obj)
3239 Elf_Data *symbols = obj->efile.symbols;
3242 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
3243 nrels = shdr->sh_size / shdr->sh_entsize;
3245 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
3246 if (!prog->reloc_desc) {
3247 pr_warn("failed to alloc memory in relocation\n");
3250 prog->nr_reloc = nrels;
3252 for (i = 0; i < nrels; i++) {
3258 if (!gelf_getrel(data, i, &rel)) {
3259 pr_warn("relocation: failed to get %d reloc\n", i);
3260 return -LIBBPF_ERRNO__FORMAT;
3262 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3263 pr_warn("relocation: symbol %"PRIx64" not found\n",
3264 GELF_R_SYM(rel.r_info));
3265 return -LIBBPF_ERRNO__FORMAT;
3267 if (rel.r_offset % sizeof(struct bpf_insn))
3268 return -LIBBPF_ERRNO__FORMAT;
3270 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
3271 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
3272 sym.st_name) ? : "<?>";
3274 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
3275 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
3276 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
3277 GELF_ST_BIND(sym.st_info), sym.st_name, name,
3280 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
3281 insn_idx, name, &sym, &rel);
3288 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3290 struct bpf_map_def *def = &map->def;
3291 __u32 key_type_id = 0, value_type_id = 0;
3294 /* if it's BTF-defined map, we don't need to search for type IDs.
3295 * For struct_ops map, it does not need btf_key_type_id and
3296 * btf_value_type_id.
3298 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3299 bpf_map__is_struct_ops(map))
3302 if (!bpf_map__is_internal(map)) {
3303 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3304 def->value_size, &key_type_id,
3308 * LLVM annotates global data differently in BTF, that is,
3309 * only as '.data', '.bss' or '.rodata'.
3311 ret = btf__find_by_name(obj->btf,
3312 libbpf_type_to_btf_name[map->libbpf_type]);
3317 map->btf_key_type_id = key_type_id;
3318 map->btf_value_type_id = bpf_map__is_internal(map) ?
3319 ret : value_type_id;
3323 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3325 struct bpf_map_info info = {};
3326 __u32 len = sizeof(info);
3330 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3334 new_name = strdup(info.name);
3338 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3341 goto err_free_new_name;
3344 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3347 goto err_close_new_fd;
3350 err = zclose(map->fd);
3353 goto err_close_new_fd;
3358 map->name = new_name;
3359 map->def.type = info.type;
3360 map->def.key_size = info.key_size;
3361 map->def.value_size = info.value_size;
3362 map->def.max_entries = info.max_entries;
3363 map->def.map_flags = info.map_flags;
3364 map->btf_key_type_id = info.btf_key_type_id;
3365 map->btf_value_type_id = info.btf_value_type_id;
3377 __u32 bpf_map__max_entries(const struct bpf_map *map)
3379 return map->def.max_entries;
3382 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
3386 map->def.max_entries = max_entries;
3390 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3392 if (!map || !max_entries)
3395 return bpf_map__set_max_entries(map, max_entries);
3399 bpf_object__probe_loading(struct bpf_object *obj)
3401 struct bpf_load_program_attr attr;
3402 char *cp, errmsg[STRERR_BUFSIZE];
3403 struct bpf_insn insns[] = {
3404 BPF_MOV64_IMM(BPF_REG_0, 0),
3409 /* make sure basic loading works */
3411 memset(&attr, 0, sizeof(attr));
3412 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3414 attr.insns_cnt = ARRAY_SIZE(insns);
3415 attr.license = "GPL";
3417 ret = bpf_load_program_xattr(&attr, NULL, 0);
3420 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3421 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
3422 "program. Make sure your kernel supports BPF "
3423 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
3424 "set to big enough value.\n", __func__, cp, ret);
3433 bpf_object__probe_name(struct bpf_object *obj)
3435 struct bpf_load_program_attr attr;
3436 struct bpf_insn insns[] = {
3437 BPF_MOV64_IMM(BPF_REG_0, 0),
3442 /* make sure loading with name works */
3444 memset(&attr, 0, sizeof(attr));
3445 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3447 attr.insns_cnt = ARRAY_SIZE(insns);
3448 attr.license = "GPL";
3450 ret = bpf_load_program_xattr(&attr, NULL, 0);
3460 bpf_object__probe_global_data(struct bpf_object *obj)
3462 struct bpf_load_program_attr prg_attr;
3463 struct bpf_create_map_attr map_attr;
3464 char *cp, errmsg[STRERR_BUFSIZE];
3465 struct bpf_insn insns[] = {
3466 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3467 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3468 BPF_MOV64_IMM(BPF_REG_0, 0),
3473 memset(&map_attr, 0, sizeof(map_attr));
3474 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3475 map_attr.key_size = sizeof(int);
3476 map_attr.value_size = 32;
3477 map_attr.max_entries = 1;
3479 map = bpf_create_map_xattr(&map_attr);
3481 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3482 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3483 __func__, cp, errno);
3489 memset(&prg_attr, 0, sizeof(prg_attr));
3490 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3491 prg_attr.insns = insns;
3492 prg_attr.insns_cnt = ARRAY_SIZE(insns);
3493 prg_attr.license = "GPL";
3495 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
3497 obj->caps.global_data = 1;
3505 static int bpf_object__probe_btf_func(struct bpf_object *obj)
3507 static const char strs[] = "\0int\0x\0a";
3508 /* void x(int a) {} */
3511 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3512 /* FUNC_PROTO */ /* [2] */
3513 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3514 BTF_PARAM_ENC(7, 1),
3515 /* FUNC x */ /* [3] */
3516 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3520 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3521 strs, sizeof(strs));
3523 obj->caps.btf_func = 1;
3531 static int bpf_object__probe_btf_func_global(struct bpf_object *obj)
3533 static const char strs[] = "\0int\0x\0a";
3534 /* static void x(int a) {} */
3537 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3538 /* FUNC_PROTO */ /* [2] */
3539 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3540 BTF_PARAM_ENC(7, 1),
3541 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
3542 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3546 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3547 strs, sizeof(strs));
3549 obj->caps.btf_func_global = 1;
3557 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
3559 static const char strs[] = "\0x\0.data";
3563 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3564 /* VAR x */ /* [2] */
3565 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3567 /* DATASEC val */ /* [3] */
3568 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3569 BTF_VAR_SECINFO_ENC(2, 0, 4),
3573 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3574 strs, sizeof(strs));
3576 obj->caps.btf_datasec = 1;
3584 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
3586 struct bpf_create_map_attr attr = {
3587 .map_type = BPF_MAP_TYPE_ARRAY,
3588 .map_flags = BPF_F_MMAPABLE,
3589 .key_size = sizeof(int),
3590 .value_size = sizeof(int),
3595 fd = bpf_create_map_xattr(&attr);
3597 obj->caps.array_mmap = 1;
3606 bpf_object__probe_exp_attach_type(struct bpf_object *obj)
3608 struct bpf_load_program_attr attr;
3609 struct bpf_insn insns[] = {
3610 BPF_MOV64_IMM(BPF_REG_0, 0),
3615 memset(&attr, 0, sizeof(attr));
3616 /* use any valid combination of program type and (optional)
3617 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
3618 * to see if kernel supports expected_attach_type field for
3619 * BPF_PROG_LOAD command
3621 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
3622 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
3624 attr.insns_cnt = ARRAY_SIZE(insns);
3625 attr.license = "GPL";
3627 fd = bpf_load_program_xattr(&attr, NULL, 0);
3629 obj->caps.exp_attach_type = 1;
3637 bpf_object__probe_caps(struct bpf_object *obj)
3639 int (*probe_fn[])(struct bpf_object *obj) = {
3640 bpf_object__probe_name,
3641 bpf_object__probe_global_data,
3642 bpf_object__probe_btf_func,
3643 bpf_object__probe_btf_func_global,
3644 bpf_object__probe_btf_datasec,
3645 bpf_object__probe_array_mmap,
3646 bpf_object__probe_exp_attach_type,
3650 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
3651 ret = probe_fn[i](obj);
3653 pr_debug("Probe #%d failed with %d.\n", i, ret);
3659 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
3661 struct bpf_map_info map_info = {};
3662 char msg[STRERR_BUFSIZE];
3665 map_info_len = sizeof(map_info);
3667 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
3668 pr_warn("failed to get map info for map FD %d: %s\n",
3669 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
3673 return (map_info.type == map->def.type &&
3674 map_info.key_size == map->def.key_size &&
3675 map_info.value_size == map->def.value_size &&
3676 map_info.max_entries == map->def.max_entries &&
3677 map_info.map_flags == map->def.map_flags);
3681 bpf_object__reuse_map(struct bpf_map *map)
3683 char *cp, errmsg[STRERR_BUFSIZE];
3686 pin_fd = bpf_obj_get(map->pin_path);
3689 if (err == -ENOENT) {
3690 pr_debug("found no pinned map to reuse at '%s'\n",
3695 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3696 pr_warn("couldn't retrieve pinned map '%s': %s\n",
3701 if (!map_is_reuse_compat(map, pin_fd)) {
3702 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3708 err = bpf_map__reuse_fd(map, pin_fd);
3714 pr_debug("reused pinned map at '%s'\n", map->pin_path);
3720 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
3722 enum libbpf_map_type map_type = map->libbpf_type;
3723 char *cp, errmsg[STRERR_BUFSIZE];
3726 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
3729 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3730 pr_warn("Error setting initial map(%s) contents: %s\n",
3735 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
3736 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
3737 err = bpf_map_freeze(map->fd);
3740 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3741 pr_warn("Error freezing map(%s) as read-only: %s\n",
3749 static void bpf_map__destroy(struct bpf_map *map);
3751 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map)
3753 struct bpf_create_map_attr create_attr;
3754 struct bpf_map_def *def = &map->def;
3756 memset(&create_attr, 0, sizeof(create_attr));
3759 create_attr.name = map->name;
3760 create_attr.map_ifindex = map->map_ifindex;
3761 create_attr.map_type = def->type;
3762 create_attr.map_flags = def->map_flags;
3763 create_attr.key_size = def->key_size;
3764 create_attr.value_size = def->value_size;
3765 create_attr.numa_node = map->numa_node;
3767 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
3770 nr_cpus = libbpf_num_possible_cpus();
3772 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
3773 map->name, nr_cpus);
3776 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
3777 create_attr.max_entries = nr_cpus;
3779 create_attr.max_entries = def->max_entries;
3782 if (bpf_map__is_struct_ops(map))
3783 create_attr.btf_vmlinux_value_type_id =
3784 map->btf_vmlinux_value_type_id;
3786 create_attr.btf_fd = 0;
3787 create_attr.btf_key_type_id = 0;
3788 create_attr.btf_value_type_id = 0;
3789 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
3790 create_attr.btf_fd = btf__fd(obj->btf);
3791 create_attr.btf_key_type_id = map->btf_key_type_id;
3792 create_attr.btf_value_type_id = map->btf_value_type_id;
3795 if (bpf_map_type__is_map_in_map(def->type)) {
3796 if (map->inner_map) {
3799 err = bpf_object__create_map(obj, map->inner_map);
3801 pr_warn("map '%s': failed to create inner map: %d\n",
3805 map->inner_map_fd = bpf_map__fd(map->inner_map);
3807 if (map->inner_map_fd >= 0)
3808 create_attr.inner_map_fd = map->inner_map_fd;
3811 map->fd = bpf_create_map_xattr(&create_attr);
3812 if (map->fd < 0 && (create_attr.btf_key_type_id ||
3813 create_attr.btf_value_type_id)) {
3814 char *cp, errmsg[STRERR_BUFSIZE];
3817 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3818 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3819 map->name, cp, err);
3820 create_attr.btf_fd = 0;
3821 create_attr.btf_key_type_id = 0;
3822 create_attr.btf_value_type_id = 0;
3823 map->btf_key_type_id = 0;
3824 map->btf_value_type_id = 0;
3825 map->fd = bpf_create_map_xattr(&create_attr);
3831 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
3832 bpf_map__destroy(map->inner_map);
3833 zfree(&map->inner_map);
3840 bpf_object__create_maps(struct bpf_object *obj)
3842 struct bpf_map *map;
3843 char *cp, errmsg[STRERR_BUFSIZE];
3847 for (i = 0; i < obj->nr_maps; i++) {
3848 map = &obj->maps[i];
3850 if (map->pin_path) {
3851 err = bpf_object__reuse_map(map);
3853 pr_warn("map '%s': error reusing pinned map\n",
3860 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
3861 map->name, map->fd);
3865 err = bpf_object__create_map(obj, map);
3869 pr_debug("map '%s': created successfully, fd=%d\n", map->name,
3872 if (bpf_map__is_internal(map)) {
3873 err = bpf_object__populate_internal_map(obj, map);
3880 if (map->init_slots_sz) {
3881 for (j = 0; j < map->init_slots_sz; j++) {
3882 const struct bpf_map *targ_map;
3885 if (!map->init_slots[j])
3888 targ_map = map->init_slots[j];
3889 fd = bpf_map__fd(targ_map);
3890 err = bpf_map_update_elem(map->fd, &j, &fd, 0);
3893 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
3894 map->name, j, targ_map->name,
3898 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
3899 map->name, j, targ_map->name, fd);
3901 zfree(&map->init_slots);
3902 map->init_slots_sz = 0;
3905 if (map->pin_path && !map->pinned) {
3906 err = bpf_map__pin(map, NULL);
3908 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
3909 map->name, map->pin_path, err);
3919 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3920 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
3922 for (j = 0; j < i; j++)
3923 zclose(obj->maps[j].fd);
3928 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3929 void *btf_prog_info, const char *info_name)
3931 if (err != -ENOENT) {
3932 pr_warn("Error in loading %s for sec %s.\n",
3933 info_name, prog->section_name);
3937 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3939 if (btf_prog_info) {
3941 * Some info has already been found but has problem
3942 * in the last btf_ext reloc. Must have to error out.
3944 pr_warn("Error in relocating %s for sec %s.\n",
3945 info_name, prog->section_name);
3949 /* Have problem loading the very first info. Ignore the rest. */
3950 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3951 info_name, prog->section_name, info_name);
3956 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3957 const char *section_name, __u32 insn_offset)
3961 if (!insn_offset || prog->func_info) {
3963 * !insn_offset => main program
3965 * For sub prog, the main program's func_info has to
3966 * be loaded first (i.e. prog->func_info != NULL)
3968 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3969 section_name, insn_offset,
3971 &prog->func_info_cnt);
3973 return check_btf_ext_reloc_err(prog, err,
3977 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3980 if (!insn_offset || prog->line_info) {
3981 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3982 section_name, insn_offset,
3984 &prog->line_info_cnt);
3986 return check_btf_ext_reloc_err(prog, err,
3990 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3996 #define BPF_CORE_SPEC_MAX_LEN 64
3998 /* represents BPF CO-RE field or array element accessor */
3999 struct bpf_core_accessor {
4000 __u32 type_id; /* struct/union type or array element type */
4001 __u32 idx; /* field index or array index */
4002 const char *name; /* field name or NULL for array accessor */
4005 struct bpf_core_spec {
4006 const struct btf *btf;
4007 /* high-level spec: named fields and array indices only */
4008 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
4009 /* high-level spec length */
4011 /* raw, low-level spec: 1-to-1 with accessor spec string */
4012 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
4013 /* raw spec length */
4015 /* field bit offset represented by spec */
4019 static bool str_is_empty(const char *s)
4024 static bool is_flex_arr(const struct btf *btf,
4025 const struct bpf_core_accessor *acc,
4026 const struct btf_array *arr)
4028 const struct btf_type *t;
4030 /* not a flexible array, if not inside a struct or has non-zero size */
4031 if (!acc->name || arr->nelems > 0)
4034 /* has to be the last member of enclosing struct */
4035 t = btf__type_by_id(btf, acc->type_id);
4036 return acc->idx == btf_vlen(t) - 1;
4040 * Turn bpf_field_reloc into a low- and high-level spec representation,
4041 * validating correctness along the way, as well as calculating resulting
4042 * field bit offset, specified by accessor string. Low-level spec captures
4043 * every single level of nestedness, including traversing anonymous
4044 * struct/union members. High-level one only captures semantically meaningful
4045 * "turning points": named fields and array indicies.
4046 * E.g., for this case:
4049 * int __unimportant;
4057 * struct sample *s = ...;
4059 * int x = &s->a[3]; // access string = '0:1:2:3'
4061 * Low-level spec has 1:1 mapping with each element of access string (it's
4062 * just a parsed access string representation): [0, 1, 2, 3].
4064 * High-level spec will capture only 3 points:
4065 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
4066 * - field 'a' access (corresponds to '2' in low-level spec);
4067 * - array element #3 access (corresponds to '3' in low-level spec).
4070 static int bpf_core_spec_parse(const struct btf *btf,
4072 const char *spec_str,
4073 struct bpf_core_spec *spec)
4075 int access_idx, parsed_len, i;
4076 struct bpf_core_accessor *acc;
4077 const struct btf_type *t;
4082 if (str_is_empty(spec_str) || *spec_str == ':')
4085 memset(spec, 0, sizeof(*spec));
4088 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
4090 if (*spec_str == ':')
4092 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
4094 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4096 spec_str += parsed_len;
4097 spec->raw_spec[spec->raw_len++] = access_idx;
4100 if (spec->raw_len == 0)
4103 /* first spec value is always reloc type array index */
4104 t = skip_mods_and_typedefs(btf, type_id, &id);
4108 access_idx = spec->raw_spec[0];
4109 spec->spec[0].type_id = id;
4110 spec->spec[0].idx = access_idx;
4113 sz = btf__resolve_size(btf, id);
4116 spec->bit_offset = access_idx * sz * 8;
4118 for (i = 1; i < spec->raw_len; i++) {
4119 t = skip_mods_and_typedefs(btf, id, &id);
4123 access_idx = spec->raw_spec[i];
4124 acc = &spec->spec[spec->len];
4126 if (btf_is_composite(t)) {
4127 const struct btf_member *m;
4130 if (access_idx >= btf_vlen(t))
4133 bit_offset = btf_member_bit_offset(t, access_idx);
4134 spec->bit_offset += bit_offset;
4136 m = btf_members(t) + access_idx;
4138 name = btf__name_by_offset(btf, m->name_off);
4139 if (str_is_empty(name))
4143 acc->idx = access_idx;
4149 } else if (btf_is_array(t)) {
4150 const struct btf_array *a = btf_array(t);
4153 t = skip_mods_and_typedefs(btf, a->type, &id);
4157 flex = is_flex_arr(btf, acc - 1, a);
4158 if (!flex && access_idx >= a->nelems)
4161 spec->spec[spec->len].type_id = id;
4162 spec->spec[spec->len].idx = access_idx;
4165 sz = btf__resolve_size(btf, id);
4168 spec->bit_offset += access_idx * sz * 8;
4170 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
4171 type_id, spec_str, i, id, btf_kind(t));
4179 static bool bpf_core_is_flavor_sep(const char *s)
4181 /* check X___Y name pattern, where X and Y are not underscores */
4182 return s[0] != '_' && /* X */
4183 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4184 s[4] != '_'; /* Y */
4187 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4188 * before last triple underscore. Struct name part after last triple
4189 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4191 static size_t bpf_core_essential_name_len(const char *name)
4193 size_t n = strlen(name);
4196 for (i = n - 5; i >= 0; i--) {
4197 if (bpf_core_is_flavor_sep(name + i))
4203 /* dynamically sized list of type IDs */
4209 static void bpf_core_free_cands(struct ids_vec *cand_ids)
4211 free(cand_ids->data);
4215 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
4216 __u32 local_type_id,
4217 const struct btf *targ_btf)
4219 size_t local_essent_len, targ_essent_len;
4220 const char *local_name, *targ_name;
4221 const struct btf_type *t;
4222 struct ids_vec *cand_ids;
4226 t = btf__type_by_id(local_btf, local_type_id);
4228 return ERR_PTR(-EINVAL);
4230 local_name = btf__name_by_offset(local_btf, t->name_off);
4231 if (str_is_empty(local_name))
4232 return ERR_PTR(-EINVAL);
4233 local_essent_len = bpf_core_essential_name_len(local_name);
4235 cand_ids = calloc(1, sizeof(*cand_ids));
4237 return ERR_PTR(-ENOMEM);
4239 n = btf__get_nr_types(targ_btf);
4240 for (i = 1; i <= n; i++) {
4241 t = btf__type_by_id(targ_btf, i);
4242 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4243 if (str_is_empty(targ_name))
4246 t = skip_mods_and_typedefs(targ_btf, i, NULL);
4247 if (!btf_is_composite(t) && !btf_is_array(t))
4250 targ_essent_len = bpf_core_essential_name_len(targ_name);
4251 if (targ_essent_len != local_essent_len)
4254 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
4255 pr_debug("[%d] %s: found candidate [%d] %s\n",
4256 local_type_id, local_name, i, targ_name);
4257 new_ids = reallocarray(cand_ids->data,
4259 sizeof(*cand_ids->data));
4264 cand_ids->data = new_ids;
4265 cand_ids->data[cand_ids->len++] = i;
4270 bpf_core_free_cands(cand_ids);
4271 return ERR_PTR(err);
4274 /* Check two types for compatibility, skipping const/volatile/restrict and
4275 * typedefs, to ensure we are relocating compatible entities:
4276 * - any two STRUCTs/UNIONs are compatible and can be mixed;
4277 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
4278 * - any two PTRs are always compatible;
4279 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
4280 * least one of enums should be anonymous;
4281 * - for ENUMs, check sizes, names are ignored;
4282 * - for INT, size and signedness are ignored;
4283 * - for ARRAY, dimensionality is ignored, element types are checked for
4284 * compatibility recursively;
4285 * - everything else shouldn't be ever a target of relocation.
4286 * These rules are not set in stone and probably will be adjusted as we get
4287 * more experience with using BPF CO-RE relocations.
4289 static int bpf_core_fields_are_compat(const struct btf *local_btf,
4291 const struct btf *targ_btf,
4294 const struct btf_type *local_type, *targ_type;
4297 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
4298 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4299 if (!local_type || !targ_type)
4302 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
4304 if (btf_kind(local_type) != btf_kind(targ_type))
4307 switch (btf_kind(local_type)) {
4311 case BTF_KIND_ENUM: {
4312 const char *local_name, *targ_name;
4313 size_t local_len, targ_len;
4315 local_name = btf__name_by_offset(local_btf,
4316 local_type->name_off);
4317 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
4318 local_len = bpf_core_essential_name_len(local_name);
4319 targ_len = bpf_core_essential_name_len(targ_name);
4320 /* one of them is anonymous or both w/ same flavor-less names */
4321 return local_len == 0 || targ_len == 0 ||
4322 (local_len == targ_len &&
4323 strncmp(local_name, targ_name, local_len) == 0);
4326 /* just reject deprecated bitfield-like integers; all other
4327 * integers are by default compatible between each other
4329 return btf_int_offset(local_type) == 0 &&
4330 btf_int_offset(targ_type) == 0;
4331 case BTF_KIND_ARRAY:
4332 local_id = btf_array(local_type)->type;
4333 targ_id = btf_array(targ_type)->type;
4336 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
4337 btf_kind(local_type), local_id, targ_id);
4343 * Given single high-level named field accessor in local type, find
4344 * corresponding high-level accessor for a target type. Along the way,
4345 * maintain low-level spec for target as well. Also keep updating target
4348 * Searching is performed through recursive exhaustive enumeration of all
4349 * fields of a struct/union. If there are any anonymous (embedded)
4350 * structs/unions, they are recursively searched as well. If field with
4351 * desired name is found, check compatibility between local and target types,
4352 * before returning result.
4354 * 1 is returned, if field is found.
4355 * 0 is returned if no compatible field is found.
4356 * <0 is returned on error.
4358 static int bpf_core_match_member(const struct btf *local_btf,
4359 const struct bpf_core_accessor *local_acc,
4360 const struct btf *targ_btf,
4362 struct bpf_core_spec *spec,
4363 __u32 *next_targ_id)
4365 const struct btf_type *local_type, *targ_type;
4366 const struct btf_member *local_member, *m;
4367 const char *local_name, *targ_name;
4371 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4374 if (!btf_is_composite(targ_type))
4377 local_id = local_acc->type_id;
4378 local_type = btf__type_by_id(local_btf, local_id);
4379 local_member = btf_members(local_type) + local_acc->idx;
4380 local_name = btf__name_by_offset(local_btf, local_member->name_off);
4382 n = btf_vlen(targ_type);
4383 m = btf_members(targ_type);
4384 for (i = 0; i < n; i++, m++) {
4387 bit_offset = btf_member_bit_offset(targ_type, i);
4389 /* too deep struct/union/array nesting */
4390 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4393 /* speculate this member will be the good one */
4394 spec->bit_offset += bit_offset;
4395 spec->raw_spec[spec->raw_len++] = i;
4397 targ_name = btf__name_by_offset(targ_btf, m->name_off);
4398 if (str_is_empty(targ_name)) {
4399 /* embedded struct/union, we need to go deeper */
4400 found = bpf_core_match_member(local_btf, local_acc,
4402 spec, next_targ_id);
4403 if (found) /* either found or error */
4405 } else if (strcmp(local_name, targ_name) == 0) {
4406 /* matching named field */
4407 struct bpf_core_accessor *targ_acc;
4409 targ_acc = &spec->spec[spec->len++];
4410 targ_acc->type_id = targ_id;
4412 targ_acc->name = targ_name;
4414 *next_targ_id = m->type;
4415 found = bpf_core_fields_are_compat(local_btf,
4419 spec->len--; /* pop accessor */
4422 /* member turned out not to be what we looked for */
4423 spec->bit_offset -= bit_offset;
4431 * Try to match local spec to a target type and, if successful, produce full
4432 * target spec (high-level, low-level + bit offset).
4434 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4435 const struct btf *targ_btf, __u32 targ_id,
4436 struct bpf_core_spec *targ_spec)
4438 const struct btf_type *targ_type;
4439 const struct bpf_core_accessor *local_acc;
4440 struct bpf_core_accessor *targ_acc;
4443 memset(targ_spec, 0, sizeof(*targ_spec));
4444 targ_spec->btf = targ_btf;
4446 local_acc = &local_spec->spec[0];
4447 targ_acc = &targ_spec->spec[0];
4449 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
4450 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
4455 if (local_acc->name) {
4456 matched = bpf_core_match_member(local_spec->btf,
4459 targ_spec, &targ_id);
4463 /* for i=0, targ_id is already treated as array element
4464 * type (because it's the original struct), for others
4465 * we should find array element type first
4468 const struct btf_array *a;
4471 if (!btf_is_array(targ_type))
4474 a = btf_array(targ_type);
4475 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
4476 if (!flex && local_acc->idx >= a->nelems)
4478 if (!skip_mods_and_typedefs(targ_btf, a->type,
4483 /* too deep struct/union/array nesting */
4484 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4487 targ_acc->type_id = targ_id;
4488 targ_acc->idx = local_acc->idx;
4489 targ_acc->name = NULL;
4491 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
4492 targ_spec->raw_len++;
4494 sz = btf__resolve_size(targ_btf, targ_id);
4497 targ_spec->bit_offset += local_acc->idx * sz * 8;
4504 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
4505 const struct bpf_field_reloc *relo,
4506 const struct bpf_core_spec *spec,
4507 __u32 *val, bool *validate)
4509 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
4510 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
4511 __u32 byte_off, byte_sz, bit_off, bit_sz;
4512 const struct btf_member *m;
4513 const struct btf_type *mt;
4517 /* a[n] accessor needs special handling */
4519 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
4520 *val = spec->bit_offset / 8;
4521 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
4522 sz = btf__resolve_size(spec->btf, acc->type_id);
4527 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4528 bpf_program__title(prog, false),
4529 relo->kind, relo->insn_off / 8);
4537 m = btf_members(t) + acc->idx;
4538 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
4539 bit_off = spec->bit_offset;
4540 bit_sz = btf_member_bitfield_size(t, acc->idx);
4542 bitfield = bit_sz > 0;
4545 byte_off = bit_off / 8 / byte_sz * byte_sz;
4546 /* figure out smallest int size necessary for bitfield load */
4547 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
4549 /* bitfield can't be read with 64-bit read */
4550 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4551 bpf_program__title(prog, false),
4552 relo->kind, relo->insn_off / 8);
4556 byte_off = bit_off / 8 / byte_sz * byte_sz;
4559 sz = btf__resolve_size(spec->btf, m->type);
4563 byte_off = spec->bit_offset / 8;
4564 bit_sz = byte_sz * 8;
4567 /* for bitfields, all the relocatable aspects are ambiguous and we
4568 * might disagree with compiler, so turn off validation of expected
4569 * value, except for signedness
4572 *validate = !bitfield;
4574 switch (relo->kind) {
4575 case BPF_FIELD_BYTE_OFFSET:
4578 case BPF_FIELD_BYTE_SIZE:
4581 case BPF_FIELD_SIGNED:
4582 /* enums will be assumed unsigned */
4583 *val = btf_is_enum(mt) ||
4584 (btf_int_encoding(mt) & BTF_INT_SIGNED);
4586 *validate = true; /* signedness is never ambiguous */
4588 case BPF_FIELD_LSHIFT_U64:
4589 #if __BYTE_ORDER == __LITTLE_ENDIAN
4590 *val = 64 - (bit_off + bit_sz - byte_off * 8);
4592 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
4595 case BPF_FIELD_RSHIFT_U64:
4598 *validate = true; /* right shift is never ambiguous */
4600 case BPF_FIELD_EXISTS:
4602 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4603 bpf_program__title(prog, false),
4604 relo->kind, relo->insn_off / 8);
4612 * Patch relocatable BPF instruction.
4614 * Patched value is determined by relocation kind and target specification.
4615 * For field existence relocation target spec will be NULL if field is not
4617 * Expected insn->imm value is determined using relocation kind and local
4618 * spec, and is checked before patching instruction. If actual insn->imm value
4619 * is wrong, bail out with error.
4621 * Currently three kinds of BPF instructions are supported:
4622 * 1. rX = <imm> (assignment with immediate operand);
4623 * 2. rX += <imm> (arithmetic operations with immediate operand);
4625 static int bpf_core_reloc_insn(struct bpf_program *prog,
4626 const struct bpf_field_reloc *relo,
4628 const struct bpf_core_spec *local_spec,
4629 const struct bpf_core_spec *targ_spec)
4631 __u32 orig_val, new_val;
4632 struct bpf_insn *insn;
4633 bool validate = true;
4637 if (relo->insn_off % sizeof(struct bpf_insn))
4639 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
4640 insn = &prog->insns[insn_idx];
4641 class = BPF_CLASS(insn->code);
4643 if (relo->kind == BPF_FIELD_EXISTS) {
4644 orig_val = 1; /* can't generate EXISTS relo w/o local field */
4645 new_val = targ_spec ? 1 : 0;
4646 } else if (!targ_spec) {
4647 pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
4648 bpf_program__title(prog, false), relo_idx, insn_idx);
4649 insn->code = BPF_JMP | BPF_CALL;
4653 /* if this instruction is reachable (not a dead code),
4654 * verifier will complain with the following message:
4655 * invalid func unknown#195896080
4657 insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
4660 err = bpf_core_calc_field_relo(prog, relo, local_spec,
4661 &orig_val, &validate);
4664 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
4673 if (BPF_SRC(insn->code) != BPF_K)
4675 if (validate && insn->imm != orig_val) {
4676 pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4677 bpf_program__title(prog, false), relo_idx,
4678 insn_idx, insn->imm, orig_val, new_val);
4681 orig_val = insn->imm;
4682 insn->imm = new_val;
4683 pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
4684 bpf_program__title(prog, false), relo_idx, insn_idx,
4690 if (validate && insn->off != orig_val) {
4691 pr_warn("prog '%s': relo #%d: unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4692 bpf_program__title(prog, false), relo_idx,
4693 insn_idx, insn->off, orig_val, new_val);
4696 if (new_val > SHRT_MAX) {
4697 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
4698 bpf_program__title(prog, false), relo_idx,
4702 orig_val = insn->off;
4703 insn->off = new_val;
4704 pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
4705 bpf_program__title(prog, false), relo_idx, insn_idx,
4709 pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4710 bpf_program__title(prog, false), relo_idx,
4711 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
4712 insn->off, insn->imm);
4719 /* Output spec definition in the format:
4720 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4721 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4723 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
4725 const struct btf_type *t;
4730 type_id = spec->spec[0].type_id;
4731 t = btf__type_by_id(spec->btf, type_id);
4732 s = btf__name_by_offset(spec->btf, t->name_off);
4733 libbpf_print(level, "[%u] %s + ", type_id, s);
4735 for (i = 0; i < spec->raw_len; i++)
4736 libbpf_print(level, "%d%s", spec->raw_spec[i],
4737 i == spec->raw_len - 1 ? " => " : ":");
4739 libbpf_print(level, "%u.%u @ &x",
4740 spec->bit_offset / 8, spec->bit_offset % 8);
4742 for (i = 0; i < spec->len; i++) {
4743 if (spec->spec[i].name)
4744 libbpf_print(level, ".%s", spec->spec[i].name);
4746 libbpf_print(level, "[%u]", spec->spec[i].idx);
4751 static size_t bpf_core_hash_fn(const void *key, void *ctx)
4756 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
4761 static void *u32_as_hash_key(__u32 x)
4763 return (void *)(uintptr_t)x;
4767 * CO-RE relocate single instruction.
4769 * The outline and important points of the algorithm:
4770 * 1. For given local type, find corresponding candidate target types.
4771 * Candidate type is a type with the same "essential" name, ignoring
4772 * everything after last triple underscore (___). E.g., `sample`,
4773 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4774 * for each other. Names with triple underscore are referred to as
4775 * "flavors" and are useful, among other things, to allow to
4776 * specify/support incompatible variations of the same kernel struct, which
4777 * might differ between different kernel versions and/or build
4780 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4781 * converter, when deduplicated BTF of a kernel still contains more than
4782 * one different types with the same name. In that case, ___2, ___3, etc
4783 * are appended starting from second name conflict. But start flavors are
4784 * also useful to be defined "locally", in BPF program, to extract same
4785 * data from incompatible changes between different kernel
4786 * versions/configurations. For instance, to handle field renames between
4787 * kernel versions, one can use two flavors of the struct name with the
4788 * same common name and use conditional relocations to extract that field,
4789 * depending on target kernel version.
4790 * 2. For each candidate type, try to match local specification to this
4791 * candidate target type. Matching involves finding corresponding
4792 * high-level spec accessors, meaning that all named fields should match,
4793 * as well as all array accesses should be within the actual bounds. Also,
4794 * types should be compatible (see bpf_core_fields_are_compat for details).
4795 * 3. It is supported and expected that there might be multiple flavors
4796 * matching the spec. As long as all the specs resolve to the same set of
4797 * offsets across all candidates, there is no error. If there is any
4798 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4799 * imprefection of BTF deduplication, which can cause slight duplication of
4800 * the same BTF type, if some directly or indirectly referenced (by
4801 * pointer) type gets resolved to different actual types in different
4802 * object files. If such situation occurs, deduplicated BTF will end up
4803 * with two (or more) structurally identical types, which differ only in
4804 * types they refer to through pointer. This should be OK in most cases and
4806 * 4. Candidate types search is performed by linearly scanning through all
4807 * types in target BTF. It is anticipated that this is overall more
4808 * efficient memory-wise and not significantly worse (if not better)
4809 * CPU-wise compared to prebuilding a map from all local type names to
4810 * a list of candidate type names. It's also sped up by caching resolved
4811 * list of matching candidates per each local "root" type ID, that has at
4812 * least one bpf_field_reloc associated with it. This list is shared
4813 * between multiple relocations for the same type ID and is updated as some
4814 * of the candidates are pruned due to structural incompatibility.
4816 static int bpf_core_reloc_field(struct bpf_program *prog,
4817 const struct bpf_field_reloc *relo,
4819 const struct btf *local_btf,
4820 const struct btf *targ_btf,
4821 struct hashmap *cand_cache)
4823 const char *prog_name = bpf_program__title(prog, false);
4824 struct bpf_core_spec local_spec, cand_spec, targ_spec;
4825 const void *type_key = u32_as_hash_key(relo->type_id);
4826 const struct btf_type *local_type, *cand_type;
4827 const char *local_name, *cand_name;
4828 struct ids_vec *cand_ids;
4829 __u32 local_id, cand_id;
4830 const char *spec_str;
4833 local_id = relo->type_id;
4834 local_type = btf__type_by_id(local_btf, local_id);
4838 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4839 if (str_is_empty(local_name))
4842 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4843 if (str_is_empty(spec_str))
4846 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4848 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4849 prog_name, relo_idx, local_id, local_name, spec_str,
4854 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4856 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4857 libbpf_print(LIBBPF_DEBUG, "\n");
4859 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4860 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4861 if (IS_ERR(cand_ids)) {
4862 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4863 prog_name, relo_idx, local_id, local_name,
4865 return PTR_ERR(cand_ids);
4867 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4869 bpf_core_free_cands(cand_ids);
4874 for (i = 0, j = 0; i < cand_ids->len; i++) {
4875 cand_id = cand_ids->data[i];
4876 cand_type = btf__type_by_id(targ_btf, cand_id);
4877 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4879 err = bpf_core_spec_match(&local_spec, targ_btf,
4880 cand_id, &cand_spec);
4881 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4882 prog_name, relo_idx, i, cand_name);
4883 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4884 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4886 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4887 prog_name, relo_idx, err);
4894 targ_spec = cand_spec;
4895 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4896 /* if there are many candidates, they should all
4897 * resolve to the same bit offset
4899 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4900 prog_name, relo_idx, cand_spec.bit_offset,
4901 targ_spec.bit_offset);
4905 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4909 * For BPF_FIELD_EXISTS relo or when used BPF program has field
4910 * existence checks or kernel version/config checks, it's expected
4911 * that we might not find any candidates. In this case, if field
4912 * wasn't found in any candidate, the list of candidates shouldn't
4913 * change at all, we'll just handle relocating appropriately,
4914 * depending on relo's kind.
4920 * If no candidates were found, it might be both a programmer error,
4921 * as well as expected case, depending whether instruction w/
4922 * relocation is guarded in some way that makes it unreachable (dead
4923 * code) if relocation can't be resolved. This is handled in
4924 * bpf_core_reloc_insn() uniformly by replacing that instruction with
4925 * BPF helper call insn (using invalid helper ID). If that instruction
4926 * is indeed unreachable, then it will be ignored and eliminated by
4927 * verifier. If it was an error, then verifier will complain and point
4928 * to a specific instruction number in its log.
4931 pr_debug("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4932 prog_name, relo_idx, local_id, local_name, spec_str);
4934 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4935 err = bpf_core_reloc_insn(prog, relo, relo_idx, &local_spec,
4936 j ? &targ_spec : NULL);
4938 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4939 prog_name, relo_idx, relo->insn_off, err);
4947 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4949 const struct btf_ext_info_sec *sec;
4950 const struct bpf_field_reloc *rec;
4951 const struct btf_ext_info *seg;
4952 struct hashmap_entry *entry;
4953 struct hashmap *cand_cache = NULL;
4954 struct bpf_program *prog;
4955 struct btf *targ_btf;
4956 const char *sec_name;
4960 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4962 targ_btf = obj->btf_vmlinux;
4963 if (IS_ERR_OR_NULL(targ_btf)) {
4964 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4965 return PTR_ERR(targ_btf);
4968 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4969 if (IS_ERR(cand_cache)) {
4970 err = PTR_ERR(cand_cache);
4974 seg = &obj->btf_ext->field_reloc_info;
4975 for_each_btf_ext_sec(seg, sec) {
4976 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4977 if (str_is_empty(sec_name)) {
4982 for (i = 0; i < obj->nr_programs; i++) {
4983 if (!strcmp(obj->programs[i].section_name, sec_name)) {
4984 prog = &obj->programs[i];
4989 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4995 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4996 sec_name, sec->num_info);
4998 for_each_btf_ext_rec(seg, sec, i, rec) {
4999 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
5000 targ_btf, cand_cache);
5002 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5010 /* obj->btf_vmlinux is freed at the end of object load phase */
5011 if (targ_btf != obj->btf_vmlinux)
5012 btf__free(targ_btf);
5013 if (!IS_ERR_OR_NULL(cand_cache)) {
5014 hashmap__for_each_entry(cand_cache, entry, i) {
5015 bpf_core_free_cands(entry->value);
5017 hashmap__free(cand_cache);
5023 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5027 if (obj->btf_ext->field_reloc_info.len)
5028 err = bpf_core_reloc_fields(obj, targ_btf_path);
5034 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
5035 struct reloc_desc *relo)
5037 struct bpf_insn *insn, *new_insn;
5038 struct bpf_program *text;
5042 if (prog->idx != obj->efile.text_shndx && prog->main_prog_cnt == 0) {
5043 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
5045 pr_warn("no .text section found yet relo into text exist\n");
5046 return -LIBBPF_ERRNO__RELOC;
5048 new_cnt = prog->insns_cnt + text->insns_cnt;
5049 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
5051 pr_warn("oom in prog realloc\n");
5054 prog->insns = new_insn;
5057 err = bpf_program_reloc_btf_ext(prog, obj,
5064 memcpy(new_insn + prog->insns_cnt, text->insns,
5065 text->insns_cnt * sizeof(*insn));
5066 prog->main_prog_cnt = prog->insns_cnt;
5067 prog->insns_cnt = new_cnt;
5068 pr_debug("added %zd insn from %s to prog %s\n",
5069 text->insns_cnt, text->section_name,
5070 prog->section_name);
5073 insn = &prog->insns[relo->insn_idx];
5074 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
5079 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
5087 err = bpf_program_reloc_btf_ext(prog, obj,
5088 prog->section_name, 0);
5093 if (!prog->reloc_desc)
5096 for (i = 0; i < prog->nr_reloc; i++) {
5097 struct reloc_desc *relo = &prog->reloc_desc[i];
5098 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5099 struct extern_desc *ext;
5101 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
5102 pr_warn("relocation out of range: '%s'\n",
5103 prog->section_name);
5104 return -LIBBPF_ERRNO__RELOC;
5107 switch (relo->type) {
5109 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5110 insn[0].imm = obj->maps[relo->map_idx].fd;
5113 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5114 insn[1].imm = insn[0].imm + relo->sym_off;
5115 insn[0].imm = obj->maps[relo->map_idx].fd;
5118 ext = &obj->externs[relo->sym_off];
5119 if (ext->type == EXT_KCFG) {
5120 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5121 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5122 insn[1].imm = ext->kcfg.data_off;
5123 } else /* EXT_KSYM */ {
5124 insn[0].imm = (__u32)ext->ksym.addr;
5125 insn[1].imm = ext->ksym.addr >> 32;
5129 err = bpf_program__reloc_text(prog, obj, relo);
5134 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
5139 zfree(&prog->reloc_desc);
5145 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
5147 struct bpf_program *prog;
5152 err = bpf_object__relocate_core(obj, targ_btf_path);
5154 pr_warn("failed to perform CO-RE relocations: %d\n",
5159 /* ensure .text is relocated first, as it's going to be copied as-is
5160 * later for sub-program calls
5162 for (i = 0; i < obj->nr_programs; i++) {
5163 prog = &obj->programs[i];
5164 if (prog->idx != obj->efile.text_shndx)
5167 err = bpf_program__relocate(prog, obj);
5169 pr_warn("failed to relocate '%s'\n", prog->section_name);
5174 /* now relocate everything but .text, which by now is relocated
5175 * properly, so we can copy raw sub-program instructions as is safely
5177 for (i = 0; i < obj->nr_programs; i++) {
5178 prog = &obj->programs[i];
5179 if (prog->idx == obj->efile.text_shndx)
5182 err = bpf_program__relocate(prog, obj);
5184 pr_warn("failed to relocate '%s'\n", prog->section_name);
5191 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5192 GElf_Shdr *shdr, Elf_Data *data);
5194 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5195 GElf_Shdr *shdr, Elf_Data *data)
5197 int i, j, nrels, new_sz, ptr_sz = sizeof(void *);
5198 const struct btf_var_secinfo *vi = NULL;
5199 const struct btf_type *sec, *var, *def;
5200 const struct btf_member *member;
5201 struct bpf_map *map, *targ_map;
5202 const char *name, *mname;
5209 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5211 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5215 symbols = obj->efile.symbols;
5216 nrels = shdr->sh_size / shdr->sh_entsize;
5217 for (i = 0; i < nrels; i++) {
5218 if (!gelf_getrel(data, i, &rel)) {
5219 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5220 return -LIBBPF_ERRNO__FORMAT;
5222 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5223 pr_warn(".maps relo #%d: symbol %zx not found\n",
5224 i, (size_t)GELF_R_SYM(rel.r_info));
5225 return -LIBBPF_ERRNO__FORMAT;
5227 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
5228 sym.st_name) ? : "<?>";
5229 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5230 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5232 return -LIBBPF_ERRNO__RELOC;
5235 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5236 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5237 (size_t)rel.r_offset, sym.st_name, name);
5239 for (j = 0; j < obj->nr_maps; j++) {
5240 map = &obj->maps[j];
5241 if (map->sec_idx != obj->efile.btf_maps_shndx)
5244 vi = btf_var_secinfos(sec) + map->btf_var_idx;
5245 if (vi->offset <= rel.r_offset &&
5246 rel.r_offset + sizeof(void *) <= vi->offset + vi->size)
5249 if (j == obj->nr_maps) {
5250 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5251 i, name, (size_t)rel.r_offset);
5255 if (!bpf_map_type__is_map_in_map(map->def.type))
5257 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5258 map->def.key_size != sizeof(int)) {
5259 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5260 i, map->name, sizeof(int));
5264 targ_map = bpf_object__find_map_by_name(obj, name);
5268 var = btf__type_by_id(obj->btf, vi->type);
5269 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5270 if (btf_vlen(def) == 0)
5272 member = btf_members(def) + btf_vlen(def) - 1;
5273 mname = btf__name_by_offset(obj->btf, member->name_off);
5274 if (strcmp(mname, "values"))
5277 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5278 if (rel.r_offset - vi->offset < moff)
5281 moff = rel.r_offset - vi->offset - moff;
5285 if (moff >= map->init_slots_sz) {
5287 tmp = realloc(map->init_slots, new_sz * ptr_sz);
5290 map->init_slots = tmp;
5291 memset(map->init_slots + map->init_slots_sz, 0,
5292 (new_sz - map->init_slots_sz) * ptr_sz);
5293 map->init_slots_sz = new_sz;
5295 map->init_slots[moff] = targ_map;
5297 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5298 i, map->name, moff, name);
5304 static int bpf_object__collect_reloc(struct bpf_object *obj)
5308 if (!obj_elf_valid(obj)) {
5309 pr_warn("Internal error: elf object is closed\n");
5310 return -LIBBPF_ERRNO__INTERNAL;
5313 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5314 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5315 Elf_Data *data = obj->efile.reloc_sects[i].data;
5316 int idx = shdr->sh_info;
5317 struct bpf_program *prog;
5319 if (shdr->sh_type != SHT_REL) {
5320 pr_warn("internal error at %d\n", __LINE__);
5321 return -LIBBPF_ERRNO__INTERNAL;
5324 if (idx == obj->efile.st_ops_shndx) {
5325 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
5326 } else if (idx == obj->efile.btf_maps_shndx) {
5327 err = bpf_object__collect_map_relos(obj, shdr, data);
5329 prog = bpf_object__find_prog_by_idx(obj, idx);
5331 pr_warn("relocation failed: no prog in section(%d)\n", idx);
5332 return -LIBBPF_ERRNO__RELOC;
5334 err = bpf_program__collect_reloc(prog, shdr, data, obj);
5343 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
5344 char *license, __u32 kern_version, int *pfd)
5346 struct bpf_load_program_attr load_attr;
5347 char *cp, errmsg[STRERR_BUFSIZE];
5348 size_t log_buf_size = 0;
5349 char *log_buf = NULL;
5352 if (!insns || !insns_cnt)
5355 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
5356 load_attr.prog_type = prog->type;
5357 /* old kernels might not support specifying expected_attach_type */
5358 if (!prog->caps->exp_attach_type && prog->sec_def &&
5359 prog->sec_def->is_exp_attach_type_optional)
5360 load_attr.expected_attach_type = 0;
5362 load_attr.expected_attach_type = prog->expected_attach_type;
5363 if (prog->caps->name)
5364 load_attr.name = prog->name;
5365 load_attr.insns = insns;
5366 load_attr.insns_cnt = insns_cnt;
5367 load_attr.license = license;
5368 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
5369 prog->type == BPF_PROG_TYPE_LSM) {
5370 load_attr.attach_btf_id = prog->attach_btf_id;
5371 } else if (prog->type == BPF_PROG_TYPE_TRACING ||
5372 prog->type == BPF_PROG_TYPE_EXT) {
5373 load_attr.attach_prog_fd = prog->attach_prog_fd;
5374 load_attr.attach_btf_id = prog->attach_btf_id;
5376 load_attr.kern_version = kern_version;
5377 load_attr.prog_ifindex = prog->prog_ifindex;
5379 /* specify func_info/line_info only if kernel supports them */
5380 btf_fd = bpf_object__btf_fd(prog->obj);
5381 if (btf_fd >= 0 && prog->obj->caps.btf_func) {
5382 load_attr.prog_btf_fd = btf_fd;
5383 load_attr.func_info = prog->func_info;
5384 load_attr.func_info_rec_size = prog->func_info_rec_size;
5385 load_attr.func_info_cnt = prog->func_info_cnt;
5386 load_attr.line_info = prog->line_info;
5387 load_attr.line_info_rec_size = prog->line_info_rec_size;
5388 load_attr.line_info_cnt = prog->line_info_cnt;
5390 load_attr.log_level = prog->log_level;
5391 load_attr.prog_flags = prog->prog_flags;
5395 log_buf = malloc(log_buf_size);
5402 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
5405 if (log_buf && load_attr.log_level)
5406 pr_debug("verifier log:\n%s", log_buf);
5412 if (!log_buf || errno == ENOSPC) {
5413 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
5420 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5421 pr_warn("load bpf program failed: %s\n", cp);
5424 if (log_buf && log_buf[0] != '\0') {
5425 ret = -LIBBPF_ERRNO__VERIFY;
5426 pr_warn("-- BEGIN DUMP LOG ---\n");
5427 pr_warn("\n%s\n", log_buf);
5428 pr_warn("-- END LOG --\n");
5429 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
5430 pr_warn("Program too large (%zu insns), at most %d insns\n",
5431 load_attr.insns_cnt, BPF_MAXINSNS);
5432 ret = -LIBBPF_ERRNO__PROG2BIG;
5433 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
5434 /* Wrong program type? */
5437 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
5438 load_attr.expected_attach_type = 0;
5439 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
5442 ret = -LIBBPF_ERRNO__PROGTYPE;
5452 static int libbpf_find_attach_btf_id(struct bpf_program *prog);
5454 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
5456 int err = 0, fd, i, btf_id;
5458 if (prog->obj->loaded) {
5459 pr_warn("prog '%s'('%s'): can't load after object was loaded\n",
5460 prog->name, prog->section_name);
5464 if ((prog->type == BPF_PROG_TYPE_TRACING ||
5465 prog->type == BPF_PROG_TYPE_LSM ||
5466 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
5467 btf_id = libbpf_find_attach_btf_id(prog);
5470 prog->attach_btf_id = btf_id;
5473 if (prog->instances.nr < 0 || !prog->instances.fds) {
5474 if (prog->preprocessor) {
5475 pr_warn("Internal error: can't load program '%s'\n",
5476 prog->section_name);
5477 return -LIBBPF_ERRNO__INTERNAL;
5480 prog->instances.fds = malloc(sizeof(int));
5481 if (!prog->instances.fds) {
5482 pr_warn("Not enough memory for BPF fds\n");
5485 prog->instances.nr = 1;
5486 prog->instances.fds[0] = -1;
5489 if (!prog->preprocessor) {
5490 if (prog->instances.nr != 1) {
5491 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
5492 prog->section_name, prog->instances.nr);
5494 err = load_program(prog, prog->insns, prog->insns_cnt,
5495 license, kern_ver, &fd);
5497 prog->instances.fds[0] = fd;
5501 for (i = 0; i < prog->instances.nr; i++) {
5502 struct bpf_prog_prep_result result;
5503 bpf_program_prep_t preprocessor = prog->preprocessor;
5505 memset(&result, 0, sizeof(result));
5506 err = preprocessor(prog, i, prog->insns,
5507 prog->insns_cnt, &result);
5509 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
5510 i, prog->section_name);
5514 if (!result.new_insn_ptr || !result.new_insn_cnt) {
5515 pr_debug("Skip loading the %dth instance of program '%s'\n",
5516 i, prog->section_name);
5517 prog->instances.fds[i] = -1;
5523 err = load_program(prog, result.new_insn_ptr,
5524 result.new_insn_cnt, license, kern_ver, &fd);
5526 pr_warn("Loading the %dth instance of program '%s' failed\n",
5527 i, prog->section_name);
5533 prog->instances.fds[i] = fd;
5537 pr_warn("failed to load program '%s'\n", prog->section_name);
5538 zfree(&prog->insns);
5539 prog->insns_cnt = 0;
5543 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
5544 const struct bpf_object *obj)
5546 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
5550 bpf_object__load_progs(struct bpf_object *obj, int log_level)
5552 struct bpf_program *prog;
5556 for (i = 0; i < obj->nr_programs; i++) {
5557 prog = &obj->programs[i];
5558 if (bpf_program__is_function_storage(prog, obj))
5561 pr_debug("prog '%s'('%s'): skipped loading\n",
5562 prog->name, prog->section_name);
5565 prog->log_level |= log_level;
5566 err = bpf_program__load(prog, obj->license, obj->kern_version);
5573 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
5575 static struct bpf_object *
5576 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
5577 const struct bpf_object_open_opts *opts)
5579 const char *obj_name, *kconfig;
5580 struct bpf_program *prog;
5581 struct bpf_object *obj;
5585 if (elf_version(EV_CURRENT) == EV_NONE) {
5586 pr_warn("failed to init libelf for %s\n",
5587 path ? : "(mem buf)");
5588 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
5591 if (!OPTS_VALID(opts, bpf_object_open_opts))
5592 return ERR_PTR(-EINVAL);
5594 obj_name = OPTS_GET(opts, object_name, NULL);
5597 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
5598 (unsigned long)obj_buf,
5599 (unsigned long)obj_buf_sz);
5600 obj_name = tmp_name;
5603 pr_debug("loading object '%s' from buffer\n", obj_name);
5606 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
5610 kconfig = OPTS_GET(opts, kconfig, NULL);
5612 obj->kconfig = strdup(kconfig);
5614 return ERR_PTR(-ENOMEM);
5617 err = bpf_object__elf_init(obj);
5618 err = err ? : bpf_object__check_endianness(obj);
5619 err = err ? : bpf_object__elf_collect(obj);
5620 err = err ? : bpf_object__collect_externs(obj);
5621 err = err ? : bpf_object__finalize_btf(obj);
5622 err = err ? : bpf_object__init_maps(obj, opts);
5623 err = err ? : bpf_object__init_prog_names(obj);
5624 err = err ? : bpf_object__collect_reloc(obj);
5627 bpf_object__elf_finish(obj);
5629 bpf_object__for_each_program(prog, obj) {
5630 prog->sec_def = find_sec_def(prog->section_name);
5632 /* couldn't guess, but user might manually specify */
5635 bpf_program__set_type(prog, prog->sec_def->prog_type);
5636 bpf_program__set_expected_attach_type(prog,
5637 prog->sec_def->expected_attach_type);
5639 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
5640 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
5641 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
5646 bpf_object__close(obj);
5647 return ERR_PTR(err);
5650 static struct bpf_object *
5651 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
5653 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5654 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
5657 /* param validation */
5661 pr_debug("loading %s\n", attr->file);
5662 return __bpf_object__open(attr->file, NULL, 0, &opts);
5665 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
5667 return __bpf_object__open_xattr(attr, 0);
5670 struct bpf_object *bpf_object__open(const char *path)
5672 struct bpf_object_open_attr attr = {
5674 .prog_type = BPF_PROG_TYPE_UNSPEC,
5677 return bpf_object__open_xattr(&attr);
5681 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
5684 return ERR_PTR(-EINVAL);
5686 pr_debug("loading %s\n", path);
5688 return __bpf_object__open(path, NULL, 0, opts);
5692 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
5693 const struct bpf_object_open_opts *opts)
5695 if (!obj_buf || obj_buf_sz == 0)
5696 return ERR_PTR(-EINVAL);
5698 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
5702 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
5705 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5706 .object_name = name,
5707 /* wrong default, but backwards-compatible */
5708 .relaxed_maps = true,
5711 /* returning NULL is wrong, but backwards-compatible */
5712 if (!obj_buf || obj_buf_sz == 0)
5715 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
5718 int bpf_object__unload(struct bpf_object *obj)
5725 for (i = 0; i < obj->nr_maps; i++) {
5726 zclose(obj->maps[i].fd);
5727 if (obj->maps[i].st_ops)
5728 zfree(&obj->maps[i].st_ops->kern_vdata);
5731 for (i = 0; i < obj->nr_programs; i++)
5732 bpf_program__unload(&obj->programs[i]);
5737 static int bpf_object__sanitize_maps(struct bpf_object *obj)
5741 bpf_object__for_each_map(m, obj) {
5742 if (!bpf_map__is_internal(m))
5744 if (!obj->caps.global_data) {
5745 pr_warn("kernel doesn't support global data\n");
5748 if (!obj->caps.array_mmap)
5749 m->def.map_flags ^= BPF_F_MMAPABLE;
5755 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
5757 char sym_type, sym_name[500];
5758 unsigned long long sym_addr;
5759 struct extern_desc *ext;
5763 f = fopen("/proc/kallsyms", "r");
5766 pr_warn("failed to open /proc/kallsyms: %d\n", err);
5771 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
5772 &sym_addr, &sym_type, sym_name);
5773 if (ret == EOF && feof(f))
5776 pr_warn("failed to read kallsyms entry: %d\n", ret);
5781 ext = find_extern_by_name(obj, sym_name);
5782 if (!ext || ext->type != EXT_KSYM)
5785 if (ext->is_set && ext->ksym.addr != sym_addr) {
5786 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
5787 sym_name, ext->ksym.addr, sym_addr);
5793 ext->ksym.addr = sym_addr;
5794 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
5803 static int bpf_object__resolve_externs(struct bpf_object *obj,
5804 const char *extra_kconfig)
5806 bool need_config = false, need_kallsyms = false;
5807 struct extern_desc *ext;
5808 void *kcfg_data = NULL;
5811 if (obj->nr_extern == 0)
5814 if (obj->kconfig_map_idx >= 0)
5815 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
5817 for (i = 0; i < obj->nr_extern; i++) {
5818 ext = &obj->externs[i];
5820 if (ext->type == EXT_KCFG &&
5821 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
5822 void *ext_val = kcfg_data + ext->kcfg.data_off;
5823 __u32 kver = get_kernel_version();
5826 pr_warn("failed to get kernel version\n");
5829 err = set_kcfg_value_num(ext, ext_val, kver);
5832 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
5833 } else if (ext->type == EXT_KCFG &&
5834 strncmp(ext->name, "CONFIG_", 7) == 0) {
5836 } else if (ext->type == EXT_KSYM) {
5837 need_kallsyms = true;
5839 pr_warn("unrecognized extern '%s'\n", ext->name);
5843 if (need_config && extra_kconfig) {
5844 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
5847 need_config = false;
5848 for (i = 0; i < obj->nr_extern; i++) {
5849 ext = &obj->externs[i];
5850 if (ext->type == EXT_KCFG && !ext->is_set) {
5857 err = bpf_object__read_kconfig_file(obj, kcfg_data);
5861 if (need_kallsyms) {
5862 err = bpf_object__read_kallsyms_file(obj);
5866 for (i = 0; i < obj->nr_extern; i++) {
5867 ext = &obj->externs[i];
5869 if (!ext->is_set && !ext->is_weak) {
5870 pr_warn("extern %s (strong) not resolved\n", ext->name);
5872 } else if (!ext->is_set) {
5873 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5881 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
5883 struct bpf_object *obj;
5893 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
5897 err = bpf_object__probe_loading(obj);
5898 err = err ? : bpf_object__probe_caps(obj);
5899 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
5900 err = err ? : bpf_object__sanitize_and_load_btf(obj);
5901 err = err ? : bpf_object__sanitize_maps(obj);
5902 err = err ? : bpf_object__load_vmlinux_btf(obj);
5903 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
5904 err = err ? : bpf_object__create_maps(obj);
5905 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
5906 err = err ? : bpf_object__load_progs(obj, attr->log_level);
5908 btf__free(obj->btf_vmlinux);
5909 obj->btf_vmlinux = NULL;
5911 obj->loaded = true; /* doesn't matter if successfully or not */
5918 /* unpin any maps that were auto-pinned during load */
5919 for (i = 0; i < obj->nr_maps; i++)
5920 if (obj->maps[i].pinned && !obj->maps[i].reused)
5921 bpf_map__unpin(&obj->maps[i], NULL);
5923 bpf_object__unload(obj);
5924 pr_warn("failed to load object '%s'\n", obj->path);
5928 int bpf_object__load(struct bpf_object *obj)
5930 struct bpf_object_load_attr attr = {
5934 return bpf_object__load_xattr(&attr);
5937 static int make_parent_dir(const char *path)
5939 char *cp, errmsg[STRERR_BUFSIZE];
5943 dname = strdup(path);
5947 dir = dirname(dname);
5948 if (mkdir(dir, 0700) && errno != EEXIST)
5953 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5954 pr_warn("failed to mkdir %s: %s\n", path, cp);
5959 static int check_path(const char *path)
5961 char *cp, errmsg[STRERR_BUFSIZE];
5962 struct statfs st_fs;
5969 dname = strdup(path);
5973 dir = dirname(dname);
5974 if (statfs(dir, &st_fs)) {
5975 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5976 pr_warn("failed to statfs %s: %s\n", dir, cp);
5981 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
5982 pr_warn("specified path %s is not on BPF FS\n", path);
5989 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
5992 char *cp, errmsg[STRERR_BUFSIZE];
5995 err = make_parent_dir(path);
5999 err = check_path(path);
6004 pr_warn("invalid program pointer\n");
6008 if (instance < 0 || instance >= prog->instances.nr) {
6009 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
6010 instance, prog->section_name, prog->instances.nr);
6014 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
6015 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6016 pr_warn("failed to pin program: %s\n", cp);
6019 pr_debug("pinned program '%s'\n", path);
6024 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
6029 err = check_path(path);
6034 pr_warn("invalid program pointer\n");
6038 if (instance < 0 || instance >= prog->instances.nr) {
6039 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
6040 instance, prog->section_name, prog->instances.nr);
6047 pr_debug("unpinned program '%s'\n", path);
6052 int bpf_program__pin(struct bpf_program *prog, const char *path)
6056 err = make_parent_dir(path);
6060 err = check_path(path);
6065 pr_warn("invalid program pointer\n");
6069 if (prog->instances.nr <= 0) {
6070 pr_warn("no instances of prog %s to pin\n",
6071 prog->section_name);
6075 if (prog->instances.nr == 1) {
6076 /* don't create subdirs when pinning single instance */
6077 return bpf_program__pin_instance(prog, path, 0);
6080 for (i = 0; i < prog->instances.nr; i++) {
6084 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
6088 } else if (len >= PATH_MAX) {
6089 err = -ENAMETOOLONG;
6093 err = bpf_program__pin_instance(prog, buf, i);
6101 for (i = i - 1; i >= 0; i--) {
6105 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
6108 else if (len >= PATH_MAX)
6111 bpf_program__unpin_instance(prog, buf, i);
6119 int bpf_program__unpin(struct bpf_program *prog, const char *path)
6123 err = check_path(path);
6128 pr_warn("invalid program pointer\n");
6132 if (prog->instances.nr <= 0) {
6133 pr_warn("no instances of prog %s to pin\n",
6134 prog->section_name);
6138 if (prog->instances.nr == 1) {
6139 /* don't create subdirs when pinning single instance */
6140 return bpf_program__unpin_instance(prog, path, 0);
6143 for (i = 0; i < prog->instances.nr; i++) {
6147 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
6150 else if (len >= PATH_MAX)
6151 return -ENAMETOOLONG;
6153 err = bpf_program__unpin_instance(prog, buf, i);
6165 int bpf_map__pin(struct bpf_map *map, const char *path)
6167 char *cp, errmsg[STRERR_BUFSIZE];
6171 pr_warn("invalid map pointer\n");
6175 if (map->pin_path) {
6176 if (path && strcmp(path, map->pin_path)) {
6177 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
6178 bpf_map__name(map), map->pin_path, path);
6180 } else if (map->pinned) {
6181 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
6182 bpf_map__name(map), map->pin_path);
6187 pr_warn("missing a path to pin map '%s' at\n",
6188 bpf_map__name(map));
6190 } else if (map->pinned) {
6191 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
6195 map->pin_path = strdup(path);
6196 if (!map->pin_path) {
6202 err = make_parent_dir(map->pin_path);
6206 err = check_path(map->pin_path);
6210 if (bpf_obj_pin(map->fd, map->pin_path)) {
6216 pr_debug("pinned map '%s'\n", map->pin_path);
6221 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
6222 pr_warn("failed to pin map: %s\n", cp);
6226 int bpf_map__unpin(struct bpf_map *map, const char *path)
6231 pr_warn("invalid map pointer\n");
6235 if (map->pin_path) {
6236 if (path && strcmp(path, map->pin_path)) {
6237 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
6238 bpf_map__name(map), map->pin_path, path);
6241 path = map->pin_path;
6243 pr_warn("no path to unpin map '%s' from\n",
6244 bpf_map__name(map));
6248 err = check_path(path);
6256 map->pinned = false;
6257 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
6262 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
6272 free(map->pin_path);
6273 map->pin_path = new;
6277 const char *bpf_map__get_pin_path(const struct bpf_map *map)
6279 return map->pin_path;
6282 bool bpf_map__is_pinned(const struct bpf_map *map)
6287 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
6289 struct bpf_map *map;
6296 pr_warn("object not yet loaded; load it first\n");
6300 bpf_object__for_each_map(map, obj) {
6301 char *pin_path = NULL;
6307 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6308 bpf_map__name(map));
6311 goto err_unpin_maps;
6312 } else if (len >= PATH_MAX) {
6313 err = -ENAMETOOLONG;
6314 goto err_unpin_maps;
6317 } else if (!map->pin_path) {
6321 err = bpf_map__pin(map, pin_path);
6323 goto err_unpin_maps;
6329 while ((map = bpf_map__prev(map, obj))) {
6333 bpf_map__unpin(map, NULL);
6339 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
6341 struct bpf_map *map;
6347 bpf_object__for_each_map(map, obj) {
6348 char *pin_path = NULL;
6354 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6355 bpf_map__name(map));
6358 else if (len >= PATH_MAX)
6359 return -ENAMETOOLONG;
6361 } else if (!map->pin_path) {
6365 err = bpf_map__unpin(map, pin_path);
6373 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
6375 struct bpf_program *prog;
6382 pr_warn("object not yet loaded; load it first\n");
6386 bpf_object__for_each_program(prog, obj) {
6390 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6394 goto err_unpin_programs;
6395 } else if (len >= PATH_MAX) {
6396 err = -ENAMETOOLONG;
6397 goto err_unpin_programs;
6400 err = bpf_program__pin(prog, buf);
6402 goto err_unpin_programs;
6408 while ((prog = bpf_program__prev(prog, obj))) {
6412 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6416 else if (len >= PATH_MAX)
6419 bpf_program__unpin(prog, buf);
6425 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
6427 struct bpf_program *prog;
6433 bpf_object__for_each_program(prog, obj) {
6437 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6441 else if (len >= PATH_MAX)
6442 return -ENAMETOOLONG;
6444 err = bpf_program__unpin(prog, buf);
6452 int bpf_object__pin(struct bpf_object *obj, const char *path)
6456 err = bpf_object__pin_maps(obj, path);
6460 err = bpf_object__pin_programs(obj, path);
6462 bpf_object__unpin_maps(obj, path);
6469 static void bpf_map__destroy(struct bpf_map *map)
6471 if (map->clear_priv)
6472 map->clear_priv(map, map->priv);
6474 map->clear_priv = NULL;
6476 if (map->inner_map) {
6477 bpf_map__destroy(map->inner_map);
6478 zfree(&map->inner_map);
6481 zfree(&map->init_slots);
6482 map->init_slots_sz = 0;
6485 munmap(map->mmaped, bpf_map_mmap_sz(map));
6490 zfree(&map->st_ops->data);
6491 zfree(&map->st_ops->progs);
6492 zfree(&map->st_ops->kern_func_off);
6493 zfree(&map->st_ops);
6497 zfree(&map->pin_path);
6503 void bpf_object__close(struct bpf_object *obj)
6510 if (obj->clear_priv)
6511 obj->clear_priv(obj, obj->priv);
6513 bpf_object__elf_finish(obj);
6514 bpf_object__unload(obj);
6515 btf__free(obj->btf);
6516 btf_ext__free(obj->btf_ext);
6518 for (i = 0; i < obj->nr_maps; i++)
6519 bpf_map__destroy(&obj->maps[i]);
6521 zfree(&obj->kconfig);
6522 zfree(&obj->externs);
6528 if (obj->programs && obj->nr_programs) {
6529 for (i = 0; i < obj->nr_programs; i++)
6530 bpf_program__exit(&obj->programs[i]);
6532 zfree(&obj->programs);
6534 list_del(&obj->list);
6539 bpf_object__next(struct bpf_object *prev)
6541 struct bpf_object *next;
6544 next = list_first_entry(&bpf_objects_list,
6548 next = list_next_entry(prev, list);
6550 /* Empty list is noticed here so don't need checking on entry. */
6551 if (&next->list == &bpf_objects_list)
6557 const char *bpf_object__name(const struct bpf_object *obj)
6559 return obj ? obj->name : ERR_PTR(-EINVAL);
6562 unsigned int bpf_object__kversion(const struct bpf_object *obj)
6564 return obj ? obj->kern_version : 0;
6567 struct btf *bpf_object__btf(const struct bpf_object *obj)
6569 return obj ? obj->btf : NULL;
6572 int bpf_object__btf_fd(const struct bpf_object *obj)
6574 return obj->btf ? btf__fd(obj->btf) : -1;
6577 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
6578 bpf_object_clear_priv_t clear_priv)
6580 if (obj->priv && obj->clear_priv)
6581 obj->clear_priv(obj, obj->priv);
6584 obj->clear_priv = clear_priv;
6588 void *bpf_object__priv(const struct bpf_object *obj)
6590 return obj ? obj->priv : ERR_PTR(-EINVAL);
6593 static struct bpf_program *
6594 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
6597 size_t nr_programs = obj->nr_programs;
6604 /* Iter from the beginning */
6605 return forward ? &obj->programs[0] :
6606 &obj->programs[nr_programs - 1];
6608 if (p->obj != obj) {
6609 pr_warn("error: program handler doesn't match object\n");
6613 idx = (p - obj->programs) + (forward ? 1 : -1);
6614 if (idx >= obj->nr_programs || idx < 0)
6616 return &obj->programs[idx];
6619 struct bpf_program *
6620 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
6622 struct bpf_program *prog = prev;
6625 prog = __bpf_program__iter(prog, obj, true);
6626 } while (prog && bpf_program__is_function_storage(prog, obj));
6631 struct bpf_program *
6632 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
6634 struct bpf_program *prog = next;
6637 prog = __bpf_program__iter(prog, obj, false);
6638 } while (prog && bpf_program__is_function_storage(prog, obj));
6643 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
6644 bpf_program_clear_priv_t clear_priv)
6646 if (prog->priv && prog->clear_priv)
6647 prog->clear_priv(prog, prog->priv);
6650 prog->clear_priv = clear_priv;
6654 void *bpf_program__priv(const struct bpf_program *prog)
6656 return prog ? prog->priv : ERR_PTR(-EINVAL);
6659 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
6661 prog->prog_ifindex = ifindex;
6664 const char *bpf_program__name(const struct bpf_program *prog)
6669 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
6673 title = prog->section_name;
6675 title = strdup(title);
6677 pr_warn("failed to strdup program title\n");
6678 return ERR_PTR(-ENOMEM);
6685 bool bpf_program__autoload(const struct bpf_program *prog)
6690 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
6692 if (prog->obj->loaded)
6695 prog->load = autoload;
6699 int bpf_program__fd(const struct bpf_program *prog)
6701 return bpf_program__nth_fd(prog, 0);
6704 size_t bpf_program__size(const struct bpf_program *prog)
6706 return prog->insns_cnt * sizeof(struct bpf_insn);
6709 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
6710 bpf_program_prep_t prep)
6714 if (nr_instances <= 0 || !prep)
6717 if (prog->instances.nr > 0 || prog->instances.fds) {
6718 pr_warn("Can't set pre-processor after loading\n");
6722 instances_fds = malloc(sizeof(int) * nr_instances);
6723 if (!instances_fds) {
6724 pr_warn("alloc memory failed for fds\n");
6728 /* fill all fd with -1 */
6729 memset(instances_fds, -1, sizeof(int) * nr_instances);
6731 prog->instances.nr = nr_instances;
6732 prog->instances.fds = instances_fds;
6733 prog->preprocessor = prep;
6737 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
6744 if (n >= prog->instances.nr || n < 0) {
6745 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6746 n, prog->section_name, prog->instances.nr);
6750 fd = prog->instances.fds[n];
6752 pr_warn("%dth instance of program '%s' is invalid\n",
6753 n, prog->section_name);
6760 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
6765 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
6770 static bool bpf_program__is_type(const struct bpf_program *prog,
6771 enum bpf_prog_type type)
6773 return prog ? (prog->type == type) : false;
6776 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
6777 int bpf_program__set_##NAME(struct bpf_program *prog) \
6781 bpf_program__set_type(prog, TYPE); \
6785 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
6787 return bpf_program__is_type(prog, TYPE); \
6790 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6791 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
6792 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
6793 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
6794 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
6795 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
6796 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
6797 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
6798 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
6799 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
6800 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
6801 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
6802 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
6804 enum bpf_attach_type
6805 bpf_program__get_expected_attach_type(struct bpf_program *prog)
6807 return prog->expected_attach_type;
6810 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
6811 enum bpf_attach_type type)
6813 prog->expected_attach_type = type;
6816 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
6817 attachable, attach_btf) \
6820 .len = sizeof(string) - 1, \
6821 .prog_type = ptype, \
6822 .expected_attach_type = eatype, \
6823 .is_exp_attach_type_optional = eatype_optional, \
6824 .is_attachable = attachable, \
6825 .is_attach_btf = attach_btf, \
6828 /* Programs that can NOT be attached. */
6829 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6831 /* Programs that can be attached. */
6832 #define BPF_APROG_SEC(string, ptype, atype) \
6833 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
6835 /* Programs that must specify expected attach type at load time. */
6836 #define BPF_EAPROG_SEC(string, ptype, eatype) \
6837 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
6839 /* Programs that use BTF to identify attach point */
6840 #define BPF_PROG_BTF(string, ptype, eatype) \
6841 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
6843 /* Programs that can be attached but attach type can't be identified by section
6844 * name. Kept for backward compatibility.
6846 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6848 #define SEC_DEF(sec_pfx, ptype, ...) { \
6850 .len = sizeof(sec_pfx) - 1, \
6851 .prog_type = BPF_PROG_TYPE_##ptype, \
6855 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6856 struct bpf_program *prog);
6857 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6858 struct bpf_program *prog);
6859 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6860 struct bpf_program *prog);
6861 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6862 struct bpf_program *prog);
6863 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
6864 struct bpf_program *prog);
6865 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
6866 struct bpf_program *prog);
6868 static const struct bpf_sec_def section_defs[] = {
6869 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
6870 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
6871 SEC_DEF("kprobe/", KPROBE,
6872 .attach_fn = attach_kprobe),
6873 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
6874 SEC_DEF("kretprobe/", KPROBE,
6875 .attach_fn = attach_kprobe),
6876 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
6877 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
6878 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
6879 SEC_DEF("tracepoint/", TRACEPOINT,
6880 .attach_fn = attach_tp),
6881 SEC_DEF("tp/", TRACEPOINT,
6882 .attach_fn = attach_tp),
6883 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
6884 .attach_fn = attach_raw_tp),
6885 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
6886 .attach_fn = attach_raw_tp),
6887 SEC_DEF("tp_btf/", TRACING,
6888 .expected_attach_type = BPF_TRACE_RAW_TP,
6889 .is_attach_btf = true,
6890 .attach_fn = attach_trace),
6891 SEC_DEF("fentry/", TRACING,
6892 .expected_attach_type = BPF_TRACE_FENTRY,
6893 .is_attach_btf = true,
6894 .attach_fn = attach_trace),
6895 SEC_DEF("fmod_ret/", TRACING,
6896 .expected_attach_type = BPF_MODIFY_RETURN,
6897 .is_attach_btf = true,
6898 .attach_fn = attach_trace),
6899 SEC_DEF("fexit/", TRACING,
6900 .expected_attach_type = BPF_TRACE_FEXIT,
6901 .is_attach_btf = true,
6902 .attach_fn = attach_trace),
6903 SEC_DEF("freplace/", EXT,
6904 .is_attach_btf = true,
6905 .attach_fn = attach_trace),
6906 SEC_DEF("lsm/", LSM,
6907 .is_attach_btf = true,
6908 .expected_attach_type = BPF_LSM_MAC,
6909 .attach_fn = attach_lsm),
6910 SEC_DEF("iter/", TRACING,
6911 .expected_attach_type = BPF_TRACE_ITER,
6912 .is_attach_btf = true,
6913 .attach_fn = attach_iter),
6914 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
6916 BPF_EAPROG_SEC("xdp_cpumap/", BPF_PROG_TYPE_XDP,
6918 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
6919 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
6920 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
6921 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
6922 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
6923 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
6924 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
6925 BPF_CGROUP_INET_INGRESS),
6926 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
6927 BPF_CGROUP_INET_EGRESS),
6928 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
6929 BPF_EAPROG_SEC("cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK,
6930 BPF_CGROUP_INET_SOCK_CREATE),
6931 BPF_EAPROG_SEC("cgroup/sock_release", BPF_PROG_TYPE_CGROUP_SOCK,
6932 BPF_CGROUP_INET_SOCK_RELEASE),
6933 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
6934 BPF_CGROUP_INET_SOCK_CREATE),
6935 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
6936 BPF_CGROUP_INET4_POST_BIND),
6937 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
6938 BPF_CGROUP_INET6_POST_BIND),
6939 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
6941 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
6942 BPF_CGROUP_SOCK_OPS),
6943 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
6944 BPF_SK_SKB_STREAM_PARSER),
6945 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
6946 BPF_SK_SKB_STREAM_VERDICT),
6947 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
6948 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
6949 BPF_SK_MSG_VERDICT),
6950 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
6952 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
6953 BPF_FLOW_DISSECTOR),
6954 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6955 BPF_CGROUP_INET4_BIND),
6956 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6957 BPF_CGROUP_INET6_BIND),
6958 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6959 BPF_CGROUP_INET4_CONNECT),
6960 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6961 BPF_CGROUP_INET6_CONNECT),
6962 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6963 BPF_CGROUP_UDP4_SENDMSG),
6964 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6965 BPF_CGROUP_UDP6_SENDMSG),
6966 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6967 BPF_CGROUP_UDP4_RECVMSG),
6968 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6969 BPF_CGROUP_UDP6_RECVMSG),
6970 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6971 BPF_CGROUP_INET4_GETPEERNAME),
6972 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6973 BPF_CGROUP_INET6_GETPEERNAME),
6974 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6975 BPF_CGROUP_INET4_GETSOCKNAME),
6976 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6977 BPF_CGROUP_INET6_GETSOCKNAME),
6978 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
6980 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6981 BPF_CGROUP_GETSOCKOPT),
6982 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6983 BPF_CGROUP_SETSOCKOPT),
6984 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
6985 BPF_EAPROG_SEC("sk_lookup/", BPF_PROG_TYPE_SK_LOOKUP,
6989 #undef BPF_PROG_SEC_IMPL
6991 #undef BPF_APROG_SEC
6992 #undef BPF_EAPROG_SEC
6993 #undef BPF_APROG_COMPAT
6996 #define MAX_TYPE_NAME_SIZE 32
6998 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
7000 int i, n = ARRAY_SIZE(section_defs);
7002 for (i = 0; i < n; i++) {
7003 if (strncmp(sec_name,
7004 section_defs[i].sec, section_defs[i].len))
7006 return §ion_defs[i];
7011 static char *libbpf_get_type_names(bool attach_type)
7013 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
7021 /* Forge string buf with all available names */
7022 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7023 if (attach_type && !section_defs[i].is_attachable)
7026 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
7031 strcat(buf, section_defs[i].sec);
7037 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
7038 enum bpf_attach_type *expected_attach_type)
7040 const struct bpf_sec_def *sec_def;
7046 sec_def = find_sec_def(name);
7048 *prog_type = sec_def->prog_type;
7049 *expected_attach_type = sec_def->expected_attach_type;
7053 pr_debug("failed to guess program type from ELF section '%s'\n", name);
7054 type_names = libbpf_get_type_names(false);
7055 if (type_names != NULL) {
7056 pr_debug("supported section(type) names are:%s\n", type_names);
7063 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
7066 struct bpf_map *map;
7069 for (i = 0; i < obj->nr_maps; i++) {
7070 map = &obj->maps[i];
7071 if (!bpf_map__is_struct_ops(map))
7073 if (map->sec_offset <= offset &&
7074 offset - map->sec_offset < map->def.value_size)
7081 /* Collect the reloc from ELF and populate the st_ops->progs[] */
7082 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7083 GElf_Shdr *shdr, Elf_Data *data)
7085 const struct btf_member *member;
7086 struct bpf_struct_ops *st_ops;
7087 struct bpf_program *prog;
7088 unsigned int shdr_idx;
7089 const struct btf *btf;
7090 struct bpf_map *map;
7099 symbols = obj->efile.symbols;
7101 nrels = shdr->sh_size / shdr->sh_entsize;
7102 for (i = 0; i < nrels; i++) {
7103 if (!gelf_getrel(data, i, &rel)) {
7104 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
7105 return -LIBBPF_ERRNO__FORMAT;
7108 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
7109 pr_warn("struct_ops reloc: symbol %zx not found\n",
7110 (size_t)GELF_R_SYM(rel.r_info));
7111 return -LIBBPF_ERRNO__FORMAT;
7114 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
7115 sym.st_name) ? : "<?>";
7116 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
7118 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
7119 (size_t)rel.r_offset);
7123 moff = rel.r_offset - map->sec_offset;
7124 shdr_idx = sym.st_shndx;
7125 st_ops = map->st_ops;
7126 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",
7128 (long long)(rel.r_info >> 32),
7129 (long long)sym.st_value,
7130 shdr_idx, (size_t)rel.r_offset,
7131 map->sec_offset, sym.st_name, name);
7133 if (shdr_idx >= SHN_LORESERVE) {
7134 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
7135 map->name, (size_t)rel.r_offset, shdr_idx);
7136 return -LIBBPF_ERRNO__RELOC;
7139 member = find_member_by_offset(st_ops->type, moff * 8);
7141 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
7145 member_idx = member - btf_members(st_ops->type);
7146 name = btf__name_by_offset(btf, member->name_off);
7148 if (!resolve_func_ptr(btf, member->type, NULL)) {
7149 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
7154 prog = bpf_object__find_prog_by_idx(obj, shdr_idx);
7156 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
7157 map->name, shdr_idx, name);
7161 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7162 const struct bpf_sec_def *sec_def;
7164 sec_def = find_sec_def(prog->section_name);
7166 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
7168 prog->type = sec_def->prog_type;
7172 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
7173 prog->attach_btf_id = st_ops->type_id;
7174 prog->expected_attach_type = member_idx;
7175 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
7176 prog->attach_btf_id != st_ops->type_id ||
7177 prog->expected_attach_type != member_idx) {
7180 st_ops->progs[member_idx] = prog;
7186 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",
7187 map->name, prog->name, prog->section_name, prog->type,
7188 prog->attach_btf_id, prog->expected_attach_type, name);
7192 #define BTF_TRACE_PREFIX "btf_trace_"
7193 #define BTF_LSM_PREFIX "bpf_lsm_"
7194 #define BTF_ITER_PREFIX "bpf_iter_"
7195 #define BTF_MAX_NAME_SIZE 128
7197 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
7198 const char *name, __u32 kind)
7200 char btf_type_name[BTF_MAX_NAME_SIZE];
7203 ret = snprintf(btf_type_name, sizeof(btf_type_name),
7204 "%s%s", prefix, name);
7205 /* snprintf returns the number of characters written excluding the
7206 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
7207 * indicates truncation.
7209 if (ret < 0 || ret >= sizeof(btf_type_name))
7210 return -ENAMETOOLONG;
7211 return btf__find_by_name_kind(btf, btf_type_name, kind);
7214 static inline int __find_vmlinux_btf_id(struct btf *btf, const char *name,
7215 enum bpf_attach_type attach_type)
7219 if (attach_type == BPF_TRACE_RAW_TP)
7220 err = find_btf_by_prefix_kind(btf, BTF_TRACE_PREFIX, name,
7222 else if (attach_type == BPF_LSM_MAC)
7223 err = find_btf_by_prefix_kind(btf, BTF_LSM_PREFIX, name,
7225 else if (attach_type == BPF_TRACE_ITER)
7226 err = find_btf_by_prefix_kind(btf, BTF_ITER_PREFIX, name,
7229 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
7232 pr_warn("%s is not found in vmlinux BTF\n", name);
7237 int libbpf_find_vmlinux_btf_id(const char *name,
7238 enum bpf_attach_type attach_type)
7243 btf = libbpf_find_kernel_btf();
7245 pr_warn("vmlinux BTF is not found\n");
7249 err = __find_vmlinux_btf_id(btf, name, attach_type);
7254 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
7256 struct bpf_prog_info_linear *info_linear;
7257 struct bpf_prog_info *info;
7258 struct btf *btf = NULL;
7261 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
7262 if (IS_ERR_OR_NULL(info_linear)) {
7263 pr_warn("failed get_prog_info_linear for FD %d\n",
7267 info = &info_linear->info;
7268 if (!info->btf_id) {
7269 pr_warn("The target program doesn't have BTF\n");
7272 if (btf__get_from_id(info->btf_id, &btf)) {
7273 pr_warn("Failed to get BTF of the program\n");
7276 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
7279 pr_warn("%s is not found in prog's BTF\n", name);
7287 static int libbpf_find_attach_btf_id(struct bpf_program *prog)
7289 enum bpf_attach_type attach_type = prog->expected_attach_type;
7290 __u32 attach_prog_fd = prog->attach_prog_fd;
7291 const char *name = prog->section_name;
7297 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7298 if (!section_defs[i].is_attach_btf)
7300 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7303 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
7306 err = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
7307 name + section_defs[i].len,
7311 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
7315 int libbpf_attach_type_by_name(const char *name,
7316 enum bpf_attach_type *attach_type)
7324 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7325 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7327 if (!section_defs[i].is_attachable)
7329 *attach_type = section_defs[i].expected_attach_type;
7332 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
7333 type_names = libbpf_get_type_names(true);
7334 if (type_names != NULL) {
7335 pr_debug("attachable section(type) names are:%s\n", type_names);
7342 int bpf_map__fd(const struct bpf_map *map)
7344 return map ? map->fd : -EINVAL;
7347 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
7349 return map ? &map->def : ERR_PTR(-EINVAL);
7352 const char *bpf_map__name(const struct bpf_map *map)
7354 return map ? map->name : NULL;
7357 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
7359 return map->def.type;
7362 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
7366 map->def.type = type;
7370 __u32 bpf_map__map_flags(const struct bpf_map *map)
7372 return map->def.map_flags;
7375 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
7379 map->def.map_flags = flags;
7383 __u32 bpf_map__numa_node(const struct bpf_map *map)
7385 return map->numa_node;
7388 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
7392 map->numa_node = numa_node;
7396 __u32 bpf_map__key_size(const struct bpf_map *map)
7398 return map->def.key_size;
7401 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
7405 map->def.key_size = size;
7409 __u32 bpf_map__value_size(const struct bpf_map *map)
7411 return map->def.value_size;
7414 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
7418 map->def.value_size = size;
7422 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
7424 return map ? map->btf_key_type_id : 0;
7427 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
7429 return map ? map->btf_value_type_id : 0;
7432 int bpf_map__set_priv(struct bpf_map *map, void *priv,
7433 bpf_map_clear_priv_t clear_priv)
7439 if (map->clear_priv)
7440 map->clear_priv(map, map->priv);
7444 map->clear_priv = clear_priv;
7448 void *bpf_map__priv(const struct bpf_map *map)
7450 return map ? map->priv : ERR_PTR(-EINVAL);
7453 int bpf_map__set_initial_value(struct bpf_map *map,
7454 const void *data, size_t size)
7456 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
7457 size != map->def.value_size || map->fd >= 0)
7460 memcpy(map->mmaped, data, size);
7464 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
7466 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
7469 bool bpf_map__is_internal(const struct bpf_map *map)
7471 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
7474 __u32 bpf_map__ifindex(const struct bpf_map *map)
7476 return map->map_ifindex;
7479 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
7483 map->map_ifindex = ifindex;
7487 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
7489 if (!bpf_map_type__is_map_in_map(map->def.type)) {
7490 pr_warn("error: unsupported map type\n");
7493 if (map->inner_map_fd != -1) {
7494 pr_warn("error: inner_map_fd already specified\n");
7497 map->inner_map_fd = fd;
7501 static struct bpf_map *
7502 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
7505 struct bpf_map *s, *e;
7507 if (!obj || !obj->maps)
7511 e = obj->maps + obj->nr_maps;
7513 if ((m < s) || (m >= e)) {
7514 pr_warn("error in %s: map handler doesn't belong to object\n",
7519 idx = (m - obj->maps) + i;
7520 if (idx >= obj->nr_maps || idx < 0)
7522 return &obj->maps[idx];
7526 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
7531 return __bpf_map__iter(prev, obj, 1);
7535 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
7540 return obj->maps + obj->nr_maps - 1;
7543 return __bpf_map__iter(next, obj, -1);
7547 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
7549 struct bpf_map *pos;
7551 bpf_object__for_each_map(pos, obj) {
7552 if (pos->name && !strcmp(pos->name, name))
7559 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
7561 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
7565 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
7567 return ERR_PTR(-ENOTSUP);
7570 long libbpf_get_error(const void *ptr)
7572 return PTR_ERR_OR_ZERO(ptr);
7575 int bpf_prog_load(const char *file, enum bpf_prog_type type,
7576 struct bpf_object **pobj, int *prog_fd)
7578 struct bpf_prog_load_attr attr;
7580 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
7582 attr.prog_type = type;
7583 attr.expected_attach_type = 0;
7585 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
7588 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
7589 struct bpf_object **pobj, int *prog_fd)
7591 struct bpf_object_open_attr open_attr = {};
7592 struct bpf_program *prog, *first_prog = NULL;
7593 struct bpf_object *obj;
7594 struct bpf_map *map;
7602 open_attr.file = attr->file;
7603 open_attr.prog_type = attr->prog_type;
7605 obj = bpf_object__open_xattr(&open_attr);
7606 if (IS_ERR_OR_NULL(obj))
7609 bpf_object__for_each_program(prog, obj) {
7610 enum bpf_attach_type attach_type = attr->expected_attach_type;
7612 * to preserve backwards compatibility, bpf_prog_load treats
7613 * attr->prog_type, if specified, as an override to whatever
7614 * bpf_object__open guessed
7616 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
7617 bpf_program__set_type(prog, attr->prog_type);
7618 bpf_program__set_expected_attach_type(prog,
7621 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
7623 * we haven't guessed from section name and user
7624 * didn't provide a fallback type, too bad...
7626 bpf_object__close(obj);
7630 prog->prog_ifindex = attr->ifindex;
7631 prog->log_level = attr->log_level;
7632 prog->prog_flags = attr->prog_flags;
7637 bpf_object__for_each_map(map, obj) {
7638 if (!bpf_map__is_offload_neutral(map))
7639 map->map_ifindex = attr->ifindex;
7643 pr_warn("object file doesn't contain bpf program\n");
7644 bpf_object__close(obj);
7648 err = bpf_object__load(obj);
7650 bpf_object__close(obj);
7655 *prog_fd = bpf_program__fd(first_prog);
7660 int (*detach)(struct bpf_link *link);
7661 int (*destroy)(struct bpf_link *link);
7662 char *pin_path; /* NULL, if not pinned */
7663 int fd; /* hook FD, -1 if not applicable */
7667 /* Replace link's underlying BPF program with the new one */
7668 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
7670 return bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
7673 /* Release "ownership" of underlying BPF resource (typically, BPF program
7674 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
7675 * link, when destructed through bpf_link__destroy() call won't attempt to
7676 * detach/unregisted that BPF resource. This is useful in situations where,
7677 * say, attached BPF program has to outlive userspace program that attached it
7678 * in the system. Depending on type of BPF program, though, there might be
7679 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
7680 * exit of userspace program doesn't trigger automatic detachment and clean up
7681 * inside the kernel.
7683 void bpf_link__disconnect(struct bpf_link *link)
7685 link->disconnected = true;
7688 int bpf_link__destroy(struct bpf_link *link)
7695 if (!link->disconnected && link->detach)
7696 err = link->detach(link);
7698 link->destroy(link);
7700 free(link->pin_path);
7706 int bpf_link__fd(const struct bpf_link *link)
7711 const char *bpf_link__pin_path(const struct bpf_link *link)
7713 return link->pin_path;
7716 static int bpf_link__detach_fd(struct bpf_link *link)
7718 return close(link->fd);
7721 struct bpf_link *bpf_link__open(const char *path)
7723 struct bpf_link *link;
7726 fd = bpf_obj_get(path);
7729 pr_warn("failed to open link at %s: %d\n", path, fd);
7733 link = calloc(1, sizeof(*link));
7736 return ERR_PTR(-ENOMEM);
7738 link->detach = &bpf_link__detach_fd;
7741 link->pin_path = strdup(path);
7742 if (!link->pin_path) {
7743 bpf_link__destroy(link);
7744 return ERR_PTR(-ENOMEM);
7750 int bpf_link__pin(struct bpf_link *link, const char *path)
7756 err = make_parent_dir(path);
7759 err = check_path(path);
7763 link->pin_path = strdup(path);
7764 if (!link->pin_path)
7767 if (bpf_obj_pin(link->fd, link->pin_path)) {
7769 zfree(&link->pin_path);
7773 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
7777 int bpf_link__unpin(struct bpf_link *link)
7781 if (!link->pin_path)
7784 err = unlink(link->pin_path);
7788 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
7789 zfree(&link->pin_path);
7793 static int bpf_link__detach_perf_event(struct bpf_link *link)
7797 err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
7805 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
7808 char errmsg[STRERR_BUFSIZE];
7809 struct bpf_link *link;
7813 pr_warn("program '%s': invalid perf event FD %d\n",
7814 bpf_program__title(prog, false), pfd);
7815 return ERR_PTR(-EINVAL);
7817 prog_fd = bpf_program__fd(prog);
7819 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
7820 bpf_program__title(prog, false));
7821 return ERR_PTR(-EINVAL);
7824 link = calloc(1, sizeof(*link));
7826 return ERR_PTR(-ENOMEM);
7827 link->detach = &bpf_link__detach_perf_event;
7830 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
7833 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7834 bpf_program__title(prog, false), pfd,
7835 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7837 pr_warn("program '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
7838 bpf_program__title(prog, false), pfd);
7839 return ERR_PTR(err);
7841 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7844 pr_warn("program '%s': failed to enable pfd %d: %s\n",
7845 bpf_program__title(prog, false), pfd,
7846 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7847 return ERR_PTR(err);
7853 * this function is expected to parse integer in the range of [0, 2^31-1] from
7854 * given file using scanf format string fmt. If actual parsed value is
7855 * negative, the result might be indistinguishable from error
7857 static int parse_uint_from_file(const char *file, const char *fmt)
7859 char buf[STRERR_BUFSIZE];
7863 f = fopen(file, "r");
7866 pr_debug("failed to open '%s': %s\n", file,
7867 libbpf_strerror_r(err, buf, sizeof(buf)));
7870 err = fscanf(f, fmt, &ret);
7872 err = err == EOF ? -EIO : -errno;
7873 pr_debug("failed to parse '%s': %s\n", file,
7874 libbpf_strerror_r(err, buf, sizeof(buf)));
7882 static int determine_kprobe_perf_type(void)
7884 const char *file = "/sys/bus/event_source/devices/kprobe/type";
7886 return parse_uint_from_file(file, "%d\n");
7889 static int determine_uprobe_perf_type(void)
7891 const char *file = "/sys/bus/event_source/devices/uprobe/type";
7893 return parse_uint_from_file(file, "%d\n");
7896 static int determine_kprobe_retprobe_bit(void)
7898 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
7900 return parse_uint_from_file(file, "config:%d\n");
7903 static int determine_uprobe_retprobe_bit(void)
7905 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
7907 return parse_uint_from_file(file, "config:%d\n");
7910 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
7911 uint64_t offset, int pid)
7913 struct perf_event_attr attr = {};
7914 char errmsg[STRERR_BUFSIZE];
7917 type = uprobe ? determine_uprobe_perf_type()
7918 : determine_kprobe_perf_type();
7920 pr_warn("failed to determine %s perf type: %s\n",
7921 uprobe ? "uprobe" : "kprobe",
7922 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
7926 int bit = uprobe ? determine_uprobe_retprobe_bit()
7927 : determine_kprobe_retprobe_bit();
7930 pr_warn("failed to determine %s retprobe bit: %s\n",
7931 uprobe ? "uprobe" : "kprobe",
7932 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
7935 attr.config |= 1 << bit;
7937 attr.size = sizeof(attr);
7939 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
7940 attr.config2 = offset; /* kprobe_addr or probe_offset */
7942 /* pid filter is meaningful only for uprobes */
7943 pfd = syscall(__NR_perf_event_open, &attr,
7944 pid < 0 ? -1 : pid /* pid */,
7945 pid == -1 ? 0 : -1 /* cpu */,
7946 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7949 pr_warn("%s perf_event_open() failed: %s\n",
7950 uprobe ? "uprobe" : "kprobe",
7951 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7957 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
7959 const char *func_name)
7961 char errmsg[STRERR_BUFSIZE];
7962 struct bpf_link *link;
7965 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
7966 0 /* offset */, -1 /* pid */);
7968 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7969 bpf_program__title(prog, false),
7970 retprobe ? "kretprobe" : "kprobe", func_name,
7971 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7972 return ERR_PTR(pfd);
7974 link = bpf_program__attach_perf_event(prog, pfd);
7977 err = PTR_ERR(link);
7978 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7979 bpf_program__title(prog, false),
7980 retprobe ? "kretprobe" : "kprobe", func_name,
7981 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7987 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7988 struct bpf_program *prog)
7990 const char *func_name;
7993 func_name = bpf_program__title(prog, false) + sec->len;
7994 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
7996 return bpf_program__attach_kprobe(prog, retprobe, func_name);
7999 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
8000 bool retprobe, pid_t pid,
8001 const char *binary_path,
8004 char errmsg[STRERR_BUFSIZE];
8005 struct bpf_link *link;
8008 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
8009 binary_path, func_offset, pid);
8011 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
8012 bpf_program__title(prog, false),
8013 retprobe ? "uretprobe" : "uprobe",
8014 binary_path, func_offset,
8015 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8016 return ERR_PTR(pfd);
8018 link = bpf_program__attach_perf_event(prog, pfd);
8021 err = PTR_ERR(link);
8022 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
8023 bpf_program__title(prog, false),
8024 retprobe ? "uretprobe" : "uprobe",
8025 binary_path, func_offset,
8026 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8032 static int determine_tracepoint_id(const char *tp_category,
8033 const char *tp_name)
8035 char file[PATH_MAX];
8038 ret = snprintf(file, sizeof(file),
8039 "/sys/kernel/debug/tracing/events/%s/%s/id",
8040 tp_category, tp_name);
8043 if (ret >= sizeof(file)) {
8044 pr_debug("tracepoint %s/%s path is too long\n",
8045 tp_category, tp_name);
8048 return parse_uint_from_file(file, "%d\n");
8051 static int perf_event_open_tracepoint(const char *tp_category,
8052 const char *tp_name)
8054 struct perf_event_attr attr = {};
8055 char errmsg[STRERR_BUFSIZE];
8056 int tp_id, pfd, err;
8058 tp_id = determine_tracepoint_id(tp_category, tp_name);
8060 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
8061 tp_category, tp_name,
8062 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
8066 attr.type = PERF_TYPE_TRACEPOINT;
8067 attr.size = sizeof(attr);
8068 attr.config = tp_id;
8070 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
8071 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
8074 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
8075 tp_category, tp_name,
8076 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8082 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
8083 const char *tp_category,
8084 const char *tp_name)
8086 char errmsg[STRERR_BUFSIZE];
8087 struct bpf_link *link;
8090 pfd = perf_event_open_tracepoint(tp_category, tp_name);
8092 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
8093 bpf_program__title(prog, false),
8094 tp_category, tp_name,
8095 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8096 return ERR_PTR(pfd);
8098 link = bpf_program__attach_perf_event(prog, pfd);
8101 err = PTR_ERR(link);
8102 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
8103 bpf_program__title(prog, false),
8104 tp_category, tp_name,
8105 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8111 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
8112 struct bpf_program *prog)
8114 char *sec_name, *tp_cat, *tp_name;
8115 struct bpf_link *link;
8117 sec_name = strdup(bpf_program__title(prog, false));
8119 return ERR_PTR(-ENOMEM);
8121 /* extract "tp/<category>/<name>" */
8122 tp_cat = sec_name + sec->len;
8123 tp_name = strchr(tp_cat, '/');
8125 link = ERR_PTR(-EINVAL);
8131 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
8137 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
8138 const char *tp_name)
8140 char errmsg[STRERR_BUFSIZE];
8141 struct bpf_link *link;
8144 prog_fd = bpf_program__fd(prog);
8146 pr_warn("program '%s': can't attach before loaded\n",
8147 bpf_program__title(prog, false));
8148 return ERR_PTR(-EINVAL);
8151 link = calloc(1, sizeof(*link));
8153 return ERR_PTR(-ENOMEM);
8154 link->detach = &bpf_link__detach_fd;
8156 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
8160 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
8161 bpf_program__title(prog, false), tp_name,
8162 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8163 return ERR_PTR(pfd);
8169 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
8170 struct bpf_program *prog)
8172 const char *tp_name = bpf_program__title(prog, false) + sec->len;
8174 return bpf_program__attach_raw_tracepoint(prog, tp_name);
8177 /* Common logic for all BPF program types that attach to a btf_id */
8178 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
8180 char errmsg[STRERR_BUFSIZE];
8181 struct bpf_link *link;
8184 prog_fd = bpf_program__fd(prog);
8186 pr_warn("program '%s': can't attach before loaded\n",
8187 bpf_program__title(prog, false));
8188 return ERR_PTR(-EINVAL);
8191 link = calloc(1, sizeof(*link));
8193 return ERR_PTR(-ENOMEM);
8194 link->detach = &bpf_link__detach_fd;
8196 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
8200 pr_warn("program '%s': failed to attach: %s\n",
8201 bpf_program__title(prog, false),
8202 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
8203 return ERR_PTR(pfd);
8206 return (struct bpf_link *)link;
8209 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
8211 return bpf_program__attach_btf_id(prog);
8214 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
8216 return bpf_program__attach_btf_id(prog);
8219 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
8220 struct bpf_program *prog)
8222 return bpf_program__attach_trace(prog);
8225 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
8226 struct bpf_program *prog)
8228 return bpf_program__attach_lsm(prog);
8231 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
8232 struct bpf_program *prog)
8234 return bpf_program__attach_iter(prog, NULL);
8237 static struct bpf_link *
8238 bpf_program__attach_fd(struct bpf_program *prog, int target_fd,
8239 const char *target_name)
8241 enum bpf_attach_type attach_type;
8242 char errmsg[STRERR_BUFSIZE];
8243 struct bpf_link *link;
8244 int prog_fd, link_fd;
8246 prog_fd = bpf_program__fd(prog);
8248 pr_warn("program '%s': can't attach before loaded\n",
8249 bpf_program__title(prog, false));
8250 return ERR_PTR(-EINVAL);
8253 link = calloc(1, sizeof(*link));
8255 return ERR_PTR(-ENOMEM);
8256 link->detach = &bpf_link__detach_fd;
8258 attach_type = bpf_program__get_expected_attach_type(prog);
8259 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, NULL);
8263 pr_warn("program '%s': failed to attach to %s: %s\n",
8264 bpf_program__title(prog, false), target_name,
8265 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
8266 return ERR_PTR(link_fd);
8273 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
8275 return bpf_program__attach_fd(prog, cgroup_fd, "cgroup");
8279 bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
8281 return bpf_program__attach_fd(prog, netns_fd, "netns");
8285 bpf_program__attach_iter(struct bpf_program *prog,
8286 const struct bpf_iter_attach_opts *opts)
8288 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
8289 char errmsg[STRERR_BUFSIZE];
8290 struct bpf_link *link;
8291 int prog_fd, link_fd;
8292 __u32 target_fd = 0;
8294 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
8295 return ERR_PTR(-EINVAL);
8297 if (OPTS_HAS(opts, map_fd)) {
8298 target_fd = opts->map_fd;
8299 link_create_opts.flags = BPF_ITER_LINK_MAP_FD;
8302 prog_fd = bpf_program__fd(prog);
8304 pr_warn("program '%s': can't attach before loaded\n",
8305 bpf_program__title(prog, false));
8306 return ERR_PTR(-EINVAL);
8309 link = calloc(1, sizeof(*link));
8311 return ERR_PTR(-ENOMEM);
8312 link->detach = &bpf_link__detach_fd;
8314 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
8319 pr_warn("program '%s': failed to attach to iterator: %s\n",
8320 bpf_program__title(prog, false),
8321 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
8322 return ERR_PTR(link_fd);
8328 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
8330 const struct bpf_sec_def *sec_def;
8332 sec_def = find_sec_def(bpf_program__title(prog, false));
8333 if (!sec_def || !sec_def->attach_fn)
8334 return ERR_PTR(-ESRCH);
8336 return sec_def->attach_fn(sec_def, prog);
8339 static int bpf_link__detach_struct_ops(struct bpf_link *link)
8343 if (bpf_map_delete_elem(link->fd, &zero))
8349 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
8351 struct bpf_struct_ops *st_ops;
8352 struct bpf_link *link;
8356 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
8357 return ERR_PTR(-EINVAL);
8359 link = calloc(1, sizeof(*link));
8361 return ERR_PTR(-EINVAL);
8363 st_ops = map->st_ops;
8364 for (i = 0; i < btf_vlen(st_ops->type); i++) {
8365 struct bpf_program *prog = st_ops->progs[i];
8372 prog_fd = bpf_program__fd(prog);
8373 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8374 *(unsigned long *)kern_data = prog_fd;
8377 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
8381 return ERR_PTR(err);
8384 link->detach = bpf_link__detach_struct_ops;
8390 enum bpf_perf_event_ret
8391 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
8392 void **copy_mem, size_t *copy_size,
8393 bpf_perf_event_print_t fn, void *private_data)
8395 struct perf_event_mmap_page *header = mmap_mem;
8396 __u64 data_head = ring_buffer_read_head(header);
8397 __u64 data_tail = header->data_tail;
8398 void *base = ((__u8 *)header) + page_size;
8399 int ret = LIBBPF_PERF_EVENT_CONT;
8400 struct perf_event_header *ehdr;
8403 while (data_head != data_tail) {
8404 ehdr = base + (data_tail & (mmap_size - 1));
8405 ehdr_size = ehdr->size;
8407 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
8408 void *copy_start = ehdr;
8409 size_t len_first = base + mmap_size - copy_start;
8410 size_t len_secnd = ehdr_size - len_first;
8412 if (*copy_size < ehdr_size) {
8414 *copy_mem = malloc(ehdr_size);
8417 ret = LIBBPF_PERF_EVENT_ERROR;
8420 *copy_size = ehdr_size;
8423 memcpy(*copy_mem, copy_start, len_first);
8424 memcpy(*copy_mem + len_first, base, len_secnd);
8428 ret = fn(ehdr, private_data);
8429 data_tail += ehdr_size;
8430 if (ret != LIBBPF_PERF_EVENT_CONT)
8434 ring_buffer_write_tail(header, data_tail);
8440 struct perf_buffer_params {
8441 struct perf_event_attr *attr;
8442 /* if event_cb is specified, it takes precendence */
8443 perf_buffer_event_fn event_cb;
8444 /* sample_cb and lost_cb are higher-level common-case callbacks */
8445 perf_buffer_sample_fn sample_cb;
8446 perf_buffer_lost_fn lost_cb;
8453 struct perf_cpu_buf {
8454 struct perf_buffer *pb;
8455 void *base; /* mmap()'ed memory */
8456 void *buf; /* for reconstructing segmented data */
8463 struct perf_buffer {
8464 perf_buffer_event_fn event_cb;
8465 perf_buffer_sample_fn sample_cb;
8466 perf_buffer_lost_fn lost_cb;
8467 void *ctx; /* passed into callbacks */
8471 struct perf_cpu_buf **cpu_bufs;
8472 struct epoll_event *events;
8473 int cpu_cnt; /* number of allocated CPU buffers */
8474 int epoll_fd; /* perf event FD */
8475 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
8478 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
8479 struct perf_cpu_buf *cpu_buf)
8483 if (cpu_buf->base &&
8484 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
8485 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
8486 if (cpu_buf->fd >= 0) {
8487 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
8494 void perf_buffer__free(struct perf_buffer *pb)
8501 for (i = 0; i < pb->cpu_cnt; i++) {
8502 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8507 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
8508 perf_buffer__free_cpu_buf(pb, cpu_buf);
8512 if (pb->epoll_fd >= 0)
8513 close(pb->epoll_fd);
8518 static struct perf_cpu_buf *
8519 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
8520 int cpu, int map_key)
8522 struct perf_cpu_buf *cpu_buf;
8523 char msg[STRERR_BUFSIZE];
8526 cpu_buf = calloc(1, sizeof(*cpu_buf));
8528 return ERR_PTR(-ENOMEM);
8532 cpu_buf->map_key = map_key;
8534 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
8535 -1, PERF_FLAG_FD_CLOEXEC);
8536 if (cpu_buf->fd < 0) {
8538 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
8539 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8543 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
8544 PROT_READ | PROT_WRITE, MAP_SHARED,
8546 if (cpu_buf->base == MAP_FAILED) {
8547 cpu_buf->base = NULL;
8549 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
8550 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8554 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
8556 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
8557 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8564 perf_buffer__free_cpu_buf(pb, cpu_buf);
8565 return (struct perf_cpu_buf *)ERR_PTR(err);
8568 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8569 struct perf_buffer_params *p);
8571 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
8572 const struct perf_buffer_opts *opts)
8574 struct perf_buffer_params p = {};
8575 struct perf_event_attr attr = { 0, };
8577 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
8578 attr.type = PERF_TYPE_SOFTWARE;
8579 attr.sample_type = PERF_SAMPLE_RAW;
8580 attr.sample_period = 1;
8581 attr.wakeup_events = 1;
8584 p.sample_cb = opts ? opts->sample_cb : NULL;
8585 p.lost_cb = opts ? opts->lost_cb : NULL;
8586 p.ctx = opts ? opts->ctx : NULL;
8588 return __perf_buffer__new(map_fd, page_cnt, &p);
8591 struct perf_buffer *
8592 perf_buffer__new_raw(int map_fd, size_t page_cnt,
8593 const struct perf_buffer_raw_opts *opts)
8595 struct perf_buffer_params p = {};
8597 p.attr = opts->attr;
8598 p.event_cb = opts->event_cb;
8600 p.cpu_cnt = opts->cpu_cnt;
8601 p.cpus = opts->cpus;
8602 p.map_keys = opts->map_keys;
8604 return __perf_buffer__new(map_fd, page_cnt, &p);
8607 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8608 struct perf_buffer_params *p)
8610 const char *online_cpus_file = "/sys/devices/system/cpu/online";
8611 struct bpf_map_info map;
8612 char msg[STRERR_BUFSIZE];
8613 struct perf_buffer *pb;
8614 bool *online = NULL;
8618 if (page_cnt & (page_cnt - 1)) {
8619 pr_warn("page count should be power of two, but is %zu\n",
8621 return ERR_PTR(-EINVAL);
8624 /* best-effort sanity checks */
8625 memset(&map, 0, sizeof(map));
8626 map_info_len = sizeof(map);
8627 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
8630 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
8631 * -EBADFD, -EFAULT, or -E2BIG on real error
8633 if (err != -EINVAL) {
8634 pr_warn("failed to get map info for map FD %d: %s\n",
8635 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
8636 return ERR_PTR(err);
8638 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
8641 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
8642 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
8644 return ERR_PTR(-EINVAL);
8648 pb = calloc(1, sizeof(*pb));
8650 return ERR_PTR(-ENOMEM);
8652 pb->event_cb = p->event_cb;
8653 pb->sample_cb = p->sample_cb;
8654 pb->lost_cb = p->lost_cb;
8657 pb->page_size = getpagesize();
8658 pb->mmap_size = pb->page_size * page_cnt;
8659 pb->map_fd = map_fd;
8661 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
8662 if (pb->epoll_fd < 0) {
8664 pr_warn("failed to create epoll instance: %s\n",
8665 libbpf_strerror_r(err, msg, sizeof(msg)));
8669 if (p->cpu_cnt > 0) {
8670 pb->cpu_cnt = p->cpu_cnt;
8672 pb->cpu_cnt = libbpf_num_possible_cpus();
8673 if (pb->cpu_cnt < 0) {
8677 if (map.max_entries && map.max_entries < pb->cpu_cnt)
8678 pb->cpu_cnt = map.max_entries;
8681 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
8684 pr_warn("failed to allocate events: out of memory\n");
8687 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
8688 if (!pb->cpu_bufs) {
8690 pr_warn("failed to allocate buffers: out of memory\n");
8694 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
8696 pr_warn("failed to get online CPU mask: %d\n", err);
8700 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
8701 struct perf_cpu_buf *cpu_buf;
8704 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
8705 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
8707 /* in case user didn't explicitly requested particular CPUs to
8708 * be attached to, skip offline/not present CPUs
8710 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
8713 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
8714 if (IS_ERR(cpu_buf)) {
8715 err = PTR_ERR(cpu_buf);
8719 pb->cpu_bufs[j] = cpu_buf;
8721 err = bpf_map_update_elem(pb->map_fd, &map_key,
8725 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
8726 cpu, map_key, cpu_buf->fd,
8727 libbpf_strerror_r(err, msg, sizeof(msg)));
8731 pb->events[j].events = EPOLLIN;
8732 pb->events[j].data.ptr = cpu_buf;
8733 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
8734 &pb->events[j]) < 0) {
8736 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
8738 libbpf_strerror_r(err, msg, sizeof(msg)));
8751 perf_buffer__free(pb);
8752 return ERR_PTR(err);
8755 struct perf_sample_raw {
8756 struct perf_event_header header;
8761 struct perf_sample_lost {
8762 struct perf_event_header header;
8768 static enum bpf_perf_event_ret
8769 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
8771 struct perf_cpu_buf *cpu_buf = ctx;
8772 struct perf_buffer *pb = cpu_buf->pb;
8775 /* user wants full control over parsing perf event */
8777 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
8780 case PERF_RECORD_SAMPLE: {
8781 struct perf_sample_raw *s = data;
8784 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
8787 case PERF_RECORD_LOST: {
8788 struct perf_sample_lost *s = data;
8791 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
8795 pr_warn("unknown perf sample type %d\n", e->type);
8796 return LIBBPF_PERF_EVENT_ERROR;
8798 return LIBBPF_PERF_EVENT_CONT;
8801 static int perf_buffer__process_records(struct perf_buffer *pb,
8802 struct perf_cpu_buf *cpu_buf)
8804 enum bpf_perf_event_ret ret;
8806 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
8807 pb->page_size, &cpu_buf->buf,
8809 perf_buffer__process_record, cpu_buf);
8810 if (ret != LIBBPF_PERF_EVENT_CONT)
8815 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
8819 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
8820 for (i = 0; i < cnt; i++) {
8821 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
8823 err = perf_buffer__process_records(pb, cpu_buf);
8825 pr_warn("error while processing records: %d\n", err);
8829 return cnt < 0 ? -errno : cnt;
8832 int perf_buffer__consume(struct perf_buffer *pb)
8836 for (i = 0; i < pb->cpu_cnt; i++) {
8837 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8842 err = perf_buffer__process_records(pb, cpu_buf);
8844 pr_warn("error while processing records: %d\n", err);
8851 struct bpf_prog_info_array_desc {
8852 int array_offset; /* e.g. offset of jited_prog_insns */
8853 int count_offset; /* e.g. offset of jited_prog_len */
8854 int size_offset; /* > 0: offset of rec size,
8855 * < 0: fix size of -size_offset
8859 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
8860 [BPF_PROG_INFO_JITED_INSNS] = {
8861 offsetof(struct bpf_prog_info, jited_prog_insns),
8862 offsetof(struct bpf_prog_info, jited_prog_len),
8865 [BPF_PROG_INFO_XLATED_INSNS] = {
8866 offsetof(struct bpf_prog_info, xlated_prog_insns),
8867 offsetof(struct bpf_prog_info, xlated_prog_len),
8870 [BPF_PROG_INFO_MAP_IDS] = {
8871 offsetof(struct bpf_prog_info, map_ids),
8872 offsetof(struct bpf_prog_info, nr_map_ids),
8873 -(int)sizeof(__u32),
8875 [BPF_PROG_INFO_JITED_KSYMS] = {
8876 offsetof(struct bpf_prog_info, jited_ksyms),
8877 offsetof(struct bpf_prog_info, nr_jited_ksyms),
8878 -(int)sizeof(__u64),
8880 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
8881 offsetof(struct bpf_prog_info, jited_func_lens),
8882 offsetof(struct bpf_prog_info, nr_jited_func_lens),
8883 -(int)sizeof(__u32),
8885 [BPF_PROG_INFO_FUNC_INFO] = {
8886 offsetof(struct bpf_prog_info, func_info),
8887 offsetof(struct bpf_prog_info, nr_func_info),
8888 offsetof(struct bpf_prog_info, func_info_rec_size),
8890 [BPF_PROG_INFO_LINE_INFO] = {
8891 offsetof(struct bpf_prog_info, line_info),
8892 offsetof(struct bpf_prog_info, nr_line_info),
8893 offsetof(struct bpf_prog_info, line_info_rec_size),
8895 [BPF_PROG_INFO_JITED_LINE_INFO] = {
8896 offsetof(struct bpf_prog_info, jited_line_info),
8897 offsetof(struct bpf_prog_info, nr_jited_line_info),
8898 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
8900 [BPF_PROG_INFO_PROG_TAGS] = {
8901 offsetof(struct bpf_prog_info, prog_tags),
8902 offsetof(struct bpf_prog_info, nr_prog_tags),
8903 -(int)sizeof(__u8) * BPF_TAG_SIZE,
8908 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
8911 __u32 *array = (__u32 *)info;
8914 return array[offset / sizeof(__u32)];
8915 return -(int)offset;
8918 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
8921 __u64 *array = (__u64 *)info;
8924 return array[offset / sizeof(__u64)];
8925 return -(int)offset;
8928 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
8931 __u32 *array = (__u32 *)info;
8934 array[offset / sizeof(__u32)] = val;
8937 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
8940 __u64 *array = (__u64 *)info;
8943 array[offset / sizeof(__u64)] = val;
8946 struct bpf_prog_info_linear *
8947 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
8949 struct bpf_prog_info_linear *info_linear;
8950 struct bpf_prog_info info = {};
8951 __u32 info_len = sizeof(info);
8956 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
8957 return ERR_PTR(-EINVAL);
8959 /* step 1: get array dimensions */
8960 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
8962 pr_debug("can't get prog info: %s", strerror(errno));
8963 return ERR_PTR(-EFAULT);
8966 /* step 2: calculate total size of all arrays */
8967 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8968 bool include_array = (arrays & (1UL << i)) > 0;
8969 struct bpf_prog_info_array_desc *desc;
8972 desc = bpf_prog_info_array_desc + i;
8974 /* kernel is too old to support this field */
8975 if (info_len < desc->array_offset + sizeof(__u32) ||
8976 info_len < desc->count_offset + sizeof(__u32) ||
8977 (desc->size_offset > 0 && info_len < desc->size_offset))
8978 include_array = false;
8980 if (!include_array) {
8981 arrays &= ~(1UL << i); /* clear the bit */
8985 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8986 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8988 data_len += count * size;
8991 /* step 3: allocate continuous memory */
8992 data_len = roundup(data_len, sizeof(__u64));
8993 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
8995 return ERR_PTR(-ENOMEM);
8997 /* step 4: fill data to info_linear->info */
8998 info_linear->arrays = arrays;
8999 memset(&info_linear->info, 0, sizeof(info));
9000 ptr = info_linear->data;
9002 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9003 struct bpf_prog_info_array_desc *desc;
9006 if ((arrays & (1UL << i)) == 0)
9009 desc = bpf_prog_info_array_desc + i;
9010 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
9011 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
9012 bpf_prog_info_set_offset_u32(&info_linear->info,
9013 desc->count_offset, count);
9014 bpf_prog_info_set_offset_u32(&info_linear->info,
9015 desc->size_offset, size);
9016 bpf_prog_info_set_offset_u64(&info_linear->info,
9019 ptr += count * size;
9022 /* step 5: call syscall again to get required arrays */
9023 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
9025 pr_debug("can't get prog info: %s", strerror(errno));
9027 return ERR_PTR(-EFAULT);
9030 /* step 6: verify the data */
9031 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9032 struct bpf_prog_info_array_desc *desc;
9035 if ((arrays & (1UL << i)) == 0)
9038 desc = bpf_prog_info_array_desc + i;
9039 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
9040 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
9041 desc->count_offset);
9043 pr_warn("%s: mismatch in element count\n", __func__);
9045 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
9046 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
9049 pr_warn("%s: mismatch in rec size\n", __func__);
9052 /* step 7: update info_len and data_len */
9053 info_linear->info_len = sizeof(struct bpf_prog_info);
9054 info_linear->data_len = data_len;
9059 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
9063 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
9064 struct bpf_prog_info_array_desc *desc;
9067 if ((info_linear->arrays & (1UL << i)) == 0)
9070 desc = bpf_prog_info_array_desc + i;
9071 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
9072 desc->array_offset);
9073 offs = addr - ptr_to_u64(info_linear->data);
9074 bpf_prog_info_set_offset_u64(&info_linear->info,
9075 desc->array_offset, offs);
9079 void bpf_program__bpil_offs_to_addr(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 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
9092 desc->array_offset);
9093 addr = offs + ptr_to_u64(info_linear->data);
9094 bpf_prog_info_set_offset_u64(&info_linear->info,
9095 desc->array_offset, addr);
9099 int bpf_program__set_attach_target(struct bpf_program *prog,
9101 const char *attach_func_name)
9105 if (!prog || attach_prog_fd < 0 || !attach_func_name)
9109 btf_id = libbpf_find_prog_btf_id(attach_func_name,
9112 btf_id = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
9114 prog->expected_attach_type);
9119 prog->attach_btf_id = btf_id;
9120 prog->attach_prog_fd = attach_prog_fd;
9124 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
9126 int err = 0, n, len, start, end = -1;
9132 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
9134 if (*s == ',' || *s == '\n') {
9138 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
9139 if (n <= 0 || n > 2) {
9140 pr_warn("Failed to get CPU range %s: %d\n", s, n);
9143 } else if (n == 1) {
9146 if (start < 0 || start > end) {
9147 pr_warn("Invalid CPU range [%d,%d] in %s\n",
9152 tmp = realloc(*mask, end + 1);
9158 memset(tmp + *mask_sz, 0, start - *mask_sz);
9159 memset(tmp + start, 1, end - start + 1);
9164 pr_warn("Empty CPU range\n");
9174 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
9176 int fd, err = 0, len;
9179 fd = open(fcpu, O_RDONLY);
9182 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
9185 len = read(fd, buf, sizeof(buf));
9188 err = len ? -errno : -EINVAL;
9189 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
9192 if (len >= sizeof(buf)) {
9193 pr_warn("CPU mask is too big in file %s\n", fcpu);
9198 return parse_cpu_mask_str(buf, mask, mask_sz);
9201 int libbpf_num_possible_cpus(void)
9203 static const char *fcpu = "/sys/devices/system/cpu/possible";
9205 int err, n, i, tmp_cpus;
9208 tmp_cpus = READ_ONCE(cpus);
9212 err = parse_cpu_mask_file(fcpu, &mask, &n);
9217 for (i = 0; i < n; i++) {
9223 WRITE_ONCE(cpus, tmp_cpus);
9227 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
9228 const struct bpf_object_open_opts *opts)
9230 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
9231 .object_name = s->name,
9233 struct bpf_object *obj;
9236 /* Attempt to preserve opts->object_name, unless overriden by user
9237 * explicitly. Overwriting object name for skeletons is discouraged,
9238 * as it breaks global data maps, because they contain object name
9239 * prefix as their own map name prefix. When skeleton is generated,
9240 * bpftool is making an assumption that this name will stay the same.
9243 memcpy(&skel_opts, opts, sizeof(*opts));
9244 if (!opts->object_name)
9245 skel_opts.object_name = s->name;
9248 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
9250 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
9251 s->name, PTR_ERR(obj));
9252 return PTR_ERR(obj);
9257 for (i = 0; i < s->map_cnt; i++) {
9258 struct bpf_map **map = s->maps[i].map;
9259 const char *name = s->maps[i].name;
9260 void **mmaped = s->maps[i].mmaped;
9262 *map = bpf_object__find_map_by_name(obj, name);
9264 pr_warn("failed to find skeleton map '%s'\n", name);
9268 /* externs shouldn't be pre-setup from user code */
9269 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
9270 *mmaped = (*map)->mmaped;
9273 for (i = 0; i < s->prog_cnt; i++) {
9274 struct bpf_program **prog = s->progs[i].prog;
9275 const char *name = s->progs[i].name;
9277 *prog = bpf_object__find_program_by_name(obj, name);
9279 pr_warn("failed to find skeleton program '%s'\n", name);
9287 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
9291 err = bpf_object__load(*s->obj);
9293 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
9297 for (i = 0; i < s->map_cnt; i++) {
9298 struct bpf_map *map = *s->maps[i].map;
9299 size_t mmap_sz = bpf_map_mmap_sz(map);
9300 int prot, map_fd = bpf_map__fd(map);
9301 void **mmaped = s->maps[i].mmaped;
9306 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
9311 if (map->def.map_flags & BPF_F_RDONLY_PROG)
9314 prot = PROT_READ | PROT_WRITE;
9316 /* Remap anonymous mmap()-ed "map initialization image" as
9317 * a BPF map-backed mmap()-ed memory, but preserving the same
9318 * memory address. This will cause kernel to change process'
9319 * page table to point to a different piece of kernel memory,
9320 * but from userspace point of view memory address (and its
9321 * contents, being identical at this point) will stay the
9322 * same. This mapping will be released by bpf_object__close()
9323 * as per normal clean up procedure, so we don't need to worry
9324 * about it from skeleton's clean up perspective.
9326 *mmaped = mmap(map->mmaped, mmap_sz, prot,
9327 MAP_SHARED | MAP_FIXED, map_fd, 0);
9328 if (*mmaped == MAP_FAILED) {
9331 pr_warn("failed to re-mmap() map '%s': %d\n",
9332 bpf_map__name(map), err);
9340 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
9344 for (i = 0; i < s->prog_cnt; i++) {
9345 struct bpf_program *prog = *s->progs[i].prog;
9346 struct bpf_link **link = s->progs[i].link;
9347 const struct bpf_sec_def *sec_def;
9348 const char *sec_name = bpf_program__title(prog, false);
9353 sec_def = find_sec_def(sec_name);
9354 if (!sec_def || !sec_def->attach_fn)
9357 *link = sec_def->attach_fn(sec_def, prog);
9358 if (IS_ERR(*link)) {
9359 pr_warn("failed to auto-attach program '%s': %ld\n",
9360 bpf_program__name(prog), PTR_ERR(*link));
9361 return PTR_ERR(*link);
9368 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
9372 for (i = 0; i < s->prog_cnt; i++) {
9373 struct bpf_link **link = s->progs[i].link;
9375 if (!IS_ERR_OR_NULL(*link))
9376 bpf_link__destroy(*link);
9381 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
9384 bpf_object__detach_skeleton(s);
9386 bpf_object__close(*s->obj);