1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
27 #include <asm/unistd.h>
28 #include <linux/err.h>
29 #include <linux/kernel.h>
30 #include <linux/bpf.h>
31 #include <linux/btf.h>
32 #include <linux/filter.h>
33 #include <linux/list.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
42 #include <sys/types.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <tools/libc_compat.h>
54 #include "str_error.h"
55 #include "libbpf_internal.h"
63 #define BPF_FS_MAGIC 0xcafe4a11
66 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
67 * compilation if user enables corresponding warning. Disable it explicitly.
69 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
71 #define __printf(a, b) __attribute__((format(printf, a, b)))
73 static struct btf *bpf_find_kernel_btf(void);
74 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
75 static struct bpf_program *bpf_object__find_prog_by_idx(struct bpf_object *obj,
77 static const struct btf_type *
78 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
80 static int __base_pr(enum libbpf_print_level level, const char *format,
83 if (level == LIBBPF_DEBUG)
86 return vfprintf(stderr, format, args);
89 static libbpf_print_fn_t __libbpf_pr = __base_pr;
91 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
93 libbpf_print_fn_t old_print_fn = __libbpf_pr;
100 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
107 va_start(args, format);
108 __libbpf_pr(level, format, args);
112 static void pr_perm_msg(int err)
117 if (err != -EPERM || geteuid() != 0)
120 err = getrlimit(RLIMIT_MEMLOCK, &limit);
124 if (limit.rlim_cur == RLIM_INFINITY)
127 if (limit.rlim_cur < 1024)
128 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
129 else if (limit.rlim_cur < 1024*1024)
130 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
132 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
134 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
138 #define STRERR_BUFSIZE 128
140 /* Copied from tools/perf/util/util.h */
142 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
146 # define zclose(fd) ({ \
149 ___err = close((fd)); \
154 #ifdef HAVE_LIBELF_MMAP_SUPPORT
155 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
157 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
160 static inline __u64 ptr_to_u64(const void *ptr)
162 return (__u64) (unsigned long) ptr;
165 struct bpf_capabilities {
166 /* v4.14: kernel support for program & map names. */
168 /* v5.2: kernel support for global data sections. */
170 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
172 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
174 /* BPF_F_MMAPABLE is supported for arrays */
176 /* BTF_FUNC_GLOBAL is supported */
177 __u32 btf_func_global:1;
188 enum reloc_type type;
195 * bpf_prog should be a better name but it has been used in
199 /* Index in elf obj file, for relocation use. */
204 /* section_name with / replaced by _; makes recursive pinning
205 * in bpf_object__pin_programs easier
208 struct bpf_insn *insns;
209 size_t insns_cnt, main_prog_cnt;
210 enum bpf_prog_type type;
212 struct reloc_desc *reloc_desc;
220 bpf_program_prep_t preprocessor;
222 struct bpf_object *obj;
224 bpf_program_clear_priv_t clear_priv;
226 enum bpf_attach_type expected_attach_type;
228 __u32 attach_prog_fd;
230 __u32 func_info_rec_size;
233 struct bpf_capabilities *caps;
236 __u32 line_info_rec_size;
241 struct bpf_struct_ops {
243 const struct btf_type *type;
244 struct bpf_program **progs;
245 __u32 *kern_func_off;
246 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
248 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
249 * btf_vmlinux's format.
250 * struct bpf_struct_ops_tcp_congestion_ops {
251 * [... some other kernel fields ...]
252 * struct tcp_congestion_ops data;
254 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
255 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
262 #define DATA_SEC ".data"
263 #define BSS_SEC ".bss"
264 #define RODATA_SEC ".rodata"
265 #define KCONFIG_SEC ".kconfig"
266 #define STRUCT_OPS_SEC ".struct_ops"
268 enum libbpf_map_type {
276 static const char * const libbpf_type_to_btf_name[] = {
277 [LIBBPF_MAP_DATA] = DATA_SEC,
278 [LIBBPF_MAP_BSS] = BSS_SEC,
279 [LIBBPF_MAP_RODATA] = RODATA_SEC,
280 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
290 struct bpf_map_def def;
291 __u32 btf_key_type_id;
292 __u32 btf_value_type_id;
293 __u32 btf_vmlinux_value_type_id;
295 bpf_map_clear_priv_t clear_priv;
296 enum libbpf_map_type libbpf_type;
298 struct bpf_struct_ops *st_ops;
317 enum extern_type type;
326 static LIST_HEAD(bpf_objects_list);
329 char name[BPF_OBJ_NAME_LEN];
333 struct bpf_program *programs;
335 struct bpf_map *maps;
340 struct extern_desc *externs;
345 bool has_pseudo_calls;
346 bool relaxed_core_relocs;
349 * Information when doing elf related work. Only valid if fd
362 Elf_Data *st_ops_data;
379 * All loaded bpf_object is linked in a list, which is
380 * hidden to caller. bpf_objects__<func> handlers deal with
383 struct list_head list;
386 struct btf_ext *btf_ext;
389 bpf_object_clear_priv_t clear_priv;
391 struct bpf_capabilities caps;
395 #define obj_elf_valid(o) ((o)->efile.elf)
397 void bpf_program__unload(struct bpf_program *prog)
405 * If the object is opened but the program was never loaded,
406 * it is possible that prog->instances.nr == -1.
408 if (prog->instances.nr > 0) {
409 for (i = 0; i < prog->instances.nr; i++)
410 zclose(prog->instances.fds[i]);
411 } else if (prog->instances.nr != -1) {
412 pr_warn("Internal error: instances.nr is %d\n",
416 prog->instances.nr = -1;
417 zfree(&prog->instances.fds);
419 zfree(&prog->func_info);
420 zfree(&prog->line_info);
423 static void bpf_program__exit(struct bpf_program *prog)
428 if (prog->clear_priv)
429 prog->clear_priv(prog, prog->priv);
432 prog->clear_priv = NULL;
434 bpf_program__unload(prog);
436 zfree(&prog->section_name);
437 zfree(&prog->pin_name);
439 zfree(&prog->reloc_desc);
446 static char *__bpf_program__pin_name(struct bpf_program *prog)
450 name = p = strdup(prog->section_name);
451 while ((p = strchr(p, '/')))
458 bpf_program__init(void *data, size_t size, char *section_name, int idx,
459 struct bpf_program *prog)
461 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
463 if (size == 0 || size % bpf_insn_sz) {
464 pr_warn("corrupted section '%s', size: %zu\n",
469 memset(prog, 0, sizeof(*prog));
471 prog->section_name = strdup(section_name);
472 if (!prog->section_name) {
473 pr_warn("failed to alloc name for prog under section(%d) %s\n",
478 prog->pin_name = __bpf_program__pin_name(prog);
479 if (!prog->pin_name) {
480 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
485 prog->insns = malloc(size);
487 pr_warn("failed to alloc insns for prog under section %s\n",
491 prog->insns_cnt = size / bpf_insn_sz;
492 memcpy(prog->insns, data, size);
494 prog->instances.fds = NULL;
495 prog->instances.nr = -1;
496 prog->type = BPF_PROG_TYPE_UNSPEC;
500 bpf_program__exit(prog);
505 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
506 char *section_name, int idx)
508 struct bpf_program prog, *progs;
511 err = bpf_program__init(data, size, section_name, idx, &prog);
515 prog.caps = &obj->caps;
516 progs = obj->programs;
517 nr_progs = obj->nr_programs;
519 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
522 * In this case the original obj->programs
523 * is still valid, so don't need special treat for
524 * bpf_close_object().
526 pr_warn("failed to alloc a new program under section '%s'\n",
528 bpf_program__exit(&prog);
532 pr_debug("found program %s\n", prog.section_name);
533 obj->programs = progs;
534 obj->nr_programs = nr_progs + 1;
536 progs[nr_progs] = prog;
541 bpf_object__init_prog_names(struct bpf_object *obj)
543 Elf_Data *symbols = obj->efile.symbols;
544 struct bpf_program *prog;
547 for (pi = 0; pi < obj->nr_programs; pi++) {
548 const char *name = NULL;
550 prog = &obj->programs[pi];
552 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
556 if (!gelf_getsym(symbols, si, &sym))
558 if (sym.st_shndx != prog->idx)
560 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
563 name = elf_strptr(obj->efile.elf,
564 obj->efile.strtabidx,
567 pr_warn("failed to get sym name string for prog %s\n",
569 return -LIBBPF_ERRNO__LIBELF;
573 if (!name && prog->idx == obj->efile.text_shndx)
577 pr_warn("failed to find sym for prog %s\n",
582 prog->name = strdup(name);
584 pr_warn("failed to allocate memory for prog sym %s\n",
593 static __u32 get_kernel_version(void)
595 __u32 major, minor, patch;
599 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
601 return KERNEL_VERSION(major, minor, patch);
604 static const struct btf_member *
605 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
607 struct btf_member *m;
610 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
611 if (btf_member_bit_offset(t, i) == bit_offset)
618 static const struct btf_member *
619 find_member_by_name(const struct btf *btf, const struct btf_type *t,
622 struct btf_member *m;
625 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
626 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
633 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
634 #define STRUCT_OPS_VALUE_PREFIX_LEN (sizeof(STRUCT_OPS_VALUE_PREFIX) - 1)
637 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
638 const struct btf_type **type, __u32 *type_id,
639 const struct btf_type **vtype, __u32 *vtype_id,
640 const struct btf_member **data_member)
642 const struct btf_type *kern_type, *kern_vtype;
643 const struct btf_member *kern_data_member;
644 __s32 kern_vtype_id, kern_type_id;
645 char vtname[128] = STRUCT_OPS_VALUE_PREFIX;
648 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
649 if (kern_type_id < 0) {
650 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
654 kern_type = btf__type_by_id(btf, kern_type_id);
656 /* Find the corresponding "map_value" type that will be used
657 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
658 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
661 strncat(vtname + STRUCT_OPS_VALUE_PREFIX_LEN, tname,
662 sizeof(vtname) - STRUCT_OPS_VALUE_PREFIX_LEN - 1);
663 kern_vtype_id = btf__find_by_name_kind(btf, vtname,
665 if (kern_vtype_id < 0) {
666 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
668 return kern_vtype_id;
670 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
672 /* Find "struct tcp_congestion_ops" from
673 * struct bpf_struct_ops_tcp_congestion_ops {
675 * struct tcp_congestion_ops data;
678 kern_data_member = btf_members(kern_vtype);
679 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
680 if (kern_data_member->type == kern_type_id)
683 if (i == btf_vlen(kern_vtype)) {
684 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
690 *type_id = kern_type_id;
692 *vtype_id = kern_vtype_id;
693 *data_member = kern_data_member;
698 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
700 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
703 /* Init the map's fields that depend on kern_btf */
704 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
705 const struct btf *btf,
706 const struct btf *kern_btf)
708 const struct btf_member *member, *kern_member, *kern_data_member;
709 const struct btf_type *type, *kern_type, *kern_vtype;
710 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
711 struct bpf_struct_ops *st_ops;
712 void *data, *kern_data;
716 st_ops = map->st_ops;
718 tname = st_ops->tname;
719 err = find_struct_ops_kern_types(kern_btf, tname,
720 &kern_type, &kern_type_id,
721 &kern_vtype, &kern_vtype_id,
726 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
727 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
729 map->def.value_size = kern_vtype->size;
730 map->btf_vmlinux_value_type_id = kern_vtype_id;
732 st_ops->kern_vdata = calloc(1, kern_vtype->size);
733 if (!st_ops->kern_vdata)
737 kern_data_off = kern_data_member->offset / 8;
738 kern_data = st_ops->kern_vdata + kern_data_off;
740 member = btf_members(type);
741 for (i = 0; i < btf_vlen(type); i++, member++) {
742 const struct btf_type *mtype, *kern_mtype;
743 __u32 mtype_id, kern_mtype_id;
744 void *mdata, *kern_mdata;
745 __s64 msize, kern_msize;
746 __u32 moff, kern_moff;
747 __u32 kern_member_idx;
750 mname = btf__name_by_offset(btf, member->name_off);
751 kern_member = find_member_by_name(kern_btf, kern_type, mname);
753 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
758 kern_member_idx = kern_member - btf_members(kern_type);
759 if (btf_member_bitfield_size(type, i) ||
760 btf_member_bitfield_size(kern_type, kern_member_idx)) {
761 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
766 moff = member->offset / 8;
767 kern_moff = kern_member->offset / 8;
770 kern_mdata = kern_data + kern_moff;
772 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
773 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
775 if (BTF_INFO_KIND(mtype->info) !=
776 BTF_INFO_KIND(kern_mtype->info)) {
777 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
778 map->name, mname, BTF_INFO_KIND(mtype->info),
779 BTF_INFO_KIND(kern_mtype->info));
783 if (btf_is_ptr(mtype)) {
784 struct bpf_program *prog;
786 mtype = skip_mods_and_typedefs(btf, mtype->type, &mtype_id);
787 kern_mtype = skip_mods_and_typedefs(kern_btf,
790 if (!btf_is_func_proto(mtype) ||
791 !btf_is_func_proto(kern_mtype)) {
792 pr_warn("struct_ops init_kern %s: non func ptr %s is not supported\n",
797 prog = st_ops->progs[i];
799 pr_debug("struct_ops init_kern %s: func ptr %s is not set\n",
804 prog->attach_btf_id = kern_type_id;
805 prog->expected_attach_type = kern_member_idx;
807 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
809 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
810 map->name, mname, prog->name, moff,
816 msize = btf__resolve_size(btf, mtype_id);
817 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
818 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
819 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
820 map->name, mname, (ssize_t)msize,
821 (ssize_t)kern_msize);
825 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
826 map->name, mname, (unsigned int)msize,
828 memcpy(kern_mdata, mdata, msize);
834 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
836 struct btf *kern_btf = NULL;
841 for (i = 0; i < obj->nr_maps; i++) {
844 if (!bpf_map__is_struct_ops(map))
848 kern_btf = bpf_find_kernel_btf();
849 if (IS_ERR(kern_btf))
850 return PTR_ERR(kern_btf);
853 err = bpf_map__init_kern_struct_ops(map, obj->btf, kern_btf);
864 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
866 const struct btf_type *type, *datasec;
867 const struct btf_var_secinfo *vsi;
868 struct bpf_struct_ops *st_ops;
869 const char *tname, *var_name;
870 __s32 type_id, datasec_id;
871 const struct btf *btf;
875 if (obj->efile.st_ops_shndx == -1)
879 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
881 if (datasec_id < 0) {
882 pr_warn("struct_ops init: DATASEC %s not found\n",
887 datasec = btf__type_by_id(btf, datasec_id);
888 vsi = btf_var_secinfos(datasec);
889 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
890 type = btf__type_by_id(obj->btf, vsi->type);
891 var_name = btf__name_by_offset(obj->btf, type->name_off);
893 type_id = btf__resolve_type(obj->btf, vsi->type);
895 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
896 vsi->type, STRUCT_OPS_SEC);
900 type = btf__type_by_id(obj->btf, type_id);
901 tname = btf__name_by_offset(obj->btf, type->name_off);
903 pr_warn("struct_ops init: anonymous type is not supported\n");
906 if (!btf_is_struct(type)) {
907 pr_warn("struct_ops init: %s is not a struct\n", tname);
911 map = bpf_object__add_map(obj);
915 map->sec_idx = obj->efile.st_ops_shndx;
916 map->sec_offset = vsi->offset;
917 map->name = strdup(var_name);
921 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
922 map->def.key_size = sizeof(int);
923 map->def.value_size = type->size;
924 map->def.max_entries = 1;
926 map->st_ops = calloc(1, sizeof(*map->st_ops));
929 st_ops = map->st_ops;
930 st_ops->data = malloc(type->size);
931 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
932 st_ops->kern_func_off = malloc(btf_vlen(type) *
933 sizeof(*st_ops->kern_func_off));
934 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
937 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
938 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
939 var_name, STRUCT_OPS_SEC);
944 obj->efile.st_ops_data->d_buf + vsi->offset,
946 st_ops->tname = tname;
948 st_ops->type_id = type_id;
950 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
951 tname, type_id, var_name, vsi->offset);
957 static struct bpf_object *bpf_object__new(const char *path,
960 const char *obj_name)
962 struct bpf_object *obj;
965 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
967 pr_warn("alloc memory failed for %s\n", path);
968 return ERR_PTR(-ENOMEM);
971 strcpy(obj->path, path);
973 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
974 obj->name[sizeof(obj->name) - 1] = 0;
976 /* Using basename() GNU version which doesn't modify arg. */
977 strncpy(obj->name, basename((void *)path),
978 sizeof(obj->name) - 1);
979 end = strchr(obj->name, '.');
986 * Caller of this function should also call
987 * bpf_object__elf_finish() after data collection to return
988 * obj_buf to user. If not, we should duplicate the buffer to
989 * avoid user freeing them before elf finish.
991 obj->efile.obj_buf = obj_buf;
992 obj->efile.obj_buf_sz = obj_buf_sz;
993 obj->efile.maps_shndx = -1;
994 obj->efile.btf_maps_shndx = -1;
995 obj->efile.data_shndx = -1;
996 obj->efile.rodata_shndx = -1;
997 obj->efile.bss_shndx = -1;
998 obj->efile.st_ops_shndx = -1;
999 obj->kconfig_map_idx = -1;
1001 obj->kern_version = get_kernel_version();
1002 obj->loaded = false;
1004 INIT_LIST_HEAD(&obj->list);
1005 list_add(&obj->list, &bpf_objects_list);
1009 static void bpf_object__elf_finish(struct bpf_object *obj)
1011 if (!obj_elf_valid(obj))
1014 if (obj->efile.elf) {
1015 elf_end(obj->efile.elf);
1016 obj->efile.elf = NULL;
1018 obj->efile.symbols = NULL;
1019 obj->efile.data = NULL;
1020 obj->efile.rodata = NULL;
1021 obj->efile.bss = NULL;
1022 obj->efile.st_ops_data = NULL;
1024 zfree(&obj->efile.reloc_sects);
1025 obj->efile.nr_reloc_sects = 0;
1026 zclose(obj->efile.fd);
1027 obj->efile.obj_buf = NULL;
1028 obj->efile.obj_buf_sz = 0;
1031 static int bpf_object__elf_init(struct bpf_object *obj)
1036 if (obj_elf_valid(obj)) {
1037 pr_warn("elf init: internal error\n");
1038 return -LIBBPF_ERRNO__LIBELF;
1041 if (obj->efile.obj_buf_sz > 0) {
1043 * obj_buf should have been validated by
1044 * bpf_object__open_buffer().
1046 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1047 obj->efile.obj_buf_sz);
1049 obj->efile.fd = open(obj->path, O_RDONLY);
1050 if (obj->efile.fd < 0) {
1051 char errmsg[STRERR_BUFSIZE], *cp;
1054 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1055 pr_warn("failed to open %s: %s\n", obj->path, cp);
1059 obj->efile.elf = elf_begin(obj->efile.fd,
1060 LIBBPF_ELF_C_READ_MMAP, NULL);
1063 if (!obj->efile.elf) {
1064 pr_warn("failed to open %s as ELF file\n", obj->path);
1065 err = -LIBBPF_ERRNO__LIBELF;
1069 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1070 pr_warn("failed to get EHDR from %s\n", obj->path);
1071 err = -LIBBPF_ERRNO__FORMAT;
1074 ep = &obj->efile.ehdr;
1076 /* Old LLVM set e_machine to EM_NONE */
1077 if (ep->e_type != ET_REL ||
1078 (ep->e_machine && ep->e_machine != EM_BPF)) {
1079 pr_warn("%s is not an eBPF object file\n", obj->path);
1080 err = -LIBBPF_ERRNO__FORMAT;
1086 bpf_object__elf_finish(obj);
1090 static int bpf_object__check_endianness(struct bpf_object *obj)
1092 #if __BYTE_ORDER == __LITTLE_ENDIAN
1093 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1095 #elif __BYTE_ORDER == __BIG_ENDIAN
1096 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1099 # error "Unrecognized __BYTE_ORDER__"
1101 pr_warn("endianness mismatch.\n");
1102 return -LIBBPF_ERRNO__ENDIAN;
1106 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1108 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1109 pr_debug("license of %s is %s\n", obj->path, obj->license);
1114 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1118 if (size != sizeof(kver)) {
1119 pr_warn("invalid kver section in %s\n", obj->path);
1120 return -LIBBPF_ERRNO__FORMAT;
1122 memcpy(&kver, data, sizeof(kver));
1123 obj->kern_version = kver;
1124 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1128 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1130 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1131 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1136 static int bpf_object_search_section_size(const struct bpf_object *obj,
1137 const char *name, size_t *d_size)
1139 const GElf_Ehdr *ep = &obj->efile.ehdr;
1140 Elf *elf = obj->efile.elf;
1141 Elf_Scn *scn = NULL;
1144 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1145 const char *sec_name;
1150 if (gelf_getshdr(scn, &sh) != &sh) {
1151 pr_warn("failed to get section(%d) header from %s\n",
1156 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1158 pr_warn("failed to get section(%d) name from %s\n",
1163 if (strcmp(name, sec_name))
1166 data = elf_getdata(scn, 0);
1168 pr_warn("failed to get section(%d) data from %s(%s)\n",
1169 idx, name, obj->path);
1173 *d_size = data->d_size;
1180 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1189 } else if (!strcmp(name, DATA_SEC)) {
1190 if (obj->efile.data)
1191 *size = obj->efile.data->d_size;
1192 } else if (!strcmp(name, BSS_SEC)) {
1194 *size = obj->efile.bss->d_size;
1195 } else if (!strcmp(name, RODATA_SEC)) {
1196 if (obj->efile.rodata)
1197 *size = obj->efile.rodata->d_size;
1198 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1199 if (obj->efile.st_ops_data)
1200 *size = obj->efile.st_ops_data->d_size;
1202 ret = bpf_object_search_section_size(obj, name, &d_size);
1207 return *size ? 0 : ret;
1210 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1213 Elf_Data *symbols = obj->efile.symbols;
1220 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1223 if (!gelf_getsym(symbols, si, &sym))
1225 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1226 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1229 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1232 pr_warn("failed to get sym name string for var %s\n",
1236 if (strcmp(name, sname) == 0) {
1237 *off = sym.st_value;
1245 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1247 struct bpf_map *new_maps;
1251 if (obj->nr_maps < obj->maps_cap)
1252 return &obj->maps[obj->nr_maps++];
1254 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1255 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
1257 pr_warn("alloc maps for object failed\n");
1258 return ERR_PTR(-ENOMEM);
1261 obj->maps_cap = new_cap;
1262 obj->maps = new_maps;
1264 /* zero out new maps */
1265 memset(obj->maps + obj->nr_maps, 0,
1266 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1268 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1269 * when failure (zclose won't close negative fd)).
1271 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1272 obj->maps[i].fd = -1;
1273 obj->maps[i].inner_map_fd = -1;
1276 return &obj->maps[obj->nr_maps++];
1279 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1281 long page_sz = sysconf(_SC_PAGE_SIZE);
1284 map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
1285 map_sz = roundup(map_sz, page_sz);
1289 static char *internal_map_name(struct bpf_object *obj,
1290 enum libbpf_map_type type)
1292 char map_name[BPF_OBJ_NAME_LEN];
1293 const char *sfx = libbpf_type_to_btf_name[type];
1294 int sfx_len = max((size_t)7, strlen(sfx));
1295 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1298 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1299 sfx_len, libbpf_type_to_btf_name[type]);
1301 return strdup(map_name);
1305 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1306 int sec_idx, void *data, size_t data_sz)
1308 struct bpf_map_def *def;
1309 struct bpf_map *map;
1312 map = bpf_object__add_map(obj);
1314 return PTR_ERR(map);
1316 map->libbpf_type = type;
1317 map->sec_idx = sec_idx;
1318 map->sec_offset = 0;
1319 map->name = internal_map_name(obj, type);
1321 pr_warn("failed to alloc map name\n");
1326 def->type = BPF_MAP_TYPE_ARRAY;
1327 def->key_size = sizeof(int);
1328 def->value_size = data_sz;
1329 def->max_entries = 1;
1330 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1331 ? BPF_F_RDONLY_PROG : 0;
1332 def->map_flags |= BPF_F_MMAPABLE;
1334 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1335 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1337 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1338 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1339 if (map->mmaped == MAP_FAILED) {
1342 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1349 memcpy(map->mmaped, data, data_sz);
1351 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1355 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1360 * Populate obj->maps with libbpf internal maps.
1362 if (obj->efile.data_shndx >= 0) {
1363 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1364 obj->efile.data_shndx,
1365 obj->efile.data->d_buf,
1366 obj->efile.data->d_size);
1370 if (obj->efile.rodata_shndx >= 0) {
1371 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1372 obj->efile.rodata_shndx,
1373 obj->efile.rodata->d_buf,
1374 obj->efile.rodata->d_size);
1378 if (obj->efile.bss_shndx >= 0) {
1379 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1380 obj->efile.bss_shndx,
1382 obj->efile.bss->d_size);
1390 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1395 for (i = 0; i < obj->nr_extern; i++) {
1396 if (strcmp(obj->externs[i].name, name) == 0)
1397 return &obj->externs[i];
1402 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1405 switch (ext->type) {
1408 pr_warn("extern %s=%c should be tristate or char\n",
1412 *(bool *)ext_val = value == 'y' ? true : false;
1416 *(enum libbpf_tristate *)ext_val = TRI_YES;
1417 else if (value == 'm')
1418 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1419 else /* value == 'n' */
1420 *(enum libbpf_tristate *)ext_val = TRI_NO;
1423 *(char *)ext_val = value;
1429 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1437 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1442 if (ext->type != EXT_CHAR_ARR) {
1443 pr_warn("extern %s=%s should char array\n", ext->name, value);
1447 len = strlen(value);
1448 if (value[len - 1] != '"') {
1449 pr_warn("extern '%s': invalid string config '%s'\n",
1456 if (len >= ext->sz) {
1457 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1458 ext->name, value, len, ext->sz - 1);
1461 memcpy(ext_val, value + 1, len);
1462 ext_val[len] = '\0';
1467 static int parse_u64(const char *value, __u64 *res)
1473 *res = strtoull(value, &value_end, 0);
1476 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1480 pr_warn("failed to parse '%s' as integer completely\n", value);
1486 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1488 int bit_sz = ext->sz * 8;
1493 /* Validate that value stored in u64 fits in integer of `ext->sz`
1494 * bytes size without any loss of information. If the target integer
1495 * is signed, we rely on the following limits of integer type of
1496 * Y bits and subsequent transformation:
1498 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1499 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1500 * 0 <= X + 2^(Y-1) < 2^Y
1502 * For unsigned target integer, check that all the (64 - Y) bits are
1506 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1508 return (v >> bit_sz) == 0;
1511 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1514 if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1515 pr_warn("extern %s=%llu should be integer\n",
1516 ext->name, (unsigned long long)value);
1519 if (!is_ext_value_in_range(ext, value)) {
1520 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1521 ext->name, (unsigned long long)value, ext->sz);
1525 case 1: *(__u8 *)ext_val = value; break;
1526 case 2: *(__u16 *)ext_val = value; break;
1527 case 4: *(__u32 *)ext_val = value; break;
1528 case 8: *(__u64 *)ext_val = value; break;
1536 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1537 char *buf, void *data)
1539 struct extern_desc *ext;
1545 if (strncmp(buf, "CONFIG_", 7))
1548 sep = strchr(buf, '=');
1550 pr_warn("failed to parse '%s': no separator\n", buf);
1554 /* Trim ending '\n' */
1556 if (buf[len - 1] == '\n')
1557 buf[len - 1] = '\0';
1558 /* Split on '=' and ensure that a value is present. */
1562 pr_warn("failed to parse '%s': no value\n", buf);
1566 ext = find_extern_by_name(obj, buf);
1567 if (!ext || ext->is_set)
1570 ext_val = data + ext->data_off;
1574 case 'y': case 'n': case 'm':
1575 err = set_ext_value_tri(ext, ext_val, *value);
1578 err = set_ext_value_str(ext, ext_val, value);
1581 /* assume integer */
1582 err = parse_u64(value, &num);
1584 pr_warn("extern %s=%s should be integer\n",
1588 err = set_ext_value_num(ext, ext_val, num);
1593 pr_debug("extern %s=%s\n", ext->name, value);
1597 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1605 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1608 else if (len >= PATH_MAX)
1609 return -ENAMETOOLONG;
1611 /* gzopen also accepts uncompressed files. */
1612 file = gzopen(buf, "r");
1614 file = gzopen("/proc/config.gz", "r");
1617 pr_warn("failed to open system Kconfig\n");
1621 while (gzgets(file, buf, sizeof(buf))) {
1622 err = bpf_object__process_kconfig_line(obj, buf, data);
1624 pr_warn("error parsing system Kconfig line '%s': %d\n",
1635 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1636 const char *config, void *data)
1642 file = fmemopen((void *)config, strlen(config), "r");
1645 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1649 while (fgets(buf, sizeof(buf), file)) {
1650 err = bpf_object__process_kconfig_line(obj, buf, data);
1652 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1662 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1664 struct extern_desc *last_ext;
1668 if (obj->nr_extern == 0)
1671 last_ext = &obj->externs[obj->nr_extern - 1];
1672 map_sz = last_ext->data_off + last_ext->sz;
1674 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1675 obj->efile.symbols_shndx,
1680 obj->kconfig_map_idx = obj->nr_maps - 1;
1685 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1687 Elf_Data *symbols = obj->efile.symbols;
1688 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1689 Elf_Data *data = NULL;
1692 if (obj->efile.maps_shndx < 0)
1698 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1700 data = elf_getdata(scn, NULL);
1701 if (!scn || !data) {
1702 pr_warn("failed to get Elf_Data from map section %d\n",
1703 obj->efile.maps_shndx);
1708 * Count number of maps. Each map has a name.
1709 * Array of maps is not supported: only the first element is
1712 * TODO: Detect array of map and report error.
1714 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1715 for (i = 0; i < nr_syms; i++) {
1718 if (!gelf_getsym(symbols, i, &sym))
1720 if (sym.st_shndx != obj->efile.maps_shndx)
1724 /* Assume equally sized map definitions */
1725 pr_debug("maps in %s: %d maps in %zd bytes\n",
1726 obj->path, nr_maps, data->d_size);
1728 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1729 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1730 obj->path, nr_maps, data->d_size);
1733 map_def_sz = data->d_size / nr_maps;
1735 /* Fill obj->maps using data in "maps" section. */
1736 for (i = 0; i < nr_syms; i++) {
1738 const char *map_name;
1739 struct bpf_map_def *def;
1740 struct bpf_map *map;
1742 if (!gelf_getsym(symbols, i, &sym))
1744 if (sym.st_shndx != obj->efile.maps_shndx)
1747 map = bpf_object__add_map(obj);
1749 return PTR_ERR(map);
1751 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1754 pr_warn("failed to get map #%d name sym string for obj %s\n",
1756 return -LIBBPF_ERRNO__FORMAT;
1759 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1760 map->sec_idx = sym.st_shndx;
1761 map->sec_offset = sym.st_value;
1762 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1763 map_name, map->sec_idx, map->sec_offset);
1764 if (sym.st_value + map_def_sz > data->d_size) {
1765 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1766 obj->path, map_name);
1770 map->name = strdup(map_name);
1772 pr_warn("failed to alloc map name\n");
1775 pr_debug("map %d is \"%s\"\n", i, map->name);
1776 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1778 * If the definition of the map in the object file fits in
1779 * bpf_map_def, copy it. Any extra fields in our version
1780 * of bpf_map_def will default to zero as a result of the
1783 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1784 memcpy(&map->def, def, map_def_sz);
1787 * Here the map structure being read is bigger than what
1788 * we expect, truncate if the excess bits are all zero.
1789 * If they are not zero, reject this map as
1794 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1795 b < ((char *)def) + map_def_sz; b++) {
1797 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1798 obj->path, map_name);
1803 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1809 static const struct btf_type *
1810 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1812 const struct btf_type *t = btf__type_by_id(btf, id);
1817 while (btf_is_mod(t) || btf_is_typedef(t)) {
1820 t = btf__type_by_id(btf, t->type);
1826 static const struct btf_type *
1827 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1829 const struct btf_type *t;
1831 t = skip_mods_and_typedefs(btf, id, NULL);
1835 t = skip_mods_and_typedefs(btf, t->type, res_id);
1837 return btf_is_func_proto(t) ? t : NULL;
1841 * Fetch integer attribute of BTF map definition. Such attributes are
1842 * represented using a pointer to an array, in which dimensionality of array
1843 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1844 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1845 * type definition, while using only sizeof(void *) space in ELF data section.
1847 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1848 const struct btf_type *def,
1849 const struct btf_member *m, __u32 *res)
1851 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1852 const char *name = btf__name_by_offset(btf, m->name_off);
1853 const struct btf_array *arr_info;
1854 const struct btf_type *arr_t;
1856 if (!btf_is_ptr(t)) {
1857 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1858 map_name, name, btf_kind(t));
1862 arr_t = btf__type_by_id(btf, t->type);
1864 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1865 map_name, name, t->type);
1868 if (!btf_is_array(arr_t)) {
1869 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1870 map_name, name, btf_kind(arr_t));
1873 arr_info = btf_array(arr_t);
1874 *res = arr_info->nelems;
1878 static int build_map_pin_path(struct bpf_map *map, const char *path)
1884 path = "/sys/fs/bpf";
1886 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1889 else if (len >= PATH_MAX)
1890 return -ENAMETOOLONG;
1892 err = bpf_map__set_pin_path(map, buf);
1899 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1900 const struct btf_type *sec,
1901 int var_idx, int sec_idx,
1902 const Elf_Data *data, bool strict,
1903 const char *pin_root_path)
1905 const struct btf_type *var, *def, *t;
1906 const struct btf_var_secinfo *vi;
1907 const struct btf_var *var_extra;
1908 const struct btf_member *m;
1909 const char *map_name;
1910 struct bpf_map *map;
1913 vi = btf_var_secinfos(sec) + var_idx;
1914 var = btf__type_by_id(obj->btf, vi->type);
1915 var_extra = btf_var(var);
1916 map_name = btf__name_by_offset(obj->btf, var->name_off);
1917 vlen = btf_vlen(var);
1919 if (map_name == NULL || map_name[0] == '\0') {
1920 pr_warn("map #%d: empty name.\n", var_idx);
1923 if ((__u64)vi->offset + vi->size > data->d_size) {
1924 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1927 if (!btf_is_var(var)) {
1928 pr_warn("map '%s': unexpected var kind %u.\n",
1929 map_name, btf_kind(var));
1932 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1933 var_extra->linkage != BTF_VAR_STATIC) {
1934 pr_warn("map '%s': unsupported var linkage %u.\n",
1935 map_name, var_extra->linkage);
1939 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1940 if (!btf_is_struct(def)) {
1941 pr_warn("map '%s': unexpected def kind %u.\n",
1942 map_name, btf_kind(var));
1945 if (def->size > vi->size) {
1946 pr_warn("map '%s': invalid def size.\n", map_name);
1950 map = bpf_object__add_map(obj);
1952 return PTR_ERR(map);
1953 map->name = strdup(map_name);
1955 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1958 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1959 map->def.type = BPF_MAP_TYPE_UNSPEC;
1960 map->sec_idx = sec_idx;
1961 map->sec_offset = vi->offset;
1962 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1963 map_name, map->sec_idx, map->sec_offset);
1965 vlen = btf_vlen(def);
1966 m = btf_members(def);
1967 for (i = 0; i < vlen; i++, m++) {
1968 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1971 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1974 if (strcmp(name, "type") == 0) {
1975 if (!get_map_field_int(map_name, obj->btf, def, m,
1978 pr_debug("map '%s': found type = %u.\n",
1979 map_name, map->def.type);
1980 } else if (strcmp(name, "max_entries") == 0) {
1981 if (!get_map_field_int(map_name, obj->btf, def, m,
1982 &map->def.max_entries))
1984 pr_debug("map '%s': found max_entries = %u.\n",
1985 map_name, map->def.max_entries);
1986 } else if (strcmp(name, "map_flags") == 0) {
1987 if (!get_map_field_int(map_name, obj->btf, def, m,
1988 &map->def.map_flags))
1990 pr_debug("map '%s': found map_flags = %u.\n",
1991 map_name, map->def.map_flags);
1992 } else if (strcmp(name, "key_size") == 0) {
1995 if (!get_map_field_int(map_name, obj->btf, def, m,
1998 pr_debug("map '%s': found key_size = %u.\n",
2000 if (map->def.key_size && map->def.key_size != sz) {
2001 pr_warn("map '%s': conflicting key size %u != %u.\n",
2002 map_name, map->def.key_size, sz);
2005 map->def.key_size = sz;
2006 } else if (strcmp(name, "key") == 0) {
2009 t = btf__type_by_id(obj->btf, m->type);
2011 pr_warn("map '%s': key type [%d] not found.\n",
2015 if (!btf_is_ptr(t)) {
2016 pr_warn("map '%s': key spec is not PTR: %u.\n",
2017 map_name, btf_kind(t));
2020 sz = btf__resolve_size(obj->btf, t->type);
2022 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2023 map_name, t->type, (ssize_t)sz);
2026 pr_debug("map '%s': found key [%u], sz = %zd.\n",
2027 map_name, t->type, (ssize_t)sz);
2028 if (map->def.key_size && map->def.key_size != sz) {
2029 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2030 map_name, map->def.key_size, (ssize_t)sz);
2033 map->def.key_size = sz;
2034 map->btf_key_type_id = t->type;
2035 } else if (strcmp(name, "value_size") == 0) {
2038 if (!get_map_field_int(map_name, obj->btf, def, m,
2041 pr_debug("map '%s': found value_size = %u.\n",
2043 if (map->def.value_size && map->def.value_size != sz) {
2044 pr_warn("map '%s': conflicting value size %u != %u.\n",
2045 map_name, map->def.value_size, sz);
2048 map->def.value_size = sz;
2049 } else if (strcmp(name, "value") == 0) {
2052 t = btf__type_by_id(obj->btf, m->type);
2054 pr_warn("map '%s': value type [%d] not found.\n",
2058 if (!btf_is_ptr(t)) {
2059 pr_warn("map '%s': value spec is not PTR: %u.\n",
2060 map_name, btf_kind(t));
2063 sz = btf__resolve_size(obj->btf, t->type);
2065 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2066 map_name, t->type, (ssize_t)sz);
2069 pr_debug("map '%s': found value [%u], sz = %zd.\n",
2070 map_name, t->type, (ssize_t)sz);
2071 if (map->def.value_size && map->def.value_size != sz) {
2072 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2073 map_name, map->def.value_size, (ssize_t)sz);
2076 map->def.value_size = sz;
2077 map->btf_value_type_id = t->type;
2078 } else if (strcmp(name, "pinning") == 0) {
2082 if (!get_map_field_int(map_name, obj->btf, def, m,
2085 pr_debug("map '%s': found pinning = %u.\n",
2088 if (val != LIBBPF_PIN_NONE &&
2089 val != LIBBPF_PIN_BY_NAME) {
2090 pr_warn("map '%s': invalid pinning value %u.\n",
2094 if (val == LIBBPF_PIN_BY_NAME) {
2095 err = build_map_pin_path(map, pin_root_path);
2097 pr_warn("map '%s': couldn't build pin path.\n",
2104 pr_warn("map '%s': unknown field '%s'.\n",
2108 pr_debug("map '%s': ignoring unknown field '%s'.\n",
2113 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
2114 pr_warn("map '%s': map type isn't specified.\n", map_name);
2121 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2122 const char *pin_root_path)
2124 const struct btf_type *sec = NULL;
2125 int nr_types, i, vlen, err;
2126 const struct btf_type *t;
2131 if (obj->efile.btf_maps_shndx < 0)
2134 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
2136 data = elf_getdata(scn, NULL);
2137 if (!scn || !data) {
2138 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
2139 obj->efile.maps_shndx, MAPS_ELF_SEC);
2143 nr_types = btf__get_nr_types(obj->btf);
2144 for (i = 1; i <= nr_types; i++) {
2145 t = btf__type_by_id(obj->btf, i);
2146 if (!btf_is_datasec(t))
2148 name = btf__name_by_offset(obj->btf, t->name_off);
2149 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2156 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2160 vlen = btf_vlen(sec);
2161 for (i = 0; i < vlen; i++) {
2162 err = bpf_object__init_user_btf_map(obj, sec, i,
2163 obj->efile.btf_maps_shndx,
2173 static int bpf_object__init_maps(struct bpf_object *obj,
2174 const struct bpf_object_open_opts *opts)
2176 const char *pin_root_path;
2180 strict = !OPTS_GET(opts, relaxed_maps, false);
2181 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2183 err = bpf_object__init_user_maps(obj, strict);
2184 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2185 err = err ?: bpf_object__init_global_data_maps(obj);
2186 err = err ?: bpf_object__init_kconfig_map(obj);
2187 err = err ?: bpf_object__init_struct_ops_maps(obj);
2194 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2199 scn = elf_getscn(obj->efile.elf, idx);
2203 if (gelf_getshdr(scn, &sh) != &sh)
2206 if (sh.sh_flags & SHF_EXECINSTR)
2212 static void bpf_object__sanitize_btf(struct bpf_object *obj)
2214 bool has_func_global = obj->caps.btf_func_global;
2215 bool has_datasec = obj->caps.btf_datasec;
2216 bool has_func = obj->caps.btf_func;
2217 struct btf *btf = obj->btf;
2221 if (!obj->btf || (has_func && has_datasec && has_func_global))
2224 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2225 t = (struct btf_type *)btf__type_by_id(btf, i);
2227 if (!has_datasec && btf_is_var(t)) {
2228 /* replace VAR with INT */
2229 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2231 * using size = 1 is the safest choice, 4 will be too
2232 * big and cause kernel BTF validation failure if
2233 * original variable took less than 4 bytes
2236 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2237 } else if (!has_datasec && btf_is_datasec(t)) {
2238 /* replace DATASEC with STRUCT */
2239 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2240 struct btf_member *m = btf_members(t);
2241 struct btf_type *vt;
2244 name = (char *)btf__name_by_offset(btf, t->name_off);
2252 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2253 for (j = 0; j < vlen; j++, v++, m++) {
2254 /* order of field assignments is important */
2255 m->offset = v->offset * 8;
2257 /* preserve variable name as member name */
2258 vt = (void *)btf__type_by_id(btf, v->type);
2259 m->name_off = vt->name_off;
2261 } else if (!has_func && btf_is_func_proto(t)) {
2262 /* replace FUNC_PROTO with ENUM */
2264 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2265 t->size = sizeof(__u32); /* kernel enforced */
2266 } else if (!has_func && btf_is_func(t)) {
2267 /* replace FUNC with TYPEDEF */
2268 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2269 } else if (!has_func_global && btf_is_func(t)) {
2270 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2271 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2276 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
2281 if (!obj->caps.btf_func) {
2282 btf_ext__free(obj->btf_ext);
2283 obj->btf_ext = NULL;
2287 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
2289 return obj->efile.btf_maps_shndx >= 0 ||
2290 obj->efile.st_ops_shndx >= 0 ||
2294 static int bpf_object__init_btf(struct bpf_object *obj,
2296 Elf_Data *btf_ext_data)
2298 bool btf_required = bpf_object__is_btf_mandatory(obj);
2302 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2303 if (IS_ERR(obj->btf)) {
2304 pr_warn("Error loading ELF section %s: %d.\n",
2311 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2312 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2315 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2316 btf_ext_data->d_size);
2317 if (IS_ERR(obj->btf_ext)) {
2318 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2319 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
2320 obj->btf_ext = NULL;
2325 if (err || IS_ERR(obj->btf)) {
2327 err = err ? : PTR_ERR(obj->btf);
2330 if (!IS_ERR_OR_NULL(obj->btf))
2331 btf__free(obj->btf);
2334 if (btf_required && !obj->btf) {
2335 pr_warn("BTF is required, but is missing or corrupted.\n");
2336 return err == 0 ? -ENOENT : err;
2341 static int bpf_object__finalize_btf(struct bpf_object *obj)
2348 err = btf__finalize_data(obj, obj->btf);
2352 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2353 btf__free(obj->btf);
2355 btf_ext__free(obj->btf_ext);
2356 obj->btf_ext = NULL;
2358 if (bpf_object__is_btf_mandatory(obj)) {
2359 pr_warn("BTF is required, but is missing or corrupted.\n");
2365 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2372 bpf_object__sanitize_btf(obj);
2373 bpf_object__sanitize_btf_ext(obj);
2375 err = btf__load(obj->btf);
2377 pr_warn("Error loading %s into kernel: %d.\n",
2379 btf__free(obj->btf);
2381 /* btf_ext can't exist without btf, so free it as well */
2383 btf_ext__free(obj->btf_ext);
2384 obj->btf_ext = NULL;
2387 if (bpf_object__is_btf_mandatory(obj))
2393 static int bpf_object__elf_collect(struct bpf_object *obj)
2395 Elf *elf = obj->efile.elf;
2396 GElf_Ehdr *ep = &obj->efile.ehdr;
2397 Elf_Data *btf_ext_data = NULL;
2398 Elf_Data *btf_data = NULL;
2399 Elf_Scn *scn = NULL;
2400 int idx = 0, err = 0;
2402 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2403 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2404 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2405 return -LIBBPF_ERRNO__FORMAT;
2408 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2414 if (gelf_getshdr(scn, &sh) != &sh) {
2415 pr_warn("failed to get section(%d) header from %s\n",
2417 return -LIBBPF_ERRNO__FORMAT;
2420 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2422 pr_warn("failed to get section(%d) name from %s\n",
2424 return -LIBBPF_ERRNO__FORMAT;
2427 data = elf_getdata(scn, 0);
2429 pr_warn("failed to get section(%d) data from %s(%s)\n",
2430 idx, name, obj->path);
2431 return -LIBBPF_ERRNO__FORMAT;
2433 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2434 idx, name, (unsigned long)data->d_size,
2435 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2438 if (strcmp(name, "license") == 0) {
2439 err = bpf_object__init_license(obj,
2444 } else if (strcmp(name, "version") == 0) {
2445 err = bpf_object__init_kversion(obj,
2450 } else if (strcmp(name, "maps") == 0) {
2451 obj->efile.maps_shndx = idx;
2452 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2453 obj->efile.btf_maps_shndx = idx;
2454 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2456 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2457 btf_ext_data = data;
2458 } else if (sh.sh_type == SHT_SYMTAB) {
2459 if (obj->efile.symbols) {
2460 pr_warn("bpf: multiple SYMTAB in %s\n",
2462 return -LIBBPF_ERRNO__FORMAT;
2464 obj->efile.symbols = data;
2465 obj->efile.symbols_shndx = idx;
2466 obj->efile.strtabidx = sh.sh_link;
2467 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2468 if (sh.sh_flags & SHF_EXECINSTR) {
2469 if (strcmp(name, ".text") == 0)
2470 obj->efile.text_shndx = idx;
2471 err = bpf_object__add_program(obj, data->d_buf,
2475 char errmsg[STRERR_BUFSIZE];
2478 cp = libbpf_strerror_r(-err, errmsg,
2480 pr_warn("failed to alloc program %s (%s): %s",
2481 name, obj->path, cp);
2484 } else if (strcmp(name, DATA_SEC) == 0) {
2485 obj->efile.data = data;
2486 obj->efile.data_shndx = idx;
2487 } else if (strcmp(name, RODATA_SEC) == 0) {
2488 obj->efile.rodata = data;
2489 obj->efile.rodata_shndx = idx;
2490 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2491 obj->efile.st_ops_data = data;
2492 obj->efile.st_ops_shndx = idx;
2494 pr_debug("skip section(%d) %s\n", idx, name);
2496 } else if (sh.sh_type == SHT_REL) {
2497 int nr_sects = obj->efile.nr_reloc_sects;
2498 void *sects = obj->efile.reloc_sects;
2499 int sec = sh.sh_info; /* points to other section */
2501 /* Only do relo for section with exec instructions */
2502 if (!section_have_execinstr(obj, sec) &&
2503 strcmp(name, ".rel" STRUCT_OPS_SEC)) {
2504 pr_debug("skip relo %s(%d) for section(%d)\n",
2509 sects = reallocarray(sects, nr_sects + 1,
2510 sizeof(*obj->efile.reloc_sects));
2512 pr_warn("reloc_sects realloc failed\n");
2516 obj->efile.reloc_sects = sects;
2517 obj->efile.nr_reloc_sects++;
2519 obj->efile.reloc_sects[nr_sects].shdr = sh;
2520 obj->efile.reloc_sects[nr_sects].data = data;
2521 } else if (sh.sh_type == SHT_NOBITS &&
2522 strcmp(name, BSS_SEC) == 0) {
2523 obj->efile.bss = data;
2524 obj->efile.bss_shndx = idx;
2526 pr_debug("skip section(%d) %s\n", idx, name);
2530 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2531 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2532 return -LIBBPF_ERRNO__FORMAT;
2534 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2537 static bool sym_is_extern(const GElf_Sym *sym)
2539 int bind = GELF_ST_BIND(sym->st_info);
2540 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2541 return sym->st_shndx == SHN_UNDEF &&
2542 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2543 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2546 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2548 const struct btf_type *t;
2549 const char *var_name;
2555 n = btf__get_nr_types(btf);
2556 for (i = 1; i <= n; i++) {
2557 t = btf__type_by_id(btf, i);
2562 var_name = btf__name_by_offset(btf, t->name_off);
2563 if (strcmp(var_name, ext_name))
2566 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2575 static enum extern_type find_extern_type(const struct btf *btf, int id,
2578 const struct btf_type *t;
2581 t = skip_mods_and_typedefs(btf, id, NULL);
2582 name = btf__name_by_offset(btf, t->name_off);
2586 switch (btf_kind(t)) {
2587 case BTF_KIND_INT: {
2588 int enc = btf_int_encoding(t);
2590 if (enc & BTF_INT_BOOL)
2591 return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2593 *is_signed = enc & BTF_INT_SIGNED;
2596 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2603 if (strcmp(name, "libbpf_tristate"))
2605 return EXT_TRISTATE;
2606 case BTF_KIND_ARRAY:
2607 if (btf_array(t)->nelems == 0)
2609 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2611 return EXT_CHAR_ARR;
2617 static int cmp_externs(const void *_a, const void *_b)
2619 const struct extern_desc *a = _a;
2620 const struct extern_desc *b = _b;
2622 /* descending order by alignment requirements */
2623 if (a->align != b->align)
2624 return a->align > b->align ? -1 : 1;
2625 /* ascending order by size, within same alignment class */
2627 return a->sz < b->sz ? -1 : 1;
2628 /* resolve ties by name */
2629 return strcmp(a->name, b->name);
2632 static int bpf_object__collect_externs(struct bpf_object *obj)
2634 const struct btf_type *t;
2635 struct extern_desc *ext;
2636 int i, n, off, btf_id;
2637 struct btf_type *sec;
2638 const char *ext_name;
2642 if (!obj->efile.symbols)
2645 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2647 return -LIBBPF_ERRNO__FORMAT;
2648 if (gelf_getshdr(scn, &sh) != &sh)
2649 return -LIBBPF_ERRNO__FORMAT;
2650 n = sh.sh_size / sh.sh_entsize;
2652 pr_debug("looking for externs among %d symbols...\n", n);
2653 for (i = 0; i < n; i++) {
2656 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2657 return -LIBBPF_ERRNO__FORMAT;
2658 if (!sym_is_extern(&sym))
2660 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2662 if (!ext_name || !ext_name[0])
2666 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2670 ext = &ext[obj->nr_extern];
2671 memset(ext, 0, sizeof(*ext));
2674 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2675 if (ext->btf_id <= 0) {
2676 pr_warn("failed to find BTF for extern '%s': %d\n",
2677 ext_name, ext->btf_id);
2680 t = btf__type_by_id(obj->btf, ext->btf_id);
2681 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2683 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2684 ext->sz = btf__resolve_size(obj->btf, t->type);
2686 pr_warn("failed to resolve size of extern '%s': %d\n",
2690 ext->align = btf__align_of(obj->btf, t->type);
2691 if (ext->align <= 0) {
2692 pr_warn("failed to determine alignment of extern '%s': %d\n",
2693 ext_name, ext->align);
2696 ext->type = find_extern_type(obj->btf, t->type,
2698 if (ext->type == EXT_UNKNOWN) {
2699 pr_warn("extern '%s' type is unsupported\n", ext_name);
2703 pr_debug("collected %d externs total\n", obj->nr_extern);
2705 if (!obj->nr_extern)
2708 /* sort externs by (alignment, size, name) and calculate their offsets
2710 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2712 for (i = 0; i < obj->nr_extern; i++) {
2713 ext = &obj->externs[i];
2714 ext->data_off = roundup(off, ext->align);
2715 off = ext->data_off + ext->sz;
2716 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2717 i, ext->sym_idx, ext->data_off, ext->name);
2720 btf_id = btf__find_by_name(obj->btf, KCONFIG_SEC);
2722 pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC);
2726 sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2729 for (i = 0; i < n; i++) {
2730 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2732 t = btf__type_by_id(obj->btf, vs->type);
2733 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2734 ext = find_extern_by_name(obj, ext_name);
2736 pr_warn("failed to find extern definition for BTF var '%s'\n",
2740 vs->offset = ext->data_off;
2741 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2747 static struct bpf_program *
2748 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2750 struct bpf_program *prog;
2753 for (i = 0; i < obj->nr_programs; i++) {
2754 prog = &obj->programs[i];
2755 if (prog->idx == idx)
2761 struct bpf_program *
2762 bpf_object__find_program_by_title(const struct bpf_object *obj,
2765 struct bpf_program *pos;
2767 bpf_object__for_each_program(pos, obj) {
2768 if (pos->section_name && !strcmp(pos->section_name, title))
2774 struct bpf_program *
2775 bpf_object__find_program_by_name(const struct bpf_object *obj,
2778 struct bpf_program *prog;
2780 bpf_object__for_each_program(prog, obj) {
2781 if (!strcmp(prog->name, name))
2787 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2790 return shndx == obj->efile.data_shndx ||
2791 shndx == obj->efile.bss_shndx ||
2792 shndx == obj->efile.rodata_shndx;
2795 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2798 return shndx == obj->efile.maps_shndx ||
2799 shndx == obj->efile.btf_maps_shndx;
2802 static enum libbpf_map_type
2803 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2805 if (shndx == obj->efile.data_shndx)
2806 return LIBBPF_MAP_DATA;
2807 else if (shndx == obj->efile.bss_shndx)
2808 return LIBBPF_MAP_BSS;
2809 else if (shndx == obj->efile.rodata_shndx)
2810 return LIBBPF_MAP_RODATA;
2811 else if (shndx == obj->efile.symbols_shndx)
2812 return LIBBPF_MAP_KCONFIG;
2814 return LIBBPF_MAP_UNSPEC;
2817 static int bpf_program__record_reloc(struct bpf_program *prog,
2818 struct reloc_desc *reloc_desc,
2819 __u32 insn_idx, const char *name,
2820 const GElf_Sym *sym, const GElf_Rel *rel)
2822 struct bpf_insn *insn = &prog->insns[insn_idx];
2823 size_t map_idx, nr_maps = prog->obj->nr_maps;
2824 struct bpf_object *obj = prog->obj;
2825 __u32 shdr_idx = sym->st_shndx;
2826 enum libbpf_map_type type;
2827 struct bpf_map *map;
2829 /* sub-program call relocation */
2830 if (insn->code == (BPF_JMP | BPF_CALL)) {
2831 if (insn->src_reg != BPF_PSEUDO_CALL) {
2832 pr_warn("incorrect bpf_call opcode\n");
2833 return -LIBBPF_ERRNO__RELOC;
2835 /* text_shndx can be 0, if no default "main" program exists */
2836 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2837 pr_warn("bad call relo against section %u\n", shdr_idx);
2838 return -LIBBPF_ERRNO__RELOC;
2840 if (sym->st_value % 8) {
2841 pr_warn("bad call relo offset: %zu\n",
2842 (size_t)sym->st_value);
2843 return -LIBBPF_ERRNO__RELOC;
2845 reloc_desc->type = RELO_CALL;
2846 reloc_desc->insn_idx = insn_idx;
2847 reloc_desc->sym_off = sym->st_value;
2848 obj->has_pseudo_calls = true;
2852 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2853 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2854 insn_idx, insn->code);
2855 return -LIBBPF_ERRNO__RELOC;
2858 if (sym_is_extern(sym)) {
2859 int sym_idx = GELF_R_SYM(rel->r_info);
2860 int i, n = obj->nr_extern;
2861 struct extern_desc *ext;
2863 for (i = 0; i < n; i++) {
2864 ext = &obj->externs[i];
2865 if (ext->sym_idx == sym_idx)
2869 pr_warn("extern relo failed to find extern for sym %d\n",
2871 return -LIBBPF_ERRNO__RELOC;
2873 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2874 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2875 reloc_desc->type = RELO_EXTERN;
2876 reloc_desc->insn_idx = insn_idx;
2877 reloc_desc->sym_off = ext->data_off;
2881 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
2882 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2884 return -LIBBPF_ERRNO__RELOC;
2887 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2889 /* generic map reference relocation */
2890 if (type == LIBBPF_MAP_UNSPEC) {
2891 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2892 pr_warn("bad map relo against section %u\n",
2894 return -LIBBPF_ERRNO__RELOC;
2896 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2897 map = &obj->maps[map_idx];
2898 if (map->libbpf_type != type ||
2899 map->sec_idx != sym->st_shndx ||
2900 map->sec_offset != sym->st_value)
2902 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2903 map_idx, map->name, map->sec_idx,
2904 map->sec_offset, insn_idx);
2907 if (map_idx >= nr_maps) {
2908 pr_warn("map relo failed to find map for sec %u, off %zu\n",
2909 shdr_idx, (size_t)sym->st_value);
2910 return -LIBBPF_ERRNO__RELOC;
2912 reloc_desc->type = RELO_LD64;
2913 reloc_desc->insn_idx = insn_idx;
2914 reloc_desc->map_idx = map_idx;
2915 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
2919 /* global data map relocation */
2920 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2921 pr_warn("bad data relo against section %u\n", shdr_idx);
2922 return -LIBBPF_ERRNO__RELOC;
2924 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2925 map = &obj->maps[map_idx];
2926 if (map->libbpf_type != type)
2928 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2929 map_idx, map->name, map->sec_idx, map->sec_offset,
2933 if (map_idx >= nr_maps) {
2934 pr_warn("data relo failed to find map for sec %u\n",
2936 return -LIBBPF_ERRNO__RELOC;
2939 reloc_desc->type = RELO_DATA;
2940 reloc_desc->insn_idx = insn_idx;
2941 reloc_desc->map_idx = map_idx;
2942 reloc_desc->sym_off = sym->st_value;
2947 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2948 Elf_Data *data, struct bpf_object *obj)
2950 Elf_Data *symbols = obj->efile.symbols;
2953 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
2954 nrels = shdr->sh_size / shdr->sh_entsize;
2956 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2957 if (!prog->reloc_desc) {
2958 pr_warn("failed to alloc memory in relocation\n");
2961 prog->nr_reloc = nrels;
2963 for (i = 0; i < nrels; i++) {
2969 if (!gelf_getrel(data, i, &rel)) {
2970 pr_warn("relocation: failed to get %d reloc\n", i);
2971 return -LIBBPF_ERRNO__FORMAT;
2973 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
2974 pr_warn("relocation: symbol %"PRIx64" not found\n",
2975 GELF_R_SYM(rel.r_info));
2976 return -LIBBPF_ERRNO__FORMAT;
2978 if (rel.r_offset % sizeof(struct bpf_insn))
2979 return -LIBBPF_ERRNO__FORMAT;
2981 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
2982 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2983 sym.st_name) ? : "<?>";
2985 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2986 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2987 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
2988 GELF_ST_BIND(sym.st_info), sym.st_name, name,
2991 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2992 insn_idx, name, &sym, &rel);
2999 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3001 struct bpf_map_def *def = &map->def;
3002 __u32 key_type_id = 0, value_type_id = 0;
3005 /* if it's BTF-defined map, we don't need to search for type IDs.
3006 * For struct_ops map, it does not need btf_key_type_id and
3007 * btf_value_type_id.
3009 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3010 bpf_map__is_struct_ops(map))
3013 if (!bpf_map__is_internal(map)) {
3014 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3015 def->value_size, &key_type_id,
3019 * LLVM annotates global data differently in BTF, that is,
3020 * only as '.data', '.bss' or '.rodata'.
3022 ret = btf__find_by_name(obj->btf,
3023 libbpf_type_to_btf_name[map->libbpf_type]);
3028 map->btf_key_type_id = key_type_id;
3029 map->btf_value_type_id = bpf_map__is_internal(map) ?
3030 ret : value_type_id;
3034 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3036 struct bpf_map_info info = {};
3037 __u32 len = sizeof(info);
3041 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3045 new_name = strdup(info.name);
3049 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3052 goto err_free_new_name;
3055 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3058 goto err_close_new_fd;
3061 err = zclose(map->fd);
3064 goto err_close_new_fd;
3069 map->name = new_name;
3070 map->def.type = info.type;
3071 map->def.key_size = info.key_size;
3072 map->def.value_size = info.value_size;
3073 map->def.max_entries = info.max_entries;
3074 map->def.map_flags = info.map_flags;
3075 map->btf_key_type_id = info.btf_key_type_id;
3076 map->btf_value_type_id = info.btf_value_type_id;
3088 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3090 if (!map || !max_entries)
3093 /* If map already created, its attributes can't be changed. */
3097 map->def.max_entries = max_entries;
3103 bpf_object__probe_name(struct bpf_object *obj)
3105 struct bpf_load_program_attr attr;
3106 char *cp, errmsg[STRERR_BUFSIZE];
3107 struct bpf_insn insns[] = {
3108 BPF_MOV64_IMM(BPF_REG_0, 0),
3113 /* make sure basic loading works */
3115 memset(&attr, 0, sizeof(attr));
3116 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3118 attr.insns_cnt = ARRAY_SIZE(insns);
3119 attr.license = "GPL";
3121 ret = bpf_load_program_xattr(&attr, NULL, 0);
3123 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3124 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
3125 __func__, cp, errno);
3130 /* now try the same program, but with the name */
3133 ret = bpf_load_program_xattr(&attr, NULL, 0);
3143 bpf_object__probe_global_data(struct bpf_object *obj)
3145 struct bpf_load_program_attr prg_attr;
3146 struct bpf_create_map_attr map_attr;
3147 char *cp, errmsg[STRERR_BUFSIZE];
3148 struct bpf_insn insns[] = {
3149 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3150 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3151 BPF_MOV64_IMM(BPF_REG_0, 0),
3156 memset(&map_attr, 0, sizeof(map_attr));
3157 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3158 map_attr.key_size = sizeof(int);
3159 map_attr.value_size = 32;
3160 map_attr.max_entries = 1;
3162 map = bpf_create_map_xattr(&map_attr);
3164 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3165 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3166 __func__, cp, errno);
3172 memset(&prg_attr, 0, sizeof(prg_attr));
3173 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3174 prg_attr.insns = insns;
3175 prg_attr.insns_cnt = ARRAY_SIZE(insns);
3176 prg_attr.license = "GPL";
3178 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
3180 obj->caps.global_data = 1;
3188 static int bpf_object__probe_btf_func(struct bpf_object *obj)
3190 static const char strs[] = "\0int\0x\0a";
3191 /* void x(int a) {} */
3194 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3195 /* FUNC_PROTO */ /* [2] */
3196 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3197 BTF_PARAM_ENC(7, 1),
3198 /* FUNC x */ /* [3] */
3199 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3203 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3204 strs, sizeof(strs));
3206 obj->caps.btf_func = 1;
3214 static int bpf_object__probe_btf_func_global(struct bpf_object *obj)
3216 static const char strs[] = "\0int\0x\0a";
3217 /* static void x(int a) {} */
3220 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3221 /* FUNC_PROTO */ /* [2] */
3222 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3223 BTF_PARAM_ENC(7, 1),
3224 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
3225 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3229 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3230 strs, sizeof(strs));
3232 obj->caps.btf_func_global = 1;
3240 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
3242 static const char strs[] = "\0x\0.data";
3246 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3247 /* VAR x */ /* [2] */
3248 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3250 /* DATASEC val */ /* [3] */
3251 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3252 BTF_VAR_SECINFO_ENC(2, 0, 4),
3256 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3257 strs, sizeof(strs));
3259 obj->caps.btf_datasec = 1;
3267 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
3269 struct bpf_create_map_attr attr = {
3270 .map_type = BPF_MAP_TYPE_ARRAY,
3271 .map_flags = BPF_F_MMAPABLE,
3272 .key_size = sizeof(int),
3273 .value_size = sizeof(int),
3278 fd = bpf_create_map_xattr(&attr);
3280 obj->caps.array_mmap = 1;
3289 bpf_object__probe_caps(struct bpf_object *obj)
3291 int (*probe_fn[])(struct bpf_object *obj) = {
3292 bpf_object__probe_name,
3293 bpf_object__probe_global_data,
3294 bpf_object__probe_btf_func,
3295 bpf_object__probe_btf_func_global,
3296 bpf_object__probe_btf_datasec,
3297 bpf_object__probe_array_mmap,
3301 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
3302 ret = probe_fn[i](obj);
3304 pr_debug("Probe #%d failed with %d.\n", i, ret);
3310 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
3312 struct bpf_map_info map_info = {};
3313 char msg[STRERR_BUFSIZE];
3316 map_info_len = sizeof(map_info);
3318 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
3319 pr_warn("failed to get map info for map FD %d: %s\n",
3320 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
3324 return (map_info.type == map->def.type &&
3325 map_info.key_size == map->def.key_size &&
3326 map_info.value_size == map->def.value_size &&
3327 map_info.max_entries == map->def.max_entries &&
3328 map_info.map_flags == map->def.map_flags);
3332 bpf_object__reuse_map(struct bpf_map *map)
3334 char *cp, errmsg[STRERR_BUFSIZE];
3337 pin_fd = bpf_obj_get(map->pin_path);
3340 if (err == -ENOENT) {
3341 pr_debug("found no pinned map to reuse at '%s'\n",
3346 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3347 pr_warn("couldn't retrieve pinned map '%s': %s\n",
3352 if (!map_is_reuse_compat(map, pin_fd)) {
3353 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3359 err = bpf_map__reuse_fd(map, pin_fd);
3365 pr_debug("reused pinned map at '%s'\n", map->pin_path);
3371 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
3373 enum libbpf_map_type map_type = map->libbpf_type;
3374 char *cp, errmsg[STRERR_BUFSIZE];
3377 /* kernel already zero-initializes .bss map. */
3378 if (map_type == LIBBPF_MAP_BSS)
3381 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
3384 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3385 pr_warn("Error setting initial map(%s) contents: %s\n",
3390 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
3391 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
3392 err = bpf_map_freeze(map->fd);
3395 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3396 pr_warn("Error freezing map(%s) as read-only: %s\n",
3405 bpf_object__create_maps(struct bpf_object *obj)
3407 struct bpf_create_map_attr create_attr = {};
3412 for (i = 0; i < obj->nr_maps; i++) {
3413 struct bpf_map *map = &obj->maps[i];
3414 struct bpf_map_def *def = &map->def;
3415 char *cp, errmsg[STRERR_BUFSIZE];
3416 int *pfd = &map->fd;
3418 if (map->pin_path) {
3419 err = bpf_object__reuse_map(map);
3421 pr_warn("error reusing pinned map %s\n",
3428 pr_debug("skip map create (preset) %s: fd=%d\n",
3429 map->name, map->fd);
3434 create_attr.name = map->name;
3435 create_attr.map_ifindex = map->map_ifindex;
3436 create_attr.map_type = def->type;
3437 create_attr.map_flags = def->map_flags;
3438 create_attr.key_size = def->key_size;
3439 create_attr.value_size = def->value_size;
3440 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
3441 !def->max_entries) {
3443 nr_cpus = libbpf_num_possible_cpus();
3445 pr_warn("failed to determine number of system CPUs: %d\n",
3450 pr_debug("map '%s': setting size to %d\n",
3451 map->name, nr_cpus);
3452 create_attr.max_entries = nr_cpus;
3454 create_attr.max_entries = def->max_entries;
3456 create_attr.btf_fd = 0;
3457 create_attr.btf_key_type_id = 0;
3458 create_attr.btf_value_type_id = 0;
3459 if (bpf_map_type__is_map_in_map(def->type) &&
3460 map->inner_map_fd >= 0)
3461 create_attr.inner_map_fd = map->inner_map_fd;
3462 if (bpf_map__is_struct_ops(map))
3463 create_attr.btf_vmlinux_value_type_id =
3464 map->btf_vmlinux_value_type_id;
3466 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
3467 create_attr.btf_fd = btf__fd(obj->btf);
3468 create_attr.btf_key_type_id = map->btf_key_type_id;
3469 create_attr.btf_value_type_id = map->btf_value_type_id;
3472 *pfd = bpf_create_map_xattr(&create_attr);
3473 if (*pfd < 0 && (create_attr.btf_key_type_id ||
3474 create_attr.btf_value_type_id)) {
3476 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3477 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3478 map->name, cp, err);
3479 create_attr.btf_fd = 0;
3480 create_attr.btf_key_type_id = 0;
3481 create_attr.btf_value_type_id = 0;
3482 map->btf_key_type_id = 0;
3483 map->btf_value_type_id = 0;
3484 *pfd = bpf_create_map_xattr(&create_attr);
3492 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3493 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3494 map->name, cp, err);
3496 for (j = 0; j < i; j++)
3497 zclose(obj->maps[j].fd);
3501 if (bpf_map__is_internal(map)) {
3502 err = bpf_object__populate_internal_map(obj, map);
3509 if (map->pin_path && !map->pinned) {
3510 err = bpf_map__pin(map, NULL);
3512 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3513 map->name, map->pin_path);
3518 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
3525 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3526 void *btf_prog_info, const char *info_name)
3528 if (err != -ENOENT) {
3529 pr_warn("Error in loading %s for sec %s.\n",
3530 info_name, prog->section_name);
3534 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3536 if (btf_prog_info) {
3538 * Some info has already been found but has problem
3539 * in the last btf_ext reloc. Must have to error out.
3541 pr_warn("Error in relocating %s for sec %s.\n",
3542 info_name, prog->section_name);
3546 /* Have problem loading the very first info. Ignore the rest. */
3547 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3548 info_name, prog->section_name, info_name);
3553 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3554 const char *section_name, __u32 insn_offset)
3558 if (!insn_offset || prog->func_info) {
3560 * !insn_offset => main program
3562 * For sub prog, the main program's func_info has to
3563 * be loaded first (i.e. prog->func_info != NULL)
3565 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3566 section_name, insn_offset,
3568 &prog->func_info_cnt);
3570 return check_btf_ext_reloc_err(prog, err,
3574 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3577 if (!insn_offset || prog->line_info) {
3578 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3579 section_name, insn_offset,
3581 &prog->line_info_cnt);
3583 return check_btf_ext_reloc_err(prog, err,
3587 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3593 #define BPF_CORE_SPEC_MAX_LEN 64
3595 /* represents BPF CO-RE field or array element accessor */
3596 struct bpf_core_accessor {
3597 __u32 type_id; /* struct/union type or array element type */
3598 __u32 idx; /* field index or array index */
3599 const char *name; /* field name or NULL for array accessor */
3602 struct bpf_core_spec {
3603 const struct btf *btf;
3604 /* high-level spec: named fields and array indices only */
3605 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3606 /* high-level spec length */
3608 /* raw, low-level spec: 1-to-1 with accessor spec string */
3609 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3610 /* raw spec length */
3612 /* field bit offset represented by spec */
3616 static bool str_is_empty(const char *s)
3621 static bool is_flex_arr(const struct btf *btf,
3622 const struct bpf_core_accessor *acc,
3623 const struct btf_array *arr)
3625 const struct btf_type *t;
3627 /* not a flexible array, if not inside a struct or has non-zero size */
3628 if (!acc->name || arr->nelems > 0)
3631 /* has to be the last member of enclosing struct */
3632 t = btf__type_by_id(btf, acc->type_id);
3633 return acc->idx == btf_vlen(t) - 1;
3637 * Turn bpf_field_reloc into a low- and high-level spec representation,
3638 * validating correctness along the way, as well as calculating resulting
3639 * field bit offset, specified by accessor string. Low-level spec captures
3640 * every single level of nestedness, including traversing anonymous
3641 * struct/union members. High-level one only captures semantically meaningful
3642 * "turning points": named fields and array indicies.
3643 * E.g., for this case:
3646 * int __unimportant;
3654 * struct sample *s = ...;
3656 * int x = &s->a[3]; // access string = '0:1:2:3'
3658 * Low-level spec has 1:1 mapping with each element of access string (it's
3659 * just a parsed access string representation): [0, 1, 2, 3].
3661 * High-level spec will capture only 3 points:
3662 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3663 * - field 'a' access (corresponds to '2' in low-level spec);
3664 * - array element #3 access (corresponds to '3' in low-level spec).
3667 static int bpf_core_spec_parse(const struct btf *btf,
3669 const char *spec_str,
3670 struct bpf_core_spec *spec)
3672 int access_idx, parsed_len, i;
3673 struct bpf_core_accessor *acc;
3674 const struct btf_type *t;
3679 if (str_is_empty(spec_str) || *spec_str == ':')
3682 memset(spec, 0, sizeof(*spec));
3685 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3687 if (*spec_str == ':')
3689 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3691 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3693 spec_str += parsed_len;
3694 spec->raw_spec[spec->raw_len++] = access_idx;
3697 if (spec->raw_len == 0)
3700 /* first spec value is always reloc type array index */
3701 t = skip_mods_and_typedefs(btf, type_id, &id);
3705 access_idx = spec->raw_spec[0];
3706 spec->spec[0].type_id = id;
3707 spec->spec[0].idx = access_idx;
3710 sz = btf__resolve_size(btf, id);
3713 spec->bit_offset = access_idx * sz * 8;
3715 for (i = 1; i < spec->raw_len; i++) {
3716 t = skip_mods_and_typedefs(btf, id, &id);
3720 access_idx = spec->raw_spec[i];
3721 acc = &spec->spec[spec->len];
3723 if (btf_is_composite(t)) {
3724 const struct btf_member *m;
3727 if (access_idx >= btf_vlen(t))
3730 bit_offset = btf_member_bit_offset(t, access_idx);
3731 spec->bit_offset += bit_offset;
3733 m = btf_members(t) + access_idx;
3735 name = btf__name_by_offset(btf, m->name_off);
3736 if (str_is_empty(name))
3740 acc->idx = access_idx;
3746 } else if (btf_is_array(t)) {
3747 const struct btf_array *a = btf_array(t);
3750 t = skip_mods_and_typedefs(btf, a->type, &id);
3754 flex = is_flex_arr(btf, acc - 1, a);
3755 if (!flex && access_idx >= a->nelems)
3758 spec->spec[spec->len].type_id = id;
3759 spec->spec[spec->len].idx = access_idx;
3762 sz = btf__resolve_size(btf, id);
3765 spec->bit_offset += access_idx * sz * 8;
3767 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3768 type_id, spec_str, i, id, btf_kind(t));
3776 static bool bpf_core_is_flavor_sep(const char *s)
3778 /* check X___Y name pattern, where X and Y are not underscores */
3779 return s[0] != '_' && /* X */
3780 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
3781 s[4] != '_'; /* Y */
3784 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3785 * before last triple underscore. Struct name part after last triple
3786 * underscore is ignored by BPF CO-RE relocation during relocation matching.
3788 static size_t bpf_core_essential_name_len(const char *name)
3790 size_t n = strlen(name);
3793 for (i = n - 5; i >= 0; i--) {
3794 if (bpf_core_is_flavor_sep(name + i))
3800 /* dynamically sized list of type IDs */
3806 static void bpf_core_free_cands(struct ids_vec *cand_ids)
3808 free(cand_ids->data);
3812 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3813 __u32 local_type_id,
3814 const struct btf *targ_btf)
3816 size_t local_essent_len, targ_essent_len;
3817 const char *local_name, *targ_name;
3818 const struct btf_type *t;
3819 struct ids_vec *cand_ids;
3823 t = btf__type_by_id(local_btf, local_type_id);
3825 return ERR_PTR(-EINVAL);
3827 local_name = btf__name_by_offset(local_btf, t->name_off);
3828 if (str_is_empty(local_name))
3829 return ERR_PTR(-EINVAL);
3830 local_essent_len = bpf_core_essential_name_len(local_name);
3832 cand_ids = calloc(1, sizeof(*cand_ids));
3834 return ERR_PTR(-ENOMEM);
3836 n = btf__get_nr_types(targ_btf);
3837 for (i = 1; i <= n; i++) {
3838 t = btf__type_by_id(targ_btf, i);
3839 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3840 if (str_is_empty(targ_name))
3843 targ_essent_len = bpf_core_essential_name_len(targ_name);
3844 if (targ_essent_len != local_essent_len)
3847 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3848 pr_debug("[%d] %s: found candidate [%d] %s\n",
3849 local_type_id, local_name, i, targ_name);
3850 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3855 cand_ids->data = new_ids;
3856 cand_ids->data[cand_ids->len++] = i;
3861 bpf_core_free_cands(cand_ids);
3862 return ERR_PTR(err);
3865 /* Check two types for compatibility, skipping const/volatile/restrict and
3866 * typedefs, to ensure we are relocating compatible entities:
3867 * - any two STRUCTs/UNIONs are compatible and can be mixed;
3868 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
3869 * - any two PTRs are always compatible;
3870 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
3871 * least one of enums should be anonymous;
3872 * - for ENUMs, check sizes, names are ignored;
3873 * - for INT, size and signedness are ignored;
3874 * - for ARRAY, dimensionality is ignored, element types are checked for
3875 * compatibility recursively;
3876 * - everything else shouldn't be ever a target of relocation.
3877 * These rules are not set in stone and probably will be adjusted as we get
3878 * more experience with using BPF CO-RE relocations.
3880 static int bpf_core_fields_are_compat(const struct btf *local_btf,
3882 const struct btf *targ_btf,
3885 const struct btf_type *local_type, *targ_type;
3888 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3889 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3890 if (!local_type || !targ_type)
3893 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3895 if (btf_kind(local_type) != btf_kind(targ_type))
3898 switch (btf_kind(local_type)) {
3902 case BTF_KIND_ENUM: {
3903 const char *local_name, *targ_name;
3904 size_t local_len, targ_len;
3906 local_name = btf__name_by_offset(local_btf,
3907 local_type->name_off);
3908 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3909 local_len = bpf_core_essential_name_len(local_name);
3910 targ_len = bpf_core_essential_name_len(targ_name);
3911 /* one of them is anonymous or both w/ same flavor-less names */
3912 return local_len == 0 || targ_len == 0 ||
3913 (local_len == targ_len &&
3914 strncmp(local_name, targ_name, local_len) == 0);
3917 /* just reject deprecated bitfield-like integers; all other
3918 * integers are by default compatible between each other
3920 return btf_int_offset(local_type) == 0 &&
3921 btf_int_offset(targ_type) == 0;
3922 case BTF_KIND_ARRAY:
3923 local_id = btf_array(local_type)->type;
3924 targ_id = btf_array(targ_type)->type;
3927 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3928 btf_kind(local_type), local_id, targ_id);
3934 * Given single high-level named field accessor in local type, find
3935 * corresponding high-level accessor for a target type. Along the way,
3936 * maintain low-level spec for target as well. Also keep updating target
3939 * Searching is performed through recursive exhaustive enumeration of all
3940 * fields of a struct/union. If there are any anonymous (embedded)
3941 * structs/unions, they are recursively searched as well. If field with
3942 * desired name is found, check compatibility between local and target types,
3943 * before returning result.
3945 * 1 is returned, if field is found.
3946 * 0 is returned if no compatible field is found.
3947 * <0 is returned on error.
3949 static int bpf_core_match_member(const struct btf *local_btf,
3950 const struct bpf_core_accessor *local_acc,
3951 const struct btf *targ_btf,
3953 struct bpf_core_spec *spec,
3954 __u32 *next_targ_id)
3956 const struct btf_type *local_type, *targ_type;
3957 const struct btf_member *local_member, *m;
3958 const char *local_name, *targ_name;
3962 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3965 if (!btf_is_composite(targ_type))
3968 local_id = local_acc->type_id;
3969 local_type = btf__type_by_id(local_btf, local_id);
3970 local_member = btf_members(local_type) + local_acc->idx;
3971 local_name = btf__name_by_offset(local_btf, local_member->name_off);
3973 n = btf_vlen(targ_type);
3974 m = btf_members(targ_type);
3975 for (i = 0; i < n; i++, m++) {
3978 bit_offset = btf_member_bit_offset(targ_type, i);
3980 /* too deep struct/union/array nesting */
3981 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3984 /* speculate this member will be the good one */
3985 spec->bit_offset += bit_offset;
3986 spec->raw_spec[spec->raw_len++] = i;
3988 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3989 if (str_is_empty(targ_name)) {
3990 /* embedded struct/union, we need to go deeper */
3991 found = bpf_core_match_member(local_btf, local_acc,
3993 spec, next_targ_id);
3994 if (found) /* either found or error */
3996 } else if (strcmp(local_name, targ_name) == 0) {
3997 /* matching named field */
3998 struct bpf_core_accessor *targ_acc;
4000 targ_acc = &spec->spec[spec->len++];
4001 targ_acc->type_id = targ_id;
4003 targ_acc->name = targ_name;
4005 *next_targ_id = m->type;
4006 found = bpf_core_fields_are_compat(local_btf,
4010 spec->len--; /* pop accessor */
4013 /* member turned out not to be what we looked for */
4014 spec->bit_offset -= bit_offset;
4022 * Try to match local spec to a target type and, if successful, produce full
4023 * target spec (high-level, low-level + bit offset).
4025 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4026 const struct btf *targ_btf, __u32 targ_id,
4027 struct bpf_core_spec *targ_spec)
4029 const struct btf_type *targ_type;
4030 const struct bpf_core_accessor *local_acc;
4031 struct bpf_core_accessor *targ_acc;
4034 memset(targ_spec, 0, sizeof(*targ_spec));
4035 targ_spec->btf = targ_btf;
4037 local_acc = &local_spec->spec[0];
4038 targ_acc = &targ_spec->spec[0];
4040 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
4041 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
4046 if (local_acc->name) {
4047 matched = bpf_core_match_member(local_spec->btf,
4050 targ_spec, &targ_id);
4054 /* for i=0, targ_id is already treated as array element
4055 * type (because it's the original struct), for others
4056 * we should find array element type first
4059 const struct btf_array *a;
4062 if (!btf_is_array(targ_type))
4065 a = btf_array(targ_type);
4066 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
4067 if (!flex && local_acc->idx >= a->nelems)
4069 if (!skip_mods_and_typedefs(targ_btf, a->type,
4074 /* too deep struct/union/array nesting */
4075 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4078 targ_acc->type_id = targ_id;
4079 targ_acc->idx = local_acc->idx;
4080 targ_acc->name = NULL;
4082 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
4083 targ_spec->raw_len++;
4085 sz = btf__resolve_size(targ_btf, targ_id);
4088 targ_spec->bit_offset += local_acc->idx * sz * 8;
4095 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
4096 const struct bpf_field_reloc *relo,
4097 const struct bpf_core_spec *spec,
4098 __u32 *val, bool *validate)
4100 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
4101 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
4102 __u32 byte_off, byte_sz, bit_off, bit_sz;
4103 const struct btf_member *m;
4104 const struct btf_type *mt;
4108 /* a[n] accessor needs special handling */
4110 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
4111 *val = spec->bit_offset / 8;
4112 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
4113 sz = btf__resolve_size(spec->btf, acc->type_id);
4118 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4119 bpf_program__title(prog, false),
4120 relo->kind, relo->insn_off / 8);
4128 m = btf_members(t) + acc->idx;
4129 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
4130 bit_off = spec->bit_offset;
4131 bit_sz = btf_member_bitfield_size(t, acc->idx);
4133 bitfield = bit_sz > 0;
4136 byte_off = bit_off / 8 / byte_sz * byte_sz;
4137 /* figure out smallest int size necessary for bitfield load */
4138 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
4140 /* bitfield can't be read with 64-bit read */
4141 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4142 bpf_program__title(prog, false),
4143 relo->kind, relo->insn_off / 8);
4147 byte_off = bit_off / 8 / byte_sz * byte_sz;
4150 sz = btf__resolve_size(spec->btf, m->type);
4154 byte_off = spec->bit_offset / 8;
4155 bit_sz = byte_sz * 8;
4158 /* for bitfields, all the relocatable aspects are ambiguous and we
4159 * might disagree with compiler, so turn off validation of expected
4160 * value, except for signedness
4163 *validate = !bitfield;
4165 switch (relo->kind) {
4166 case BPF_FIELD_BYTE_OFFSET:
4169 case BPF_FIELD_BYTE_SIZE:
4172 case BPF_FIELD_SIGNED:
4173 /* enums will be assumed unsigned */
4174 *val = btf_is_enum(mt) ||
4175 (btf_int_encoding(mt) & BTF_INT_SIGNED);
4177 *validate = true; /* signedness is never ambiguous */
4179 case BPF_FIELD_LSHIFT_U64:
4180 #if __BYTE_ORDER == __LITTLE_ENDIAN
4181 *val = 64 - (bit_off + bit_sz - byte_off * 8);
4183 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
4186 case BPF_FIELD_RSHIFT_U64:
4189 *validate = true; /* right shift is never ambiguous */
4191 case BPF_FIELD_EXISTS:
4193 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4194 bpf_program__title(prog, false),
4195 relo->kind, relo->insn_off / 8);
4203 * Patch relocatable BPF instruction.
4205 * Patched value is determined by relocation kind and target specification.
4206 * For field existence relocation target spec will be NULL if field is not
4208 * Expected insn->imm value is determined using relocation kind and local
4209 * spec, and is checked before patching instruction. If actual insn->imm value
4210 * is wrong, bail out with error.
4212 * Currently three kinds of BPF instructions are supported:
4213 * 1. rX = <imm> (assignment with immediate operand);
4214 * 2. rX += <imm> (arithmetic operations with immediate operand);
4216 static int bpf_core_reloc_insn(struct bpf_program *prog,
4217 const struct bpf_field_reloc *relo,
4218 const struct bpf_core_spec *local_spec,
4219 const struct bpf_core_spec *targ_spec)
4221 bool failed = false, validate = true;
4222 __u32 orig_val, new_val;
4223 struct bpf_insn *insn;
4227 if (relo->insn_off % sizeof(struct bpf_insn))
4229 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
4231 if (relo->kind == BPF_FIELD_EXISTS) {
4232 orig_val = 1; /* can't generate EXISTS relo w/o local field */
4233 new_val = targ_spec ? 1 : 0;
4234 } else if (!targ_spec) {
4236 new_val = (__u32)-1;
4238 err = bpf_core_calc_field_relo(prog, relo, local_spec,
4239 &orig_val, &validate);
4242 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
4248 insn = &prog->insns[insn_idx];
4249 class = BPF_CLASS(insn->code);
4254 if (BPF_SRC(insn->code) != BPF_K)
4256 if (!failed && validate && insn->imm != orig_val) {
4257 pr_warn("prog '%s': unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4258 bpf_program__title(prog, false), insn_idx,
4259 insn->imm, orig_val, new_val);
4262 orig_val = insn->imm;
4263 insn->imm = new_val;
4264 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
4265 bpf_program__title(prog, false), insn_idx,
4266 failed ? " w/ failed reloc" : "", orig_val, new_val);
4271 if (!failed && validate && insn->off != orig_val) {
4272 pr_warn("prog '%s': unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4273 bpf_program__title(prog, false), insn_idx,
4274 insn->off, orig_val, new_val);
4277 if (new_val > SHRT_MAX) {
4278 pr_warn("prog '%s': insn #%d (LD/LDX/ST/STX) value too big: %u\n",
4279 bpf_program__title(prog, false), insn_idx,
4283 orig_val = insn->off;
4284 insn->off = new_val;
4285 pr_debug("prog '%s': patched insn #%d (LD/LDX/ST/STX)%s off %u -> %u\n",
4286 bpf_program__title(prog, false), insn_idx,
4287 failed ? " w/ failed reloc" : "", orig_val, new_val);
4290 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4291 bpf_program__title(prog, false),
4292 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
4293 insn->off, insn->imm);
4300 static struct btf *btf_load_raw(const char *path)
4308 if (stat(path, &st))
4309 return ERR_PTR(-errno);
4311 data = malloc(st.st_size);
4313 return ERR_PTR(-ENOMEM);
4315 f = fopen(path, "rb");
4317 btf = ERR_PTR(-errno);
4321 read_cnt = fread(data, 1, st.st_size, f);
4323 if (read_cnt < st.st_size) {
4324 btf = ERR_PTR(-EBADF);
4328 btf = btf__new(data, read_cnt);
4336 * Probe few well-known locations for vmlinux kernel image and try to load BTF
4337 * data out of it to use for target BTF.
4339 static struct btf *bpf_find_kernel_btf(void)
4342 const char *path_fmt;
4345 /* try canonical vmlinux BTF through sysfs first */
4346 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
4347 /* fall back to trying to find vmlinux ELF on disk otherwise */
4348 { "/boot/vmlinux-%1$s" },
4349 { "/lib/modules/%1$s/vmlinux-%1$s" },
4350 { "/lib/modules/%1$s/build/vmlinux" },
4351 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
4352 { "/usr/lib/debug/boot/vmlinux-%1$s" },
4353 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
4354 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
4356 char path[PATH_MAX + 1];
4363 for (i = 0; i < ARRAY_SIZE(locations); i++) {
4364 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
4366 if (access(path, R_OK))
4369 if (locations[i].raw_btf)
4370 btf = btf_load_raw(path);
4372 btf = btf__parse_elf(path, NULL);
4374 pr_debug("loading kernel BTF '%s': %ld\n",
4375 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
4382 pr_warn("failed to find valid kernel BTF\n");
4383 return ERR_PTR(-ESRCH);
4386 /* Output spec definition in the format:
4387 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4388 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4390 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
4392 const struct btf_type *t;
4397 type_id = spec->spec[0].type_id;
4398 t = btf__type_by_id(spec->btf, type_id);
4399 s = btf__name_by_offset(spec->btf, t->name_off);
4400 libbpf_print(level, "[%u] %s + ", type_id, s);
4402 for (i = 0; i < spec->raw_len; i++)
4403 libbpf_print(level, "%d%s", spec->raw_spec[i],
4404 i == spec->raw_len - 1 ? " => " : ":");
4406 libbpf_print(level, "%u.%u @ &x",
4407 spec->bit_offset / 8, spec->bit_offset % 8);
4409 for (i = 0; i < spec->len; i++) {
4410 if (spec->spec[i].name)
4411 libbpf_print(level, ".%s", spec->spec[i].name);
4413 libbpf_print(level, "[%u]", spec->spec[i].idx);
4418 static size_t bpf_core_hash_fn(const void *key, void *ctx)
4423 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
4428 static void *u32_as_hash_key(__u32 x)
4430 return (void *)(uintptr_t)x;
4434 * CO-RE relocate single instruction.
4436 * The outline and important points of the algorithm:
4437 * 1. For given local type, find corresponding candidate target types.
4438 * Candidate type is a type with the same "essential" name, ignoring
4439 * everything after last triple underscore (___). E.g., `sample`,
4440 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4441 * for each other. Names with triple underscore are referred to as
4442 * "flavors" and are useful, among other things, to allow to
4443 * specify/support incompatible variations of the same kernel struct, which
4444 * might differ between different kernel versions and/or build
4447 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4448 * converter, when deduplicated BTF of a kernel still contains more than
4449 * one different types with the same name. In that case, ___2, ___3, etc
4450 * are appended starting from second name conflict. But start flavors are
4451 * also useful to be defined "locally", in BPF program, to extract same
4452 * data from incompatible changes between different kernel
4453 * versions/configurations. For instance, to handle field renames between
4454 * kernel versions, one can use two flavors of the struct name with the
4455 * same common name and use conditional relocations to extract that field,
4456 * depending on target kernel version.
4457 * 2. For each candidate type, try to match local specification to this
4458 * candidate target type. Matching involves finding corresponding
4459 * high-level spec accessors, meaning that all named fields should match,
4460 * as well as all array accesses should be within the actual bounds. Also,
4461 * types should be compatible (see bpf_core_fields_are_compat for details).
4462 * 3. It is supported and expected that there might be multiple flavors
4463 * matching the spec. As long as all the specs resolve to the same set of
4464 * offsets across all candidates, there is no error. If there is any
4465 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4466 * imprefection of BTF deduplication, which can cause slight duplication of
4467 * the same BTF type, if some directly or indirectly referenced (by
4468 * pointer) type gets resolved to different actual types in different
4469 * object files. If such situation occurs, deduplicated BTF will end up
4470 * with two (or more) structurally identical types, which differ only in
4471 * types they refer to through pointer. This should be OK in most cases and
4473 * 4. Candidate types search is performed by linearly scanning through all
4474 * types in target BTF. It is anticipated that this is overall more
4475 * efficient memory-wise and not significantly worse (if not better)
4476 * CPU-wise compared to prebuilding a map from all local type names to
4477 * a list of candidate type names. It's also sped up by caching resolved
4478 * list of matching candidates per each local "root" type ID, that has at
4479 * least one bpf_field_reloc associated with it. This list is shared
4480 * between multiple relocations for the same type ID and is updated as some
4481 * of the candidates are pruned due to structural incompatibility.
4483 static int bpf_core_reloc_field(struct bpf_program *prog,
4484 const struct bpf_field_reloc *relo,
4486 const struct btf *local_btf,
4487 const struct btf *targ_btf,
4488 struct hashmap *cand_cache)
4490 const char *prog_name = bpf_program__title(prog, false);
4491 struct bpf_core_spec local_spec, cand_spec, targ_spec;
4492 const void *type_key = u32_as_hash_key(relo->type_id);
4493 const struct btf_type *local_type, *cand_type;
4494 const char *local_name, *cand_name;
4495 struct ids_vec *cand_ids;
4496 __u32 local_id, cand_id;
4497 const char *spec_str;
4500 local_id = relo->type_id;
4501 local_type = btf__type_by_id(local_btf, local_id);
4505 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4506 if (str_is_empty(local_name))
4509 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4510 if (str_is_empty(spec_str))
4513 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4515 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4516 prog_name, relo_idx, local_id, local_name, spec_str,
4521 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4523 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4524 libbpf_print(LIBBPF_DEBUG, "\n");
4526 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4527 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4528 if (IS_ERR(cand_ids)) {
4529 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4530 prog_name, relo_idx, local_id, local_name,
4532 return PTR_ERR(cand_ids);
4534 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4536 bpf_core_free_cands(cand_ids);
4541 for (i = 0, j = 0; i < cand_ids->len; i++) {
4542 cand_id = cand_ids->data[i];
4543 cand_type = btf__type_by_id(targ_btf, cand_id);
4544 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4546 err = bpf_core_spec_match(&local_spec, targ_btf,
4547 cand_id, &cand_spec);
4548 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4549 prog_name, relo_idx, i, cand_name);
4550 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4551 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4553 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4554 prog_name, relo_idx, err);
4561 targ_spec = cand_spec;
4562 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4563 /* if there are many candidates, they should all
4564 * resolve to the same bit offset
4566 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4567 prog_name, relo_idx, cand_spec.bit_offset,
4568 targ_spec.bit_offset);
4572 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4576 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4577 * requested, it's expected that we might not find any candidates.
4578 * In this case, if field wasn't found in any candidate, the list of
4579 * candidates shouldn't change at all, we'll just handle relocating
4580 * appropriately, depending on relo's kind.
4585 if (j == 0 && !prog->obj->relaxed_core_relocs &&
4586 relo->kind != BPF_FIELD_EXISTS) {
4587 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4588 prog_name, relo_idx, local_id, local_name, spec_str);
4592 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4593 err = bpf_core_reloc_insn(prog, relo, &local_spec,
4594 j ? &targ_spec : NULL);
4596 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4597 prog_name, relo_idx, relo->insn_off, err);
4605 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4607 const struct btf_ext_info_sec *sec;
4608 const struct bpf_field_reloc *rec;
4609 const struct btf_ext_info *seg;
4610 struct hashmap_entry *entry;
4611 struct hashmap *cand_cache = NULL;
4612 struct bpf_program *prog;
4613 struct btf *targ_btf;
4614 const char *sec_name;
4618 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4620 targ_btf = bpf_find_kernel_btf();
4621 if (IS_ERR(targ_btf)) {
4622 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4623 return PTR_ERR(targ_btf);
4626 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4627 if (IS_ERR(cand_cache)) {
4628 err = PTR_ERR(cand_cache);
4632 seg = &obj->btf_ext->field_reloc_info;
4633 for_each_btf_ext_sec(seg, sec) {
4634 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4635 if (str_is_empty(sec_name)) {
4639 prog = bpf_object__find_program_by_title(obj, sec_name);
4641 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4647 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4648 sec_name, sec->num_info);
4650 for_each_btf_ext_rec(seg, sec, i, rec) {
4651 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4652 targ_btf, cand_cache);
4654 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4662 btf__free(targ_btf);
4663 if (!IS_ERR_OR_NULL(cand_cache)) {
4664 hashmap__for_each_entry(cand_cache, entry, i) {
4665 bpf_core_free_cands(entry->value);
4667 hashmap__free(cand_cache);
4673 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4677 if (obj->btf_ext->field_reloc_info.len)
4678 err = bpf_core_reloc_fields(obj, targ_btf_path);
4684 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4685 struct reloc_desc *relo)
4687 struct bpf_insn *insn, *new_insn;
4688 struct bpf_program *text;
4692 if (prog->idx == obj->efile.text_shndx) {
4693 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4694 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
4695 return -LIBBPF_ERRNO__RELOC;
4698 if (prog->main_prog_cnt == 0) {
4699 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4701 pr_warn("no .text section found yet relo into text exist\n");
4702 return -LIBBPF_ERRNO__RELOC;
4704 new_cnt = prog->insns_cnt + text->insns_cnt;
4705 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4707 pr_warn("oom in prog realloc\n");
4710 prog->insns = new_insn;
4713 err = bpf_program_reloc_btf_ext(prog, obj,
4720 memcpy(new_insn + prog->insns_cnt, text->insns,
4721 text->insns_cnt * sizeof(*insn));
4722 prog->main_prog_cnt = prog->insns_cnt;
4723 prog->insns_cnt = new_cnt;
4724 pr_debug("added %zd insn from %s to prog %s\n",
4725 text->insns_cnt, text->section_name,
4726 prog->section_name);
4728 insn = &prog->insns[relo->insn_idx];
4729 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4734 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4742 err = bpf_program_reloc_btf_ext(prog, obj,
4743 prog->section_name, 0);
4748 if (!prog->reloc_desc)
4751 for (i = 0; i < prog->nr_reloc; i++) {
4752 struct reloc_desc *relo = &prog->reloc_desc[i];
4753 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4755 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4756 pr_warn("relocation out of range: '%s'\n",
4757 prog->section_name);
4758 return -LIBBPF_ERRNO__RELOC;
4761 switch (relo->type) {
4763 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4764 insn[0].imm = obj->maps[relo->map_idx].fd;
4767 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4768 insn[1].imm = insn[0].imm + relo->sym_off;
4769 insn[0].imm = obj->maps[relo->map_idx].fd;
4772 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4773 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
4774 insn[1].imm = relo->sym_off;
4777 err = bpf_program__reloc_text(prog, obj, relo);
4782 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4787 zfree(&prog->reloc_desc);
4793 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4795 struct bpf_program *prog;
4800 err = bpf_object__relocate_core(obj, targ_btf_path);
4802 pr_warn("failed to perform CO-RE relocations: %d\n",
4807 for (i = 0; i < obj->nr_programs; i++) {
4808 prog = &obj->programs[i];
4810 err = bpf_program__relocate(prog, obj);
4812 pr_warn("failed to relocate '%s'\n", prog->section_name);
4819 static int bpf_object__collect_struct_ops_map_reloc(struct bpf_object *obj,
4823 static int bpf_object__collect_reloc(struct bpf_object *obj)
4827 if (!obj_elf_valid(obj)) {
4828 pr_warn("Internal error: elf object is closed\n");
4829 return -LIBBPF_ERRNO__INTERNAL;
4832 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4833 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4834 Elf_Data *data = obj->efile.reloc_sects[i].data;
4835 int idx = shdr->sh_info;
4836 struct bpf_program *prog;
4838 if (shdr->sh_type != SHT_REL) {
4839 pr_warn("internal error at %d\n", __LINE__);
4840 return -LIBBPF_ERRNO__INTERNAL;
4843 if (idx == obj->efile.st_ops_shndx) {
4844 err = bpf_object__collect_struct_ops_map_reloc(obj,
4852 prog = bpf_object__find_prog_by_idx(obj, idx);
4854 pr_warn("relocation failed: no section(%d)\n", idx);
4855 return -LIBBPF_ERRNO__RELOC;
4858 err = bpf_program__collect_reloc(prog, shdr, data, obj);
4866 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
4867 char *license, __u32 kern_version, int *pfd)
4869 struct bpf_load_program_attr load_attr;
4870 char *cp, errmsg[STRERR_BUFSIZE];
4871 int log_buf_size = BPF_LOG_BUF_SIZE;
4875 if (!insns || !insns_cnt)
4878 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
4879 load_attr.prog_type = prog->type;
4880 load_attr.expected_attach_type = prog->expected_attach_type;
4881 if (prog->caps->name)
4882 load_attr.name = prog->name;
4883 load_attr.insns = insns;
4884 load_attr.insns_cnt = insns_cnt;
4885 load_attr.license = license;
4886 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
4887 load_attr.attach_btf_id = prog->attach_btf_id;
4888 } else if (prog->type == BPF_PROG_TYPE_TRACING) {
4889 load_attr.attach_prog_fd = prog->attach_prog_fd;
4890 load_attr.attach_btf_id = prog->attach_btf_id;
4892 load_attr.kern_version = kern_version;
4893 load_attr.prog_ifindex = prog->prog_ifindex;
4895 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4896 if (prog->obj->btf_ext)
4897 btf_fd = bpf_object__btf_fd(prog->obj);
4900 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
4901 load_attr.func_info = prog->func_info;
4902 load_attr.func_info_rec_size = prog->func_info_rec_size;
4903 load_attr.func_info_cnt = prog->func_info_cnt;
4904 load_attr.line_info = prog->line_info;
4905 load_attr.line_info_rec_size = prog->line_info_rec_size;
4906 load_attr.line_info_cnt = prog->line_info_cnt;
4907 load_attr.log_level = prog->log_level;
4908 load_attr.prog_flags = prog->prog_flags;
4911 log_buf = malloc(log_buf_size);
4913 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4915 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
4918 if (load_attr.log_level)
4919 pr_debug("verifier log:\n%s", log_buf);
4925 if (errno == ENOSPC) {
4931 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4932 pr_warn("load bpf program failed: %s\n", cp);
4935 if (log_buf && log_buf[0] != '\0') {
4936 ret = -LIBBPF_ERRNO__VERIFY;
4937 pr_warn("-- BEGIN DUMP LOG ---\n");
4938 pr_warn("\n%s\n", log_buf);
4939 pr_warn("-- END LOG --\n");
4940 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
4941 pr_warn("Program too large (%zu insns), at most %d insns\n",
4942 load_attr.insns_cnt, BPF_MAXINSNS);
4943 ret = -LIBBPF_ERRNO__PROG2BIG;
4944 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
4945 /* Wrong program type? */
4948 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4949 load_attr.expected_attach_type = 0;
4950 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4953 ret = -LIBBPF_ERRNO__PROGTYPE;
4963 static int libbpf_find_attach_btf_id(const char *name,
4964 enum bpf_attach_type attach_type,
4965 __u32 attach_prog_fd);
4967 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
4969 int err = 0, fd, i, btf_id;
4971 if (prog->type == BPF_PROG_TYPE_TRACING) {
4972 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4973 prog->expected_attach_type,
4974 prog->attach_prog_fd);
4977 prog->attach_btf_id = btf_id;
4980 if (prog->instances.nr < 0 || !prog->instances.fds) {
4981 if (prog->preprocessor) {
4982 pr_warn("Internal error: can't load program '%s'\n",
4983 prog->section_name);
4984 return -LIBBPF_ERRNO__INTERNAL;
4987 prog->instances.fds = malloc(sizeof(int));
4988 if (!prog->instances.fds) {
4989 pr_warn("Not enough memory for BPF fds\n");
4992 prog->instances.nr = 1;
4993 prog->instances.fds[0] = -1;
4996 if (!prog->preprocessor) {
4997 if (prog->instances.nr != 1) {
4998 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4999 prog->section_name, prog->instances.nr);
5001 err = load_program(prog, prog->insns, prog->insns_cnt,
5002 license, kern_ver, &fd);
5004 prog->instances.fds[0] = fd;
5008 for (i = 0; i < prog->instances.nr; i++) {
5009 struct bpf_prog_prep_result result;
5010 bpf_program_prep_t preprocessor = prog->preprocessor;
5012 memset(&result, 0, sizeof(result));
5013 err = preprocessor(prog, i, prog->insns,
5014 prog->insns_cnt, &result);
5016 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
5017 i, prog->section_name);
5021 if (!result.new_insn_ptr || !result.new_insn_cnt) {
5022 pr_debug("Skip loading the %dth instance of program '%s'\n",
5023 i, prog->section_name);
5024 prog->instances.fds[i] = -1;
5030 err = load_program(prog, result.new_insn_ptr,
5031 result.new_insn_cnt, license, kern_ver, &fd);
5033 pr_warn("Loading the %dth instance of program '%s' failed\n",
5034 i, prog->section_name);
5040 prog->instances.fds[i] = fd;
5044 pr_warn("failed to load program '%s'\n", prog->section_name);
5045 zfree(&prog->insns);
5046 prog->insns_cnt = 0;
5050 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
5051 const struct bpf_object *obj)
5053 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
5057 bpf_object__load_progs(struct bpf_object *obj, int log_level)
5062 for (i = 0; i < obj->nr_programs; i++) {
5063 if (bpf_program__is_function_storage(&obj->programs[i], obj))
5065 obj->programs[i].log_level |= log_level;
5066 err = bpf_program__load(&obj->programs[i],
5075 static struct bpf_object *
5076 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
5077 const struct bpf_object_open_opts *opts)
5079 const char *obj_name, *kconfig;
5080 struct bpf_program *prog;
5081 struct bpf_object *obj;
5085 if (elf_version(EV_CURRENT) == EV_NONE) {
5086 pr_warn("failed to init libelf for %s\n",
5087 path ? : "(mem buf)");
5088 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
5091 if (!OPTS_VALID(opts, bpf_object_open_opts))
5092 return ERR_PTR(-EINVAL);
5094 obj_name = OPTS_GET(opts, object_name, NULL);
5097 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
5098 (unsigned long)obj_buf,
5099 (unsigned long)obj_buf_sz);
5100 obj_name = tmp_name;
5103 pr_debug("loading object '%s' from buffer\n", obj_name);
5106 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
5110 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
5111 kconfig = OPTS_GET(opts, kconfig, NULL);
5113 obj->kconfig = strdup(kconfig);
5115 return ERR_PTR(-ENOMEM);
5118 err = bpf_object__elf_init(obj);
5119 err = err ? : bpf_object__check_endianness(obj);
5120 err = err ? : bpf_object__elf_collect(obj);
5121 err = err ? : bpf_object__collect_externs(obj);
5122 err = err ? : bpf_object__finalize_btf(obj);
5123 err = err ? : bpf_object__init_maps(obj, opts);
5124 err = err ? : bpf_object__init_prog_names(obj);
5125 err = err ? : bpf_object__collect_reloc(obj);
5128 bpf_object__elf_finish(obj);
5130 bpf_object__for_each_program(prog, obj) {
5131 enum bpf_prog_type prog_type;
5132 enum bpf_attach_type attach_type;
5134 if (prog->type != BPF_PROG_TYPE_UNSPEC)
5137 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
5140 /* couldn't guess, but user might manually specify */
5145 bpf_program__set_type(prog, prog_type);
5146 bpf_program__set_expected_attach_type(prog, attach_type);
5147 if (prog_type == BPF_PROG_TYPE_TRACING)
5148 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
5153 bpf_object__close(obj);
5154 return ERR_PTR(err);
5157 static struct bpf_object *
5158 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
5160 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5161 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
5164 /* param validation */
5168 pr_debug("loading %s\n", attr->file);
5169 return __bpf_object__open(attr->file, NULL, 0, &opts);
5172 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
5174 return __bpf_object__open_xattr(attr, 0);
5177 struct bpf_object *bpf_object__open(const char *path)
5179 struct bpf_object_open_attr attr = {
5181 .prog_type = BPF_PROG_TYPE_UNSPEC,
5184 return bpf_object__open_xattr(&attr);
5188 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
5191 return ERR_PTR(-EINVAL);
5193 pr_debug("loading %s\n", path);
5195 return __bpf_object__open(path, NULL, 0, opts);
5199 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
5200 const struct bpf_object_open_opts *opts)
5202 if (!obj_buf || obj_buf_sz == 0)
5203 return ERR_PTR(-EINVAL);
5205 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
5209 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
5212 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5213 .object_name = name,
5214 /* wrong default, but backwards-compatible */
5215 .relaxed_maps = true,
5218 /* returning NULL is wrong, but backwards-compatible */
5219 if (!obj_buf || obj_buf_sz == 0)
5222 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
5225 int bpf_object__unload(struct bpf_object *obj)
5232 for (i = 0; i < obj->nr_maps; i++) {
5233 zclose(obj->maps[i].fd);
5234 if (obj->maps[i].st_ops)
5235 zfree(&obj->maps[i].st_ops->kern_vdata);
5238 for (i = 0; i < obj->nr_programs; i++)
5239 bpf_program__unload(&obj->programs[i]);
5244 static int bpf_object__sanitize_maps(struct bpf_object *obj)
5248 bpf_object__for_each_map(m, obj) {
5249 if (!bpf_map__is_internal(m))
5251 if (!obj->caps.global_data) {
5252 pr_warn("kernel doesn't support global data\n");
5255 if (!obj->caps.array_mmap)
5256 m->def.map_flags ^= BPF_F_MMAPABLE;
5262 static int bpf_object__resolve_externs(struct bpf_object *obj,
5263 const char *extra_kconfig)
5265 bool need_config = false;
5266 struct extern_desc *ext;
5270 if (obj->nr_extern == 0)
5273 data = obj->maps[obj->kconfig_map_idx].mmaped;
5275 for (i = 0; i < obj->nr_extern; i++) {
5276 ext = &obj->externs[i];
5278 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
5279 void *ext_val = data + ext->data_off;
5280 __u32 kver = get_kernel_version();
5283 pr_warn("failed to get kernel version\n");
5286 err = set_ext_value_num(ext, ext_val, kver);
5289 pr_debug("extern %s=0x%x\n", ext->name, kver);
5290 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
5293 pr_warn("unrecognized extern '%s'\n", ext->name);
5297 if (need_config && extra_kconfig) {
5298 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, data);
5301 need_config = false;
5302 for (i = 0; i < obj->nr_extern; i++) {
5303 ext = &obj->externs[i];
5311 err = bpf_object__read_kconfig_file(obj, data);
5315 for (i = 0; i < obj->nr_extern; i++) {
5316 ext = &obj->externs[i];
5318 if (!ext->is_set && !ext->is_weak) {
5319 pr_warn("extern %s (strong) not resolved\n", ext->name);
5321 } else if (!ext->is_set) {
5322 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5330 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
5332 struct bpf_object *obj;
5342 pr_warn("object should not be loaded twice\n");
5348 err = bpf_object__probe_caps(obj);
5349 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
5350 err = err ? : bpf_object__sanitize_and_load_btf(obj);
5351 err = err ? : bpf_object__sanitize_maps(obj);
5352 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
5353 err = err ? : bpf_object__create_maps(obj);
5354 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
5355 err = err ? : bpf_object__load_progs(obj, attr->log_level);
5361 /* unpin any maps that were auto-pinned during load */
5362 for (i = 0; i < obj->nr_maps; i++)
5363 if (obj->maps[i].pinned && !obj->maps[i].reused)
5364 bpf_map__unpin(&obj->maps[i], NULL);
5366 bpf_object__unload(obj);
5367 pr_warn("failed to load object '%s'\n", obj->path);
5371 int bpf_object__load(struct bpf_object *obj)
5373 struct bpf_object_load_attr attr = {
5377 return bpf_object__load_xattr(&attr);
5380 static int make_parent_dir(const char *path)
5382 char *cp, errmsg[STRERR_BUFSIZE];
5386 dname = strdup(path);
5390 dir = dirname(dname);
5391 if (mkdir(dir, 0700) && errno != EEXIST)
5396 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5397 pr_warn("failed to mkdir %s: %s\n", path, cp);
5402 static int check_path(const char *path)
5404 char *cp, errmsg[STRERR_BUFSIZE];
5405 struct statfs st_fs;
5412 dname = strdup(path);
5416 dir = dirname(dname);
5417 if (statfs(dir, &st_fs)) {
5418 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5419 pr_warn("failed to statfs %s: %s\n", dir, cp);
5424 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
5425 pr_warn("specified path %s is not on BPF FS\n", path);
5432 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
5435 char *cp, errmsg[STRERR_BUFSIZE];
5438 err = make_parent_dir(path);
5442 err = check_path(path);
5447 pr_warn("invalid program pointer\n");
5451 if (instance < 0 || instance >= prog->instances.nr) {
5452 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5453 instance, prog->section_name, prog->instances.nr);
5457 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
5458 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5459 pr_warn("failed to pin program: %s\n", cp);
5462 pr_debug("pinned program '%s'\n", path);
5467 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
5472 err = check_path(path);
5477 pr_warn("invalid program pointer\n");
5481 if (instance < 0 || instance >= prog->instances.nr) {
5482 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5483 instance, prog->section_name, prog->instances.nr);
5490 pr_debug("unpinned program '%s'\n", path);
5495 int bpf_program__pin(struct bpf_program *prog, const char *path)
5499 err = make_parent_dir(path);
5503 err = check_path(path);
5508 pr_warn("invalid program pointer\n");
5512 if (prog->instances.nr <= 0) {
5513 pr_warn("no instances of prog %s to pin\n",
5514 prog->section_name);
5518 if (prog->instances.nr == 1) {
5519 /* don't create subdirs when pinning single instance */
5520 return bpf_program__pin_instance(prog, path, 0);
5523 for (i = 0; i < prog->instances.nr; i++) {
5527 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5531 } else if (len >= PATH_MAX) {
5532 err = -ENAMETOOLONG;
5536 err = bpf_program__pin_instance(prog, buf, i);
5544 for (i = i - 1; i >= 0; i--) {
5548 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5551 else if (len >= PATH_MAX)
5554 bpf_program__unpin_instance(prog, buf, i);
5562 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5566 err = check_path(path);
5571 pr_warn("invalid program pointer\n");
5575 if (prog->instances.nr <= 0) {
5576 pr_warn("no instances of prog %s to pin\n",
5577 prog->section_name);
5581 if (prog->instances.nr == 1) {
5582 /* don't create subdirs when pinning single instance */
5583 return bpf_program__unpin_instance(prog, path, 0);
5586 for (i = 0; i < prog->instances.nr; i++) {
5590 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5593 else if (len >= PATH_MAX)
5594 return -ENAMETOOLONG;
5596 err = bpf_program__unpin_instance(prog, buf, i);
5608 int bpf_map__pin(struct bpf_map *map, const char *path)
5610 char *cp, errmsg[STRERR_BUFSIZE];
5614 pr_warn("invalid map pointer\n");
5618 if (map->pin_path) {
5619 if (path && strcmp(path, map->pin_path)) {
5620 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5621 bpf_map__name(map), map->pin_path, path);
5623 } else if (map->pinned) {
5624 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5625 bpf_map__name(map), map->pin_path);
5630 pr_warn("missing a path to pin map '%s' at\n",
5631 bpf_map__name(map));
5633 } else if (map->pinned) {
5634 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5638 map->pin_path = strdup(path);
5639 if (!map->pin_path) {
5645 err = make_parent_dir(map->pin_path);
5649 err = check_path(map->pin_path);
5653 if (bpf_obj_pin(map->fd, map->pin_path)) {
5659 pr_debug("pinned map '%s'\n", map->pin_path);
5664 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5665 pr_warn("failed to pin map: %s\n", cp);
5669 int bpf_map__unpin(struct bpf_map *map, const char *path)
5674 pr_warn("invalid map pointer\n");
5678 if (map->pin_path) {
5679 if (path && strcmp(path, map->pin_path)) {
5680 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5681 bpf_map__name(map), map->pin_path, path);
5684 path = map->pin_path;
5686 pr_warn("no path to unpin map '%s' from\n",
5687 bpf_map__name(map));
5691 err = check_path(path);
5699 map->pinned = false;
5700 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5705 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5715 free(map->pin_path);
5716 map->pin_path = new;
5720 const char *bpf_map__get_pin_path(const struct bpf_map *map)
5722 return map->pin_path;
5725 bool bpf_map__is_pinned(const struct bpf_map *map)
5730 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5732 struct bpf_map *map;
5739 pr_warn("object not yet loaded; load it first\n");
5743 bpf_object__for_each_map(map, obj) {
5744 char *pin_path = NULL;
5750 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5751 bpf_map__name(map));
5754 goto err_unpin_maps;
5755 } else if (len >= PATH_MAX) {
5756 err = -ENAMETOOLONG;
5757 goto err_unpin_maps;
5760 } else if (!map->pin_path) {
5764 err = bpf_map__pin(map, pin_path);
5766 goto err_unpin_maps;
5772 while ((map = bpf_map__prev(map, obj))) {
5776 bpf_map__unpin(map, NULL);
5782 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5784 struct bpf_map *map;
5790 bpf_object__for_each_map(map, obj) {
5791 char *pin_path = NULL;
5797 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5798 bpf_map__name(map));
5801 else if (len >= PATH_MAX)
5802 return -ENAMETOOLONG;
5804 } else if (!map->pin_path) {
5808 err = bpf_map__unpin(map, pin_path);
5816 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5818 struct bpf_program *prog;
5825 pr_warn("object not yet loaded; load it first\n");
5829 bpf_object__for_each_program(prog, obj) {
5833 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5837 goto err_unpin_programs;
5838 } else if (len >= PATH_MAX) {
5839 err = -ENAMETOOLONG;
5840 goto err_unpin_programs;
5843 err = bpf_program__pin(prog, buf);
5845 goto err_unpin_programs;
5851 while ((prog = bpf_program__prev(prog, obj))) {
5855 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5859 else if (len >= PATH_MAX)
5862 bpf_program__unpin(prog, buf);
5868 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5870 struct bpf_program *prog;
5876 bpf_object__for_each_program(prog, obj) {
5880 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5884 else if (len >= PATH_MAX)
5885 return -ENAMETOOLONG;
5887 err = bpf_program__unpin(prog, buf);
5895 int bpf_object__pin(struct bpf_object *obj, const char *path)
5899 err = bpf_object__pin_maps(obj, path);
5903 err = bpf_object__pin_programs(obj, path);
5905 bpf_object__unpin_maps(obj, path);
5912 void bpf_object__close(struct bpf_object *obj)
5919 if (obj->clear_priv)
5920 obj->clear_priv(obj, obj->priv);
5922 bpf_object__elf_finish(obj);
5923 bpf_object__unload(obj);
5924 btf__free(obj->btf);
5925 btf_ext__free(obj->btf_ext);
5927 for (i = 0; i < obj->nr_maps; i++) {
5928 struct bpf_map *map = &obj->maps[i];
5930 if (map->clear_priv)
5931 map->clear_priv(map, map->priv);
5933 map->clear_priv = NULL;
5936 munmap(map->mmaped, bpf_map_mmap_sz(map));
5941 zfree(&map->st_ops->data);
5942 zfree(&map->st_ops->progs);
5943 zfree(&map->st_ops->kern_func_off);
5944 zfree(&map->st_ops);
5948 zfree(&map->pin_path);
5951 zfree(&obj->kconfig);
5952 zfree(&obj->externs);
5958 if (obj->programs && obj->nr_programs) {
5959 for (i = 0; i < obj->nr_programs; i++)
5960 bpf_program__exit(&obj->programs[i]);
5962 zfree(&obj->programs);
5964 list_del(&obj->list);
5969 bpf_object__next(struct bpf_object *prev)
5971 struct bpf_object *next;
5974 next = list_first_entry(&bpf_objects_list,
5978 next = list_next_entry(prev, list);
5980 /* Empty list is noticed here so don't need checking on entry. */
5981 if (&next->list == &bpf_objects_list)
5987 const char *bpf_object__name(const struct bpf_object *obj)
5989 return obj ? obj->name : ERR_PTR(-EINVAL);
5992 unsigned int bpf_object__kversion(const struct bpf_object *obj)
5994 return obj ? obj->kern_version : 0;
5997 struct btf *bpf_object__btf(const struct bpf_object *obj)
5999 return obj ? obj->btf : NULL;
6002 int bpf_object__btf_fd(const struct bpf_object *obj)
6004 return obj->btf ? btf__fd(obj->btf) : -1;
6007 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
6008 bpf_object_clear_priv_t clear_priv)
6010 if (obj->priv && obj->clear_priv)
6011 obj->clear_priv(obj, obj->priv);
6014 obj->clear_priv = clear_priv;
6018 void *bpf_object__priv(const struct bpf_object *obj)
6020 return obj ? obj->priv : ERR_PTR(-EINVAL);
6023 static struct bpf_program *
6024 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
6027 size_t nr_programs = obj->nr_programs;
6034 /* Iter from the beginning */
6035 return forward ? &obj->programs[0] :
6036 &obj->programs[nr_programs - 1];
6038 if (p->obj != obj) {
6039 pr_warn("error: program handler doesn't match object\n");
6043 idx = (p - obj->programs) + (forward ? 1 : -1);
6044 if (idx >= obj->nr_programs || idx < 0)
6046 return &obj->programs[idx];
6049 struct bpf_program *
6050 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
6052 struct bpf_program *prog = prev;
6055 prog = __bpf_program__iter(prog, obj, true);
6056 } while (prog && bpf_program__is_function_storage(prog, obj));
6061 struct bpf_program *
6062 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
6064 struct bpf_program *prog = next;
6067 prog = __bpf_program__iter(prog, obj, false);
6068 } while (prog && bpf_program__is_function_storage(prog, obj));
6073 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
6074 bpf_program_clear_priv_t clear_priv)
6076 if (prog->priv && prog->clear_priv)
6077 prog->clear_priv(prog, prog->priv);
6080 prog->clear_priv = clear_priv;
6084 void *bpf_program__priv(const struct bpf_program *prog)
6086 return prog ? prog->priv : ERR_PTR(-EINVAL);
6089 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
6091 prog->prog_ifindex = ifindex;
6094 const char *bpf_program__name(const struct bpf_program *prog)
6099 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
6103 title = prog->section_name;
6105 title = strdup(title);
6107 pr_warn("failed to strdup program title\n");
6108 return ERR_PTR(-ENOMEM);
6115 int bpf_program__fd(const struct bpf_program *prog)
6117 return bpf_program__nth_fd(prog, 0);
6120 size_t bpf_program__size(const struct bpf_program *prog)
6122 return prog->insns_cnt * sizeof(struct bpf_insn);
6125 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
6126 bpf_program_prep_t prep)
6130 if (nr_instances <= 0 || !prep)
6133 if (prog->instances.nr > 0 || prog->instances.fds) {
6134 pr_warn("Can't set pre-processor after loading\n");
6138 instances_fds = malloc(sizeof(int) * nr_instances);
6139 if (!instances_fds) {
6140 pr_warn("alloc memory failed for fds\n");
6144 /* fill all fd with -1 */
6145 memset(instances_fds, -1, sizeof(int) * nr_instances);
6147 prog->instances.nr = nr_instances;
6148 prog->instances.fds = instances_fds;
6149 prog->preprocessor = prep;
6153 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
6160 if (n >= prog->instances.nr || n < 0) {
6161 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6162 n, prog->section_name, prog->instances.nr);
6166 fd = prog->instances.fds[n];
6168 pr_warn("%dth instance of program '%s' is invalid\n",
6169 n, prog->section_name);
6176 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
6181 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
6186 static bool bpf_program__is_type(const struct bpf_program *prog,
6187 enum bpf_prog_type type)
6189 return prog ? (prog->type == type) : false;
6192 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
6193 int bpf_program__set_##NAME(struct bpf_program *prog) \
6197 bpf_program__set_type(prog, TYPE); \
6201 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
6203 return bpf_program__is_type(prog, TYPE); \
6206 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6207 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
6208 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
6209 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
6210 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
6211 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
6212 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
6213 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
6214 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
6215 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
6217 enum bpf_attach_type
6218 bpf_program__get_expected_attach_type(struct bpf_program *prog)
6220 return prog->expected_attach_type;
6223 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
6224 enum bpf_attach_type type)
6226 prog->expected_attach_type = type;
6229 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
6230 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
6232 /* Programs that can NOT be attached. */
6233 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6235 /* Programs that can be attached. */
6236 #define BPF_APROG_SEC(string, ptype, atype) \
6237 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
6239 /* Programs that must specify expected attach type at load time. */
6240 #define BPF_EAPROG_SEC(string, ptype, eatype) \
6241 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
6243 /* Programs that use BTF to identify attach point */
6244 #define BPF_PROG_BTF(string, ptype, eatype) \
6245 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
6247 /* Programs that can be attached but attach type can't be identified by section
6248 * name. Kept for backward compatibility.
6250 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6252 #define SEC_DEF(sec_pfx, ptype, ...) { \
6254 .len = sizeof(sec_pfx) - 1, \
6255 .prog_type = BPF_PROG_TYPE_##ptype, \
6261 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
6262 struct bpf_program *prog);
6264 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6265 struct bpf_program *prog);
6266 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6267 struct bpf_program *prog);
6268 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6269 struct bpf_program *prog);
6270 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6271 struct bpf_program *prog);
6273 struct bpf_sec_def {
6276 enum bpf_prog_type prog_type;
6277 enum bpf_attach_type expected_attach_type;
6280 enum bpf_attach_type attach_type;
6281 attach_fn_t attach_fn;
6284 static const struct bpf_sec_def section_defs[] = {
6285 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
6286 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
6287 SEC_DEF("kprobe/", KPROBE,
6288 .attach_fn = attach_kprobe),
6289 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
6290 SEC_DEF("kretprobe/", KPROBE,
6291 .attach_fn = attach_kprobe),
6292 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
6293 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
6294 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
6295 SEC_DEF("tracepoint/", TRACEPOINT,
6296 .attach_fn = attach_tp),
6297 SEC_DEF("tp/", TRACEPOINT,
6298 .attach_fn = attach_tp),
6299 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
6300 .attach_fn = attach_raw_tp),
6301 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
6302 .attach_fn = attach_raw_tp),
6303 SEC_DEF("tp_btf/", TRACING,
6304 .expected_attach_type = BPF_TRACE_RAW_TP,
6305 .is_attach_btf = true,
6306 .attach_fn = attach_trace),
6307 SEC_DEF("fentry/", TRACING,
6308 .expected_attach_type = BPF_TRACE_FENTRY,
6309 .is_attach_btf = true,
6310 .attach_fn = attach_trace),
6311 SEC_DEF("fexit/", TRACING,
6312 .expected_attach_type = BPF_TRACE_FEXIT,
6313 .is_attach_btf = true,
6314 .attach_fn = attach_trace),
6315 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
6316 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
6317 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
6318 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
6319 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
6320 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
6321 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
6322 BPF_CGROUP_INET_INGRESS),
6323 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
6324 BPF_CGROUP_INET_EGRESS),
6325 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
6326 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
6327 BPF_CGROUP_INET_SOCK_CREATE),
6328 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
6329 BPF_CGROUP_INET4_POST_BIND),
6330 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
6331 BPF_CGROUP_INET6_POST_BIND),
6332 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
6334 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
6335 BPF_CGROUP_SOCK_OPS),
6336 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
6337 BPF_SK_SKB_STREAM_PARSER),
6338 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
6339 BPF_SK_SKB_STREAM_VERDICT),
6340 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
6341 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
6342 BPF_SK_MSG_VERDICT),
6343 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
6345 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
6346 BPF_FLOW_DISSECTOR),
6347 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6348 BPF_CGROUP_INET4_BIND),
6349 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6350 BPF_CGROUP_INET6_BIND),
6351 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6352 BPF_CGROUP_INET4_CONNECT),
6353 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6354 BPF_CGROUP_INET6_CONNECT),
6355 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6356 BPF_CGROUP_UDP4_SENDMSG),
6357 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6358 BPF_CGROUP_UDP6_SENDMSG),
6359 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6360 BPF_CGROUP_UDP4_RECVMSG),
6361 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6362 BPF_CGROUP_UDP6_RECVMSG),
6363 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
6365 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6366 BPF_CGROUP_GETSOCKOPT),
6367 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6368 BPF_CGROUP_SETSOCKOPT),
6369 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
6372 #undef BPF_PROG_SEC_IMPL
6374 #undef BPF_APROG_SEC
6375 #undef BPF_EAPROG_SEC
6376 #undef BPF_APROG_COMPAT
6379 #define MAX_TYPE_NAME_SIZE 32
6381 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
6383 int i, n = ARRAY_SIZE(section_defs);
6385 for (i = 0; i < n; i++) {
6386 if (strncmp(sec_name,
6387 section_defs[i].sec, section_defs[i].len))
6389 return §ion_defs[i];
6394 static char *libbpf_get_type_names(bool attach_type)
6396 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
6404 /* Forge string buf with all available names */
6405 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6406 if (attach_type && !section_defs[i].is_attachable)
6409 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
6414 strcat(buf, section_defs[i].sec);
6420 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
6421 enum bpf_attach_type *expected_attach_type)
6423 const struct bpf_sec_def *sec_def;
6429 sec_def = find_sec_def(name);
6431 *prog_type = sec_def->prog_type;
6432 *expected_attach_type = sec_def->expected_attach_type;
6436 pr_debug("failed to guess program type from ELF section '%s'\n", name);
6437 type_names = libbpf_get_type_names(false);
6438 if (type_names != NULL) {
6439 pr_debug("supported section(type) names are:%s\n", type_names);
6446 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
6449 struct bpf_map *map;
6452 for (i = 0; i < obj->nr_maps; i++) {
6453 map = &obj->maps[i];
6454 if (!bpf_map__is_struct_ops(map))
6456 if (map->sec_offset <= offset &&
6457 offset - map->sec_offset < map->def.value_size)
6464 /* Collect the reloc from ELF and populate the st_ops->progs[] */
6465 static int bpf_object__collect_struct_ops_map_reloc(struct bpf_object *obj,
6469 const struct btf_member *member;
6470 struct bpf_struct_ops *st_ops;
6471 struct bpf_program *prog;
6472 unsigned int shdr_idx;
6473 const struct btf *btf;
6474 struct bpf_map *map;
6483 symbols = obj->efile.symbols;
6485 nrels = shdr->sh_size / shdr->sh_entsize;
6486 for (i = 0; i < nrels; i++) {
6487 if (!gelf_getrel(data, i, &rel)) {
6488 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
6489 return -LIBBPF_ERRNO__FORMAT;
6492 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
6493 pr_warn("struct_ops reloc: symbol %zx not found\n",
6494 (size_t)GELF_R_SYM(rel.r_info));
6495 return -LIBBPF_ERRNO__FORMAT;
6498 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
6499 sym.st_name) ? : "<?>";
6500 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
6502 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
6503 (size_t)rel.r_offset);
6507 moff = rel.r_offset - map->sec_offset;
6508 shdr_idx = sym.st_shndx;
6509 st_ops = map->st_ops;
6510 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",
6512 (long long)(rel.r_info >> 32),
6513 (long long)sym.st_value,
6514 shdr_idx, (size_t)rel.r_offset,
6515 map->sec_offset, sym.st_name, name);
6517 if (shdr_idx >= SHN_LORESERVE) {
6518 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
6519 map->name, (size_t)rel.r_offset, shdr_idx);
6520 return -LIBBPF_ERRNO__RELOC;
6523 member = find_member_by_offset(st_ops->type, moff * 8);
6525 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
6529 member_idx = member - btf_members(st_ops->type);
6530 name = btf__name_by_offset(btf, member->name_off);
6532 if (!resolve_func_ptr(btf, member->type, NULL)) {
6533 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
6538 prog = bpf_object__find_prog_by_idx(obj, shdr_idx);
6540 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
6541 map->name, shdr_idx, name);
6545 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6546 const struct bpf_sec_def *sec_def;
6548 sec_def = find_sec_def(prog->section_name);
6550 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
6552 prog->type = sec_def->prog_type;
6556 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
6557 prog->attach_btf_id = st_ops->type_id;
6558 prog->expected_attach_type = member_idx;
6559 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
6560 prog->attach_btf_id != st_ops->type_id ||
6561 prog->expected_attach_type != member_idx) {
6564 st_ops->progs[member_idx] = prog;
6570 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",
6571 map->name, prog->name, prog->section_name, prog->type,
6572 prog->attach_btf_id, prog->expected_attach_type, name);
6576 #define BTF_PREFIX "btf_trace_"
6577 int libbpf_find_vmlinux_btf_id(const char *name,
6578 enum bpf_attach_type attach_type)
6580 struct btf *btf = bpf_find_kernel_btf();
6581 char raw_tp_btf[128] = BTF_PREFIX;
6582 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
6583 const char *btf_name;
6588 pr_warn("vmlinux BTF is not found\n");
6592 if (attach_type == BPF_TRACE_RAW_TP) {
6593 /* prepend "btf_trace_" prefix per kernel convention */
6594 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
6595 btf_name = raw_tp_btf;
6596 kind = BTF_KIND_TYPEDEF;
6599 kind = BTF_KIND_FUNC;
6601 err = btf__find_by_name_kind(btf, btf_name, kind);
6606 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
6608 struct bpf_prog_info_linear *info_linear;
6609 struct bpf_prog_info *info;
6610 struct btf *btf = NULL;
6613 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
6614 if (IS_ERR_OR_NULL(info_linear)) {
6615 pr_warn("failed get_prog_info_linear for FD %d\n",
6619 info = &info_linear->info;
6620 if (!info->btf_id) {
6621 pr_warn("The target program doesn't have BTF\n");
6624 if (btf__get_from_id(info->btf_id, &btf)) {
6625 pr_warn("Failed to get BTF of the program\n");
6628 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6631 pr_warn("%s is not found in prog's BTF\n", name);
6639 static int libbpf_find_attach_btf_id(const char *name,
6640 enum bpf_attach_type attach_type,
6641 __u32 attach_prog_fd)
6648 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6649 if (!section_defs[i].is_attach_btf)
6651 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6654 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
6657 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
6660 pr_warn("%s is not found in vmlinux BTF\n", name);
6663 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
6667 int libbpf_attach_type_by_name(const char *name,
6668 enum bpf_attach_type *attach_type)
6676 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6677 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6679 if (!section_defs[i].is_attachable)
6681 *attach_type = section_defs[i].attach_type;
6684 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
6685 type_names = libbpf_get_type_names(true);
6686 if (type_names != NULL) {
6687 pr_debug("attachable section(type) names are:%s\n", type_names);
6694 int bpf_map__fd(const struct bpf_map *map)
6696 return map ? map->fd : -EINVAL;
6699 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
6701 return map ? &map->def : ERR_PTR(-EINVAL);
6704 const char *bpf_map__name(const struct bpf_map *map)
6706 return map ? map->name : NULL;
6709 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
6711 return map ? map->btf_key_type_id : 0;
6714 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
6716 return map ? map->btf_value_type_id : 0;
6719 int bpf_map__set_priv(struct bpf_map *map, void *priv,
6720 bpf_map_clear_priv_t clear_priv)
6726 if (map->clear_priv)
6727 map->clear_priv(map, map->priv);
6731 map->clear_priv = clear_priv;
6735 void *bpf_map__priv(const struct bpf_map *map)
6737 return map ? map->priv : ERR_PTR(-EINVAL);
6740 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
6742 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6745 bool bpf_map__is_internal(const struct bpf_map *map)
6747 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6750 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6752 map->map_ifindex = ifindex;
6755 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6757 if (!bpf_map_type__is_map_in_map(map->def.type)) {
6758 pr_warn("error: unsupported map type\n");
6761 if (map->inner_map_fd != -1) {
6762 pr_warn("error: inner_map_fd already specified\n");
6765 map->inner_map_fd = fd;
6769 static struct bpf_map *
6770 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
6773 struct bpf_map *s, *e;
6775 if (!obj || !obj->maps)
6779 e = obj->maps + obj->nr_maps;
6781 if ((m < s) || (m >= e)) {
6782 pr_warn("error in %s: map handler doesn't belong to object\n",
6787 idx = (m - obj->maps) + i;
6788 if (idx >= obj->nr_maps || idx < 0)
6790 return &obj->maps[idx];
6794 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
6799 return __bpf_map__iter(prev, obj, 1);
6803 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
6808 return obj->maps + obj->nr_maps - 1;
6811 return __bpf_map__iter(next, obj, -1);
6815 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
6817 struct bpf_map *pos;
6819 bpf_object__for_each_map(pos, obj) {
6820 if (pos->name && !strcmp(pos->name, name))
6827 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
6829 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6833 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6835 return ERR_PTR(-ENOTSUP);
6838 long libbpf_get_error(const void *ptr)
6840 return PTR_ERR_OR_ZERO(ptr);
6843 int bpf_prog_load(const char *file, enum bpf_prog_type type,
6844 struct bpf_object **pobj, int *prog_fd)
6846 struct bpf_prog_load_attr attr;
6848 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6850 attr.prog_type = type;
6851 attr.expected_attach_type = 0;
6853 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6856 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6857 struct bpf_object **pobj, int *prog_fd)
6859 struct bpf_object_open_attr open_attr = {};
6860 struct bpf_program *prog, *first_prog = NULL;
6861 struct bpf_object *obj;
6862 struct bpf_map *map;
6870 open_attr.file = attr->file;
6871 open_attr.prog_type = attr->prog_type;
6873 obj = bpf_object__open_xattr(&open_attr);
6874 if (IS_ERR_OR_NULL(obj))
6877 bpf_object__for_each_program(prog, obj) {
6878 enum bpf_attach_type attach_type = attr->expected_attach_type;
6880 * to preserve backwards compatibility, bpf_prog_load treats
6881 * attr->prog_type, if specified, as an override to whatever
6882 * bpf_object__open guessed
6884 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6885 bpf_program__set_type(prog, attr->prog_type);
6886 bpf_program__set_expected_attach_type(prog,
6889 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6891 * we haven't guessed from section name and user
6892 * didn't provide a fallback type, too bad...
6894 bpf_object__close(obj);
6898 prog->prog_ifindex = attr->ifindex;
6899 prog->log_level = attr->log_level;
6900 prog->prog_flags = attr->prog_flags;
6905 bpf_object__for_each_map(map, obj) {
6906 if (!bpf_map__is_offload_neutral(map))
6907 map->map_ifindex = attr->ifindex;
6911 pr_warn("object file doesn't contain bpf program\n");
6912 bpf_object__close(obj);
6916 err = bpf_object__load(obj);
6918 bpf_object__close(obj);
6923 *prog_fd = bpf_program__fd(first_prog);
6928 int (*detach)(struct bpf_link *link);
6929 int (*destroy)(struct bpf_link *link);
6933 /* Release "ownership" of underlying BPF resource (typically, BPF program
6934 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6935 * link, when destructed through bpf_link__destroy() call won't attempt to
6936 * detach/unregisted that BPF resource. This is useful in situations where,
6937 * say, attached BPF program has to outlive userspace program that attached it
6938 * in the system. Depending on type of BPF program, though, there might be
6939 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6940 * exit of userspace program doesn't trigger automatic detachment and clean up
6941 * inside the kernel.
6943 void bpf_link__disconnect(struct bpf_link *link)
6945 link->disconnected = true;
6948 int bpf_link__destroy(struct bpf_link *link)
6955 if (!link->disconnected && link->detach)
6956 err = link->detach(link);
6958 link->destroy(link);
6964 struct bpf_link_fd {
6965 struct bpf_link link; /* has to be at the top of struct */
6966 int fd; /* hook FD */
6969 static int bpf_link__detach_perf_event(struct bpf_link *link)
6971 struct bpf_link_fd *l = (void *)link;
6974 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6982 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6985 char errmsg[STRERR_BUFSIZE];
6986 struct bpf_link_fd *link;
6990 pr_warn("program '%s': invalid perf event FD %d\n",
6991 bpf_program__title(prog, false), pfd);
6992 return ERR_PTR(-EINVAL);
6994 prog_fd = bpf_program__fd(prog);
6996 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6997 bpf_program__title(prog, false));
6998 return ERR_PTR(-EINVAL);
7001 link = calloc(1, sizeof(*link));
7003 return ERR_PTR(-ENOMEM);
7004 link->link.detach = &bpf_link__detach_perf_event;
7007 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
7010 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7011 bpf_program__title(prog, false), pfd,
7012 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7013 return ERR_PTR(err);
7015 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7018 pr_warn("program '%s': failed to enable pfd %d: %s\n",
7019 bpf_program__title(prog, false), pfd,
7020 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7021 return ERR_PTR(err);
7023 return (struct bpf_link *)link;
7027 * this function is expected to parse integer in the range of [0, 2^31-1] from
7028 * given file using scanf format string fmt. If actual parsed value is
7029 * negative, the result might be indistinguishable from error
7031 static int parse_uint_from_file(const char *file, const char *fmt)
7033 char buf[STRERR_BUFSIZE];
7037 f = fopen(file, "r");
7040 pr_debug("failed to open '%s': %s\n", file,
7041 libbpf_strerror_r(err, buf, sizeof(buf)));
7044 err = fscanf(f, fmt, &ret);
7046 err = err == EOF ? -EIO : -errno;
7047 pr_debug("failed to parse '%s': %s\n", file,
7048 libbpf_strerror_r(err, buf, sizeof(buf)));
7056 static int determine_kprobe_perf_type(void)
7058 const char *file = "/sys/bus/event_source/devices/kprobe/type";
7060 return parse_uint_from_file(file, "%d\n");
7063 static int determine_uprobe_perf_type(void)
7065 const char *file = "/sys/bus/event_source/devices/uprobe/type";
7067 return parse_uint_from_file(file, "%d\n");
7070 static int determine_kprobe_retprobe_bit(void)
7072 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
7074 return parse_uint_from_file(file, "config:%d\n");
7077 static int determine_uprobe_retprobe_bit(void)
7079 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
7081 return parse_uint_from_file(file, "config:%d\n");
7084 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
7085 uint64_t offset, int pid)
7087 struct perf_event_attr attr = {};
7088 char errmsg[STRERR_BUFSIZE];
7091 type = uprobe ? determine_uprobe_perf_type()
7092 : determine_kprobe_perf_type();
7094 pr_warn("failed to determine %s perf type: %s\n",
7095 uprobe ? "uprobe" : "kprobe",
7096 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
7100 int bit = uprobe ? determine_uprobe_retprobe_bit()
7101 : determine_kprobe_retprobe_bit();
7104 pr_warn("failed to determine %s retprobe bit: %s\n",
7105 uprobe ? "uprobe" : "kprobe",
7106 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
7109 attr.config |= 1 << bit;
7111 attr.size = sizeof(attr);
7113 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
7114 attr.config2 = offset; /* kprobe_addr or probe_offset */
7116 /* pid filter is meaningful only for uprobes */
7117 pfd = syscall(__NR_perf_event_open, &attr,
7118 pid < 0 ? -1 : pid /* pid */,
7119 pid == -1 ? 0 : -1 /* cpu */,
7120 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7123 pr_warn("%s perf_event_open() failed: %s\n",
7124 uprobe ? "uprobe" : "kprobe",
7125 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7131 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
7133 const char *func_name)
7135 char errmsg[STRERR_BUFSIZE];
7136 struct bpf_link *link;
7139 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
7140 0 /* offset */, -1 /* pid */);
7142 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7143 bpf_program__title(prog, false),
7144 retprobe ? "kretprobe" : "kprobe", func_name,
7145 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7146 return ERR_PTR(pfd);
7148 link = bpf_program__attach_perf_event(prog, pfd);
7151 err = PTR_ERR(link);
7152 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7153 bpf_program__title(prog, false),
7154 retprobe ? "kretprobe" : "kprobe", func_name,
7155 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7161 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7162 struct bpf_program *prog)
7164 const char *func_name;
7167 func_name = bpf_program__title(prog, false) + sec->len;
7168 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
7170 return bpf_program__attach_kprobe(prog, retprobe, func_name);
7173 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
7174 bool retprobe, pid_t pid,
7175 const char *binary_path,
7178 char errmsg[STRERR_BUFSIZE];
7179 struct bpf_link *link;
7182 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
7183 binary_path, func_offset, pid);
7185 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
7186 bpf_program__title(prog, false),
7187 retprobe ? "uretprobe" : "uprobe",
7188 binary_path, func_offset,
7189 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7190 return ERR_PTR(pfd);
7192 link = bpf_program__attach_perf_event(prog, pfd);
7195 err = PTR_ERR(link);
7196 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
7197 bpf_program__title(prog, false),
7198 retprobe ? "uretprobe" : "uprobe",
7199 binary_path, func_offset,
7200 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7206 static int determine_tracepoint_id(const char *tp_category,
7207 const char *tp_name)
7209 char file[PATH_MAX];
7212 ret = snprintf(file, sizeof(file),
7213 "/sys/kernel/debug/tracing/events/%s/%s/id",
7214 tp_category, tp_name);
7217 if (ret >= sizeof(file)) {
7218 pr_debug("tracepoint %s/%s path is too long\n",
7219 tp_category, tp_name);
7222 return parse_uint_from_file(file, "%d\n");
7225 static int perf_event_open_tracepoint(const char *tp_category,
7226 const char *tp_name)
7228 struct perf_event_attr attr = {};
7229 char errmsg[STRERR_BUFSIZE];
7230 int tp_id, pfd, err;
7232 tp_id = determine_tracepoint_id(tp_category, tp_name);
7234 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
7235 tp_category, tp_name,
7236 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
7240 attr.type = PERF_TYPE_TRACEPOINT;
7241 attr.size = sizeof(attr);
7242 attr.config = tp_id;
7244 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
7245 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7248 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
7249 tp_category, tp_name,
7250 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7256 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
7257 const char *tp_category,
7258 const char *tp_name)
7260 char errmsg[STRERR_BUFSIZE];
7261 struct bpf_link *link;
7264 pfd = perf_event_open_tracepoint(tp_category, tp_name);
7266 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
7267 bpf_program__title(prog, false),
7268 tp_category, tp_name,
7269 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7270 return ERR_PTR(pfd);
7272 link = bpf_program__attach_perf_event(prog, pfd);
7275 err = PTR_ERR(link);
7276 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
7277 bpf_program__title(prog, false),
7278 tp_category, tp_name,
7279 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7285 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7286 struct bpf_program *prog)
7288 char *sec_name, *tp_cat, *tp_name;
7289 struct bpf_link *link;
7291 sec_name = strdup(bpf_program__title(prog, false));
7293 return ERR_PTR(-ENOMEM);
7295 /* extract "tp/<category>/<name>" */
7296 tp_cat = sec_name + sec->len;
7297 tp_name = strchr(tp_cat, '/');
7299 link = ERR_PTR(-EINVAL);
7305 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
7311 static int bpf_link__detach_fd(struct bpf_link *link)
7313 struct bpf_link_fd *l = (void *)link;
7315 return close(l->fd);
7318 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
7319 const char *tp_name)
7321 char errmsg[STRERR_BUFSIZE];
7322 struct bpf_link_fd *link;
7325 prog_fd = bpf_program__fd(prog);
7327 pr_warn("program '%s': can't attach before loaded\n",
7328 bpf_program__title(prog, false));
7329 return ERR_PTR(-EINVAL);
7332 link = calloc(1, sizeof(*link));
7334 return ERR_PTR(-ENOMEM);
7335 link->link.detach = &bpf_link__detach_fd;
7337 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
7341 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
7342 bpf_program__title(prog, false), tp_name,
7343 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7344 return ERR_PTR(pfd);
7347 return (struct bpf_link *)link;
7350 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7351 struct bpf_program *prog)
7353 const char *tp_name = bpf_program__title(prog, false) + sec->len;
7355 return bpf_program__attach_raw_tracepoint(prog, tp_name);
7358 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
7360 char errmsg[STRERR_BUFSIZE];
7361 struct bpf_link_fd *link;
7364 prog_fd = bpf_program__fd(prog);
7366 pr_warn("program '%s': can't attach before loaded\n",
7367 bpf_program__title(prog, false));
7368 return ERR_PTR(-EINVAL);
7371 link = calloc(1, sizeof(*link));
7373 return ERR_PTR(-ENOMEM);
7374 link->link.detach = &bpf_link__detach_fd;
7376 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
7380 pr_warn("program '%s': failed to attach to trace: %s\n",
7381 bpf_program__title(prog, false),
7382 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7383 return ERR_PTR(pfd);
7386 return (struct bpf_link *)link;
7389 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7390 struct bpf_program *prog)
7392 return bpf_program__attach_trace(prog);
7395 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
7397 const struct bpf_sec_def *sec_def;
7399 sec_def = find_sec_def(bpf_program__title(prog, false));
7400 if (!sec_def || !sec_def->attach_fn)
7401 return ERR_PTR(-ESRCH);
7403 return sec_def->attach_fn(sec_def, prog);
7406 static int bpf_link__detach_struct_ops(struct bpf_link *link)
7408 struct bpf_link_fd *l = (void *)link;
7411 if (bpf_map_delete_elem(l->fd, &zero))
7417 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
7419 struct bpf_struct_ops *st_ops;
7420 struct bpf_link_fd *link;
7424 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
7425 return ERR_PTR(-EINVAL);
7427 link = calloc(1, sizeof(*link));
7429 return ERR_PTR(-EINVAL);
7431 st_ops = map->st_ops;
7432 for (i = 0; i < btf_vlen(st_ops->type); i++) {
7433 struct bpf_program *prog = st_ops->progs[i];
7440 prog_fd = bpf_program__fd(prog);
7441 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7442 *(unsigned long *)kern_data = prog_fd;
7445 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
7449 return ERR_PTR(err);
7452 link->link.detach = bpf_link__detach_struct_ops;
7455 return (struct bpf_link *)link;
7458 enum bpf_perf_event_ret
7459 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
7460 void **copy_mem, size_t *copy_size,
7461 bpf_perf_event_print_t fn, void *private_data)
7463 struct perf_event_mmap_page *header = mmap_mem;
7464 __u64 data_head = ring_buffer_read_head(header);
7465 __u64 data_tail = header->data_tail;
7466 void *base = ((__u8 *)header) + page_size;
7467 int ret = LIBBPF_PERF_EVENT_CONT;
7468 struct perf_event_header *ehdr;
7471 while (data_head != data_tail) {
7472 ehdr = base + (data_tail & (mmap_size - 1));
7473 ehdr_size = ehdr->size;
7475 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
7476 void *copy_start = ehdr;
7477 size_t len_first = base + mmap_size - copy_start;
7478 size_t len_secnd = ehdr_size - len_first;
7480 if (*copy_size < ehdr_size) {
7482 *copy_mem = malloc(ehdr_size);
7485 ret = LIBBPF_PERF_EVENT_ERROR;
7488 *copy_size = ehdr_size;
7491 memcpy(*copy_mem, copy_start, len_first);
7492 memcpy(*copy_mem + len_first, base, len_secnd);
7496 ret = fn(ehdr, private_data);
7497 data_tail += ehdr_size;
7498 if (ret != LIBBPF_PERF_EVENT_CONT)
7502 ring_buffer_write_tail(header, data_tail);
7508 struct perf_buffer_params {
7509 struct perf_event_attr *attr;
7510 /* if event_cb is specified, it takes precendence */
7511 perf_buffer_event_fn event_cb;
7512 /* sample_cb and lost_cb are higher-level common-case callbacks */
7513 perf_buffer_sample_fn sample_cb;
7514 perf_buffer_lost_fn lost_cb;
7521 struct perf_cpu_buf {
7522 struct perf_buffer *pb;
7523 void *base; /* mmap()'ed memory */
7524 void *buf; /* for reconstructing segmented data */
7531 struct perf_buffer {
7532 perf_buffer_event_fn event_cb;
7533 perf_buffer_sample_fn sample_cb;
7534 perf_buffer_lost_fn lost_cb;
7535 void *ctx; /* passed into callbacks */
7539 struct perf_cpu_buf **cpu_bufs;
7540 struct epoll_event *events;
7541 int cpu_cnt; /* number of allocated CPU buffers */
7542 int epoll_fd; /* perf event FD */
7543 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
7546 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
7547 struct perf_cpu_buf *cpu_buf)
7551 if (cpu_buf->base &&
7552 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
7553 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
7554 if (cpu_buf->fd >= 0) {
7555 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
7562 void perf_buffer__free(struct perf_buffer *pb)
7569 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
7570 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
7572 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
7573 perf_buffer__free_cpu_buf(pb, cpu_buf);
7577 if (pb->epoll_fd >= 0)
7578 close(pb->epoll_fd);
7583 static struct perf_cpu_buf *
7584 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
7585 int cpu, int map_key)
7587 struct perf_cpu_buf *cpu_buf;
7588 char msg[STRERR_BUFSIZE];
7591 cpu_buf = calloc(1, sizeof(*cpu_buf));
7593 return ERR_PTR(-ENOMEM);
7597 cpu_buf->map_key = map_key;
7599 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
7600 -1, PERF_FLAG_FD_CLOEXEC);
7601 if (cpu_buf->fd < 0) {
7603 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
7604 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
7608 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
7609 PROT_READ | PROT_WRITE, MAP_SHARED,
7611 if (cpu_buf->base == MAP_FAILED) {
7612 cpu_buf->base = NULL;
7614 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
7615 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
7619 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7621 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
7622 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
7629 perf_buffer__free_cpu_buf(pb, cpu_buf);
7630 return (struct perf_cpu_buf *)ERR_PTR(err);
7633 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
7634 struct perf_buffer_params *p);
7636 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
7637 const struct perf_buffer_opts *opts)
7639 struct perf_buffer_params p = {};
7640 struct perf_event_attr attr = { 0, };
7642 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
7643 attr.type = PERF_TYPE_SOFTWARE;
7644 attr.sample_type = PERF_SAMPLE_RAW;
7645 attr.sample_period = 1;
7646 attr.wakeup_events = 1;
7649 p.sample_cb = opts ? opts->sample_cb : NULL;
7650 p.lost_cb = opts ? opts->lost_cb : NULL;
7651 p.ctx = opts ? opts->ctx : NULL;
7653 return __perf_buffer__new(map_fd, page_cnt, &p);
7656 struct perf_buffer *
7657 perf_buffer__new_raw(int map_fd, size_t page_cnt,
7658 const struct perf_buffer_raw_opts *opts)
7660 struct perf_buffer_params p = {};
7662 p.attr = opts->attr;
7663 p.event_cb = opts->event_cb;
7665 p.cpu_cnt = opts->cpu_cnt;
7666 p.cpus = opts->cpus;
7667 p.map_keys = opts->map_keys;
7669 return __perf_buffer__new(map_fd, page_cnt, &p);
7672 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
7673 struct perf_buffer_params *p)
7675 const char *online_cpus_file = "/sys/devices/system/cpu/online";
7676 struct bpf_map_info map = {};
7677 char msg[STRERR_BUFSIZE];
7678 struct perf_buffer *pb;
7679 bool *online = NULL;
7683 if (page_cnt & (page_cnt - 1)) {
7684 pr_warn("page count should be power of two, but is %zu\n",
7686 return ERR_PTR(-EINVAL);
7689 map_info_len = sizeof(map);
7690 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
7693 pr_warn("failed to get map info for map FD %d: %s\n",
7694 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
7695 return ERR_PTR(err);
7698 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
7699 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
7701 return ERR_PTR(-EINVAL);
7704 pb = calloc(1, sizeof(*pb));
7706 return ERR_PTR(-ENOMEM);
7708 pb->event_cb = p->event_cb;
7709 pb->sample_cb = p->sample_cb;
7710 pb->lost_cb = p->lost_cb;
7713 pb->page_size = getpagesize();
7714 pb->mmap_size = pb->page_size * page_cnt;
7715 pb->map_fd = map_fd;
7717 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
7718 if (pb->epoll_fd < 0) {
7720 pr_warn("failed to create epoll instance: %s\n",
7721 libbpf_strerror_r(err, msg, sizeof(msg)));
7725 if (p->cpu_cnt > 0) {
7726 pb->cpu_cnt = p->cpu_cnt;
7728 pb->cpu_cnt = libbpf_num_possible_cpus();
7729 if (pb->cpu_cnt < 0) {
7733 if (map.max_entries < pb->cpu_cnt)
7734 pb->cpu_cnt = map.max_entries;
7737 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
7740 pr_warn("failed to allocate events: out of memory\n");
7743 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
7744 if (!pb->cpu_bufs) {
7746 pr_warn("failed to allocate buffers: out of memory\n");
7750 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
7752 pr_warn("failed to get online CPU mask: %d\n", err);
7756 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
7757 struct perf_cpu_buf *cpu_buf;
7760 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7761 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7763 /* in case user didn't explicitly requested particular CPUs to
7764 * be attached to, skip offline/not present CPUs
7766 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7769 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7770 if (IS_ERR(cpu_buf)) {
7771 err = PTR_ERR(cpu_buf);
7775 pb->cpu_bufs[j] = cpu_buf;
7777 err = bpf_map_update_elem(pb->map_fd, &map_key,
7781 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7782 cpu, map_key, cpu_buf->fd,
7783 libbpf_strerror_r(err, msg, sizeof(msg)));
7787 pb->events[j].events = EPOLLIN;
7788 pb->events[j].data.ptr = cpu_buf;
7789 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
7790 &pb->events[j]) < 0) {
7792 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7794 libbpf_strerror_r(err, msg, sizeof(msg)));
7807 perf_buffer__free(pb);
7808 return ERR_PTR(err);
7811 struct perf_sample_raw {
7812 struct perf_event_header header;
7817 struct perf_sample_lost {
7818 struct perf_event_header header;
7824 static enum bpf_perf_event_ret
7825 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7827 struct perf_cpu_buf *cpu_buf = ctx;
7828 struct perf_buffer *pb = cpu_buf->pb;
7831 /* user wants full control over parsing perf event */
7833 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7836 case PERF_RECORD_SAMPLE: {
7837 struct perf_sample_raw *s = data;
7840 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7843 case PERF_RECORD_LOST: {
7844 struct perf_sample_lost *s = data;
7847 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7851 pr_warn("unknown perf sample type %d\n", e->type);
7852 return LIBBPF_PERF_EVENT_ERROR;
7854 return LIBBPF_PERF_EVENT_CONT;
7857 static int perf_buffer__process_records(struct perf_buffer *pb,
7858 struct perf_cpu_buf *cpu_buf)
7860 enum bpf_perf_event_ret ret;
7862 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7863 pb->page_size, &cpu_buf->buf,
7865 perf_buffer__process_record, cpu_buf);
7866 if (ret != LIBBPF_PERF_EVENT_CONT)
7871 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7875 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7876 for (i = 0; i < cnt; i++) {
7877 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7879 err = perf_buffer__process_records(pb, cpu_buf);
7881 pr_warn("error while processing records: %d\n", err);
7885 return cnt < 0 ? -errno : cnt;
7888 struct bpf_prog_info_array_desc {
7889 int array_offset; /* e.g. offset of jited_prog_insns */
7890 int count_offset; /* e.g. offset of jited_prog_len */
7891 int size_offset; /* > 0: offset of rec size,
7892 * < 0: fix size of -size_offset
7896 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7897 [BPF_PROG_INFO_JITED_INSNS] = {
7898 offsetof(struct bpf_prog_info, jited_prog_insns),
7899 offsetof(struct bpf_prog_info, jited_prog_len),
7902 [BPF_PROG_INFO_XLATED_INSNS] = {
7903 offsetof(struct bpf_prog_info, xlated_prog_insns),
7904 offsetof(struct bpf_prog_info, xlated_prog_len),
7907 [BPF_PROG_INFO_MAP_IDS] = {
7908 offsetof(struct bpf_prog_info, map_ids),
7909 offsetof(struct bpf_prog_info, nr_map_ids),
7910 -(int)sizeof(__u32),
7912 [BPF_PROG_INFO_JITED_KSYMS] = {
7913 offsetof(struct bpf_prog_info, jited_ksyms),
7914 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7915 -(int)sizeof(__u64),
7917 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7918 offsetof(struct bpf_prog_info, jited_func_lens),
7919 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7920 -(int)sizeof(__u32),
7922 [BPF_PROG_INFO_FUNC_INFO] = {
7923 offsetof(struct bpf_prog_info, func_info),
7924 offsetof(struct bpf_prog_info, nr_func_info),
7925 offsetof(struct bpf_prog_info, func_info_rec_size),
7927 [BPF_PROG_INFO_LINE_INFO] = {
7928 offsetof(struct bpf_prog_info, line_info),
7929 offsetof(struct bpf_prog_info, nr_line_info),
7930 offsetof(struct bpf_prog_info, line_info_rec_size),
7932 [BPF_PROG_INFO_JITED_LINE_INFO] = {
7933 offsetof(struct bpf_prog_info, jited_line_info),
7934 offsetof(struct bpf_prog_info, nr_jited_line_info),
7935 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7937 [BPF_PROG_INFO_PROG_TAGS] = {
7938 offsetof(struct bpf_prog_info, prog_tags),
7939 offsetof(struct bpf_prog_info, nr_prog_tags),
7940 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7945 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7948 __u32 *array = (__u32 *)info;
7951 return array[offset / sizeof(__u32)];
7952 return -(int)offset;
7955 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7958 __u64 *array = (__u64 *)info;
7961 return array[offset / sizeof(__u64)];
7962 return -(int)offset;
7965 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7968 __u32 *array = (__u32 *)info;
7971 array[offset / sizeof(__u32)] = val;
7974 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7977 __u64 *array = (__u64 *)info;
7980 array[offset / sizeof(__u64)] = val;
7983 struct bpf_prog_info_linear *
7984 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7986 struct bpf_prog_info_linear *info_linear;
7987 struct bpf_prog_info info = {};
7988 __u32 info_len = sizeof(info);
7993 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7994 return ERR_PTR(-EINVAL);
7996 /* step 1: get array dimensions */
7997 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7999 pr_debug("can't get prog info: %s", strerror(errno));
8000 return ERR_PTR(-EFAULT);
8003 /* step 2: calculate total size of all arrays */
8004 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8005 bool include_array = (arrays & (1UL << i)) > 0;
8006 struct bpf_prog_info_array_desc *desc;
8009 desc = bpf_prog_info_array_desc + i;
8011 /* kernel is too old to support this field */
8012 if (info_len < desc->array_offset + sizeof(__u32) ||
8013 info_len < desc->count_offset + sizeof(__u32) ||
8014 (desc->size_offset > 0 && info_len < desc->size_offset))
8015 include_array = false;
8017 if (!include_array) {
8018 arrays &= ~(1UL << i); /* clear the bit */
8022 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8023 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8025 data_len += count * size;
8028 /* step 3: allocate continuous memory */
8029 data_len = roundup(data_len, sizeof(__u64));
8030 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
8032 return ERR_PTR(-ENOMEM);
8034 /* step 4: fill data to info_linear->info */
8035 info_linear->arrays = arrays;
8036 memset(&info_linear->info, 0, sizeof(info));
8037 ptr = info_linear->data;
8039 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8040 struct bpf_prog_info_array_desc *desc;
8043 if ((arrays & (1UL << i)) == 0)
8046 desc = bpf_prog_info_array_desc + i;
8047 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8048 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8049 bpf_prog_info_set_offset_u32(&info_linear->info,
8050 desc->count_offset, count);
8051 bpf_prog_info_set_offset_u32(&info_linear->info,
8052 desc->size_offset, size);
8053 bpf_prog_info_set_offset_u64(&info_linear->info,
8056 ptr += count * size;
8059 /* step 5: call syscall again to get required arrays */
8060 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
8062 pr_debug("can't get prog info: %s", strerror(errno));
8064 return ERR_PTR(-EFAULT);
8067 /* step 6: verify the data */
8068 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8069 struct bpf_prog_info_array_desc *desc;
8072 if ((arrays & (1UL << i)) == 0)
8075 desc = bpf_prog_info_array_desc + i;
8076 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8077 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8078 desc->count_offset);
8080 pr_warn("%s: mismatch in element count\n", __func__);
8082 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8083 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8086 pr_warn("%s: mismatch in rec size\n", __func__);
8089 /* step 7: update info_len and data_len */
8090 info_linear->info_len = sizeof(struct bpf_prog_info);
8091 info_linear->data_len = data_len;
8096 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
8100 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8101 struct bpf_prog_info_array_desc *desc;
8104 if ((info_linear->arrays & (1UL << i)) == 0)
8107 desc = bpf_prog_info_array_desc + i;
8108 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
8109 desc->array_offset);
8110 offs = addr - ptr_to_u64(info_linear->data);
8111 bpf_prog_info_set_offset_u64(&info_linear->info,
8112 desc->array_offset, offs);
8116 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
8120 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8121 struct bpf_prog_info_array_desc *desc;
8124 if ((info_linear->arrays & (1UL << i)) == 0)
8127 desc = bpf_prog_info_array_desc + i;
8128 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
8129 desc->array_offset);
8130 addr = offs + ptr_to_u64(info_linear->data);
8131 bpf_prog_info_set_offset_u64(&info_linear->info,
8132 desc->array_offset, addr);
8136 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
8138 int err = 0, n, len, start, end = -1;
8144 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
8146 if (*s == ',' || *s == '\n') {
8150 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
8151 if (n <= 0 || n > 2) {
8152 pr_warn("Failed to get CPU range %s: %d\n", s, n);
8155 } else if (n == 1) {
8158 if (start < 0 || start > end) {
8159 pr_warn("Invalid CPU range [%d,%d] in %s\n",
8164 tmp = realloc(*mask, end + 1);
8170 memset(tmp + *mask_sz, 0, start - *mask_sz);
8171 memset(tmp + start, 1, end - start + 1);
8176 pr_warn("Empty CPU range\n");
8186 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
8188 int fd, err = 0, len;
8191 fd = open(fcpu, O_RDONLY);
8194 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
8197 len = read(fd, buf, sizeof(buf));
8200 err = len ? -errno : -EINVAL;
8201 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
8204 if (len >= sizeof(buf)) {
8205 pr_warn("CPU mask is too big in file %s\n", fcpu);
8210 return parse_cpu_mask_str(buf, mask, mask_sz);
8213 int libbpf_num_possible_cpus(void)
8215 static const char *fcpu = "/sys/devices/system/cpu/possible";
8217 int err, n, i, tmp_cpus;
8220 tmp_cpus = READ_ONCE(cpus);
8224 err = parse_cpu_mask_file(fcpu, &mask, &n);
8229 for (i = 0; i < n; i++) {
8235 WRITE_ONCE(cpus, tmp_cpus);
8239 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
8240 const struct bpf_object_open_opts *opts)
8242 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
8243 .object_name = s->name,
8245 struct bpf_object *obj;
8248 /* Attempt to preserve opts->object_name, unless overriden by user
8249 * explicitly. Overwriting object name for skeletons is discouraged,
8250 * as it breaks global data maps, because they contain object name
8251 * prefix as their own map name prefix. When skeleton is generated,
8252 * bpftool is making an assumption that this name will stay the same.
8255 memcpy(&skel_opts, opts, sizeof(*opts));
8256 if (!opts->object_name)
8257 skel_opts.object_name = s->name;
8260 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
8262 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
8263 s->name, PTR_ERR(obj));
8264 return PTR_ERR(obj);
8269 for (i = 0; i < s->map_cnt; i++) {
8270 struct bpf_map **map = s->maps[i].map;
8271 const char *name = s->maps[i].name;
8272 void **mmaped = s->maps[i].mmaped;
8274 *map = bpf_object__find_map_by_name(obj, name);
8276 pr_warn("failed to find skeleton map '%s'\n", name);
8280 /* externs shouldn't be pre-setup from user code */
8281 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
8282 *mmaped = (*map)->mmaped;
8285 for (i = 0; i < s->prog_cnt; i++) {
8286 struct bpf_program **prog = s->progs[i].prog;
8287 const char *name = s->progs[i].name;
8289 *prog = bpf_object__find_program_by_name(obj, name);
8291 pr_warn("failed to find skeleton program '%s'\n", name);
8299 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
8303 err = bpf_object__load(*s->obj);
8305 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
8309 for (i = 0; i < s->map_cnt; i++) {
8310 struct bpf_map *map = *s->maps[i].map;
8311 size_t mmap_sz = bpf_map_mmap_sz(map);
8312 int prot, map_fd = bpf_map__fd(map);
8313 void **mmaped = s->maps[i].mmaped;
8318 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
8323 if (map->def.map_flags & BPF_F_RDONLY_PROG)
8326 prot = PROT_READ | PROT_WRITE;
8328 /* Remap anonymous mmap()-ed "map initialization image" as
8329 * a BPF map-backed mmap()-ed memory, but preserving the same
8330 * memory address. This will cause kernel to change process'
8331 * page table to point to a different piece of kernel memory,
8332 * but from userspace point of view memory address (and its
8333 * contents, being identical at this point) will stay the
8334 * same. This mapping will be released by bpf_object__close()
8335 * as per normal clean up procedure, so we don't need to worry
8336 * about it from skeleton's clean up perspective.
8338 *mmaped = mmap(map->mmaped, mmap_sz, prot,
8339 MAP_SHARED | MAP_FIXED, map_fd, 0);
8340 if (*mmaped == MAP_FAILED) {
8343 pr_warn("failed to re-mmap() map '%s': %d\n",
8344 bpf_map__name(map), err);
8352 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
8356 for (i = 0; i < s->prog_cnt; i++) {
8357 struct bpf_program *prog = *s->progs[i].prog;
8358 struct bpf_link **link = s->progs[i].link;
8359 const struct bpf_sec_def *sec_def;
8360 const char *sec_name = bpf_program__title(prog, false);
8362 sec_def = find_sec_def(sec_name);
8363 if (!sec_def || !sec_def->attach_fn)
8366 *link = sec_def->attach_fn(sec_def, prog);
8367 if (IS_ERR(*link)) {
8368 pr_warn("failed to auto-attach program '%s': %ld\n",
8369 bpf_program__name(prog), PTR_ERR(*link));
8370 return PTR_ERR(*link);
8377 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
8381 for (i = 0; i < s->prog_cnt; i++) {
8382 struct bpf_link **link = s->progs[i].link;
8384 if (!IS_ERR_OR_NULL(*link))
8385 bpf_link__destroy(*link);
8390 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
8393 bpf_object__detach_skeleton(s);
8395 bpf_object__close(*s->obj);