1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/list.h>
35 #include <linux/limits.h>
36 #include <linux/perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <linux/version.h>
39 #include <sys/epoll.h>
40 #include <sys/ioctl.h>
43 #include <sys/types.h>
45 #include <sys/utsname.h>
46 #include <sys/resource.h>
54 #include "str_error.h"
55 #include "libbpf_internal.h"
57 #include "bpf_gen_internal.h"
60 #define BPF_FS_MAGIC 0xcafe4a11
63 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66 * compilation if user enables corresponding warning. Disable it explicitly.
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
70 #define __printf(a, b) __attribute__((format(printf, a, b)))
72 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
73 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
75 static int __base_pr(enum libbpf_print_level level, const char *format,
78 if (level == LIBBPF_DEBUG)
81 return vfprintf(stderr, format, args);
84 static libbpf_print_fn_t __libbpf_pr = __base_pr;
86 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
88 libbpf_print_fn_t old_print_fn = __libbpf_pr;
95 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
102 va_start(args, format);
103 __libbpf_pr(level, format, args);
107 static void pr_perm_msg(int err)
112 if (err != -EPERM || geteuid() != 0)
115 err = getrlimit(RLIMIT_MEMLOCK, &limit);
119 if (limit.rlim_cur == RLIM_INFINITY)
122 if (limit.rlim_cur < 1024)
123 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
124 else if (limit.rlim_cur < 1024*1024)
125 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
127 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
129 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
133 #define STRERR_BUFSIZE 128
135 /* Copied from tools/perf/util/util.h */
137 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
141 # define zclose(fd) ({ \
144 ___err = close((fd)); \
149 static inline __u64 ptr_to_u64(const void *ptr)
151 return (__u64) (unsigned long) ptr;
154 /* this goes away in libbpf 1.0 */
155 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
157 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
159 /* __LIBBPF_STRICT_LAST is the last power-of-2 value used + 1, so to
160 * get all possible values we compensate last +1, and then (2*x - 1)
161 * to get the bit mask
163 if (mode != LIBBPF_STRICT_ALL
164 && (mode & ~((__LIBBPF_STRICT_LAST - 1) * 2 - 1)))
165 return errno = EINVAL, -EINVAL;
171 enum kern_feature_id {
172 /* v4.14: kernel support for program & map names. */
174 /* v5.2: kernel support for global data sections. */
178 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
180 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
182 /* BTF_FUNC_GLOBAL is supported */
183 FEAT_BTF_GLOBAL_FUNC,
184 /* BPF_F_MMAPABLE is supported for arrays */
186 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
187 FEAT_EXP_ATTACH_TYPE,
188 /* bpf_probe_read_{kernel,user}[_str] helpers */
189 FEAT_PROBE_READ_KERN,
190 /* BPF_PROG_BIND_MAP is supported */
192 /* Kernel support for module BTFs */
194 /* BTF_KIND_FLOAT support */
196 /* BPF perf link support */
201 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
213 enum reloc_type type;
221 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
222 struct bpf_program *prog);
227 enum bpf_prog_type prog_type;
228 enum bpf_attach_type expected_attach_type;
229 bool is_exp_attach_type_optional;
233 attach_fn_t attach_fn;
237 * bpf_prog should be a better name but it has been used in
241 const struct bpf_sec_def *sec_def;
244 /* this program's instruction offset (in number of instructions)
245 * within its containing ELF section
248 /* number of original instructions in ELF section belonging to this
249 * program, not taking into account subprogram instructions possible
250 * appended later during relocation
253 /* Offset (in number of instructions) of the start of instruction
254 * belonging to this BPF program within its containing main BPF
255 * program. For the entry-point (main) BPF program, this is always
256 * zero. For a sub-program, this gets reset before each of main BPF
257 * programs are processed and relocated and is used to determined
258 * whether sub-program was already appended to the main program, and
259 * if yes, at which instruction offset.
264 /* sec_name with / replaced by _; makes recursive pinning
265 * in bpf_object__pin_programs easier
269 /* instructions that belong to BPF program; insns[0] is located at
270 * sec_insn_off instruction within its ELF section in ELF file, so
271 * when mapping ELF file instruction index to the local instruction,
272 * one needs to subtract sec_insn_off; and vice versa.
274 struct bpf_insn *insns;
275 /* actual number of instruction in this BPF program's image; for
276 * entry-point BPF programs this includes the size of main program
277 * itself plus all the used sub-programs, appended at the end
281 struct reloc_desc *reloc_desc;
289 bpf_program_prep_t preprocessor;
291 struct bpf_object *obj;
293 bpf_program_clear_priv_t clear_priv;
296 bool mark_btf_static;
297 enum bpf_prog_type type;
298 enum bpf_attach_type expected_attach_type;
300 __u32 attach_btf_obj_fd;
302 __u32 attach_prog_fd;
304 __u32 func_info_rec_size;
308 __u32 line_info_rec_size;
313 struct bpf_struct_ops {
315 const struct btf_type *type;
316 struct bpf_program **progs;
317 __u32 *kern_func_off;
318 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
320 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
321 * btf_vmlinux's format.
322 * struct bpf_struct_ops_tcp_congestion_ops {
323 * [... some other kernel fields ...]
324 * struct tcp_congestion_ops data;
326 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
327 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
334 #define DATA_SEC ".data"
335 #define BSS_SEC ".bss"
336 #define RODATA_SEC ".rodata"
337 #define KCONFIG_SEC ".kconfig"
338 #define KSYMS_SEC ".ksyms"
339 #define STRUCT_OPS_SEC ".struct_ops"
341 enum libbpf_map_type {
349 static const char * const libbpf_type_to_btf_name[] = {
350 [LIBBPF_MAP_DATA] = DATA_SEC,
351 [LIBBPF_MAP_BSS] = BSS_SEC,
352 [LIBBPF_MAP_RODATA] = RODATA_SEC,
353 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
363 struct bpf_map_def def;
366 __u32 btf_key_type_id;
367 __u32 btf_value_type_id;
368 __u32 btf_vmlinux_value_type_id;
370 bpf_map_clear_priv_t clear_priv;
371 enum libbpf_map_type libbpf_type;
373 struct bpf_struct_ops *st_ops;
374 struct bpf_map *inner_map;
398 enum extern_type type;
414 unsigned long long addr;
416 /* target btf_id of the corresponding kernel var. */
417 int kernel_btf_obj_fd;
420 /* local btf_id of the ksym extern's type. */
426 static LIST_HEAD(bpf_objects_list);
436 char name[BPF_OBJ_NAME_LEN];
440 struct bpf_program *programs;
442 struct bpf_map *maps;
447 struct extern_desc *externs;
455 struct bpf_gen *gen_loader;
458 * Information when doing elf related work. Only valid if fd
471 Elf_Data *st_ops_data;
472 size_t shstrndx; /* section index for section name strings */
481 __u32 btf_maps_sec_btf_id;
490 * All loaded bpf_object is linked in a list, which is
491 * hidden to caller. bpf_objects__<func> handlers deal with
494 struct list_head list;
497 struct btf_ext *btf_ext;
499 /* Parse and load BTF vmlinux if any of the programs in the object need
502 struct btf *btf_vmlinux;
503 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
504 * override for vmlinux BTF.
506 char *btf_custom_path;
507 /* vmlinux BTF override for CO-RE relocations */
508 struct btf *btf_vmlinux_override;
509 /* Lazily initialized kernel module BTFs */
510 struct module_btf *btf_modules;
511 bool btf_modules_loaded;
512 size_t btf_module_cnt;
513 size_t btf_module_cap;
516 bpf_object_clear_priv_t clear_priv;
520 #define obj_elf_valid(o) ((o)->efile.elf)
522 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
523 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
524 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
525 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
526 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr);
527 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
528 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
530 void bpf_program__unload(struct bpf_program *prog)
538 * If the object is opened but the program was never loaded,
539 * it is possible that prog->instances.nr == -1.
541 if (prog->instances.nr > 0) {
542 for (i = 0; i < prog->instances.nr; i++)
543 zclose(prog->instances.fds[i]);
544 } else if (prog->instances.nr != -1) {
545 pr_warn("Internal error: instances.nr is %d\n",
549 prog->instances.nr = -1;
550 zfree(&prog->instances.fds);
552 zfree(&prog->func_info);
553 zfree(&prog->line_info);
556 static void bpf_program__exit(struct bpf_program *prog)
561 if (prog->clear_priv)
562 prog->clear_priv(prog, prog->priv);
565 prog->clear_priv = NULL;
567 bpf_program__unload(prog);
569 zfree(&prog->sec_name);
570 zfree(&prog->pin_name);
572 zfree(&prog->reloc_desc);
579 static char *__bpf_program__pin_name(struct bpf_program *prog)
583 name = p = strdup(prog->sec_name);
584 while ((p = strchr(p, '/')))
590 static bool insn_is_subprog_call(const struct bpf_insn *insn)
592 return BPF_CLASS(insn->code) == BPF_JMP &&
593 BPF_OP(insn->code) == BPF_CALL &&
594 BPF_SRC(insn->code) == BPF_K &&
595 insn->src_reg == BPF_PSEUDO_CALL &&
596 insn->dst_reg == 0 &&
600 static bool is_call_insn(const struct bpf_insn *insn)
602 return insn->code == (BPF_JMP | BPF_CALL);
605 static bool insn_is_pseudo_func(struct bpf_insn *insn)
607 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
611 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
612 const char *name, size_t sec_idx, const char *sec_name,
613 size_t sec_off, void *insn_data, size_t insn_data_sz)
615 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
616 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
617 sec_name, name, sec_off, insn_data_sz);
621 memset(prog, 0, sizeof(*prog));
624 prog->sec_idx = sec_idx;
625 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
626 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
627 /* insns_cnt can later be increased by appending used subprograms */
628 prog->insns_cnt = prog->sec_insn_cnt;
630 prog->type = BPF_PROG_TYPE_UNSPEC;
633 prog->instances.fds = NULL;
634 prog->instances.nr = -1;
636 prog->sec_name = strdup(sec_name);
640 prog->name = strdup(name);
644 prog->pin_name = __bpf_program__pin_name(prog);
648 prog->insns = malloc(insn_data_sz);
651 memcpy(prog->insns, insn_data, insn_data_sz);
655 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
656 bpf_program__exit(prog);
661 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
662 const char *sec_name, int sec_idx)
664 Elf_Data *symbols = obj->efile.symbols;
665 struct bpf_program *prog, *progs;
666 void *data = sec_data->d_buf;
667 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
668 int nr_progs, err, i;
672 progs = obj->programs;
673 nr_progs = obj->nr_programs;
674 nr_syms = symbols->d_size / sizeof(GElf_Sym);
677 for (i = 0; i < nr_syms; i++) {
678 if (!gelf_getsym(symbols, i, &sym))
680 if (sym.st_shndx != sec_idx)
682 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
685 prog_sz = sym.st_size;
686 sec_off = sym.st_value;
688 name = elf_sym_str(obj, sym.st_name);
690 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
692 return -LIBBPF_ERRNO__FORMAT;
695 if (sec_off + prog_sz > sec_sz) {
696 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
698 return -LIBBPF_ERRNO__FORMAT;
701 if (sec_idx != obj->efile.text_shndx && GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
702 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
706 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
707 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
709 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
712 * In this case the original obj->programs
713 * is still valid, so don't need special treat for
714 * bpf_close_object().
716 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
720 obj->programs = progs;
722 prog = &progs[nr_progs];
724 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
725 sec_off, data + sec_off, prog_sz);
729 /* if function is a global/weak symbol, but has restricted
730 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
731 * as static to enable more permissive BPF verification mode
732 * with more outside context available to BPF verifier
734 if (GELF_ST_BIND(sym.st_info) != STB_LOCAL
735 && (GELF_ST_VISIBILITY(sym.st_other) == STV_HIDDEN
736 || GELF_ST_VISIBILITY(sym.st_other) == STV_INTERNAL))
737 prog->mark_btf_static = true;
740 obj->nr_programs = nr_progs;
746 static __u32 get_kernel_version(void)
748 __u32 major, minor, patch;
752 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
754 return KERNEL_VERSION(major, minor, patch);
757 static const struct btf_member *
758 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
760 struct btf_member *m;
763 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
764 if (btf_member_bit_offset(t, i) == bit_offset)
771 static const struct btf_member *
772 find_member_by_name(const struct btf *btf, const struct btf_type *t,
775 struct btf_member *m;
778 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
779 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
786 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
787 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
788 const char *name, __u32 kind);
791 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
792 const struct btf_type **type, __u32 *type_id,
793 const struct btf_type **vtype, __u32 *vtype_id,
794 const struct btf_member **data_member)
796 const struct btf_type *kern_type, *kern_vtype;
797 const struct btf_member *kern_data_member;
798 __s32 kern_vtype_id, kern_type_id;
801 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
802 if (kern_type_id < 0) {
803 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
807 kern_type = btf__type_by_id(btf, kern_type_id);
809 /* Find the corresponding "map_value" type that will be used
810 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
811 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
814 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
815 tname, BTF_KIND_STRUCT);
816 if (kern_vtype_id < 0) {
817 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
818 STRUCT_OPS_VALUE_PREFIX, tname);
819 return kern_vtype_id;
821 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
823 /* Find "struct tcp_congestion_ops" from
824 * struct bpf_struct_ops_tcp_congestion_ops {
826 * struct tcp_congestion_ops data;
829 kern_data_member = btf_members(kern_vtype);
830 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
831 if (kern_data_member->type == kern_type_id)
834 if (i == btf_vlen(kern_vtype)) {
835 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
836 tname, STRUCT_OPS_VALUE_PREFIX, tname);
841 *type_id = kern_type_id;
843 *vtype_id = kern_vtype_id;
844 *data_member = kern_data_member;
849 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
851 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
854 /* Init the map's fields that depend on kern_btf */
855 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
856 const struct btf *btf,
857 const struct btf *kern_btf)
859 const struct btf_member *member, *kern_member, *kern_data_member;
860 const struct btf_type *type, *kern_type, *kern_vtype;
861 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
862 struct bpf_struct_ops *st_ops;
863 void *data, *kern_data;
867 st_ops = map->st_ops;
869 tname = st_ops->tname;
870 err = find_struct_ops_kern_types(kern_btf, tname,
871 &kern_type, &kern_type_id,
872 &kern_vtype, &kern_vtype_id,
877 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
878 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
880 map->def.value_size = kern_vtype->size;
881 map->btf_vmlinux_value_type_id = kern_vtype_id;
883 st_ops->kern_vdata = calloc(1, kern_vtype->size);
884 if (!st_ops->kern_vdata)
888 kern_data_off = kern_data_member->offset / 8;
889 kern_data = st_ops->kern_vdata + kern_data_off;
891 member = btf_members(type);
892 for (i = 0; i < btf_vlen(type); i++, member++) {
893 const struct btf_type *mtype, *kern_mtype;
894 __u32 mtype_id, kern_mtype_id;
895 void *mdata, *kern_mdata;
896 __s64 msize, kern_msize;
897 __u32 moff, kern_moff;
898 __u32 kern_member_idx;
901 mname = btf__name_by_offset(btf, member->name_off);
902 kern_member = find_member_by_name(kern_btf, kern_type, mname);
904 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
909 kern_member_idx = kern_member - btf_members(kern_type);
910 if (btf_member_bitfield_size(type, i) ||
911 btf_member_bitfield_size(kern_type, kern_member_idx)) {
912 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
917 moff = member->offset / 8;
918 kern_moff = kern_member->offset / 8;
921 kern_mdata = kern_data + kern_moff;
923 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
924 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
926 if (BTF_INFO_KIND(mtype->info) !=
927 BTF_INFO_KIND(kern_mtype->info)) {
928 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
929 map->name, mname, BTF_INFO_KIND(mtype->info),
930 BTF_INFO_KIND(kern_mtype->info));
934 if (btf_is_ptr(mtype)) {
935 struct bpf_program *prog;
937 prog = st_ops->progs[i];
941 kern_mtype = skip_mods_and_typedefs(kern_btf,
945 /* mtype->type must be a func_proto which was
946 * guaranteed in bpf_object__collect_st_ops_relos(),
947 * so only check kern_mtype for func_proto here.
949 if (!btf_is_func_proto(kern_mtype)) {
950 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
955 prog->attach_btf_id = kern_type_id;
956 prog->expected_attach_type = kern_member_idx;
958 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
960 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
961 map->name, mname, prog->name, moff,
967 msize = btf__resolve_size(btf, mtype_id);
968 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
969 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
970 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
971 map->name, mname, (ssize_t)msize,
972 (ssize_t)kern_msize);
976 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
977 map->name, mname, (unsigned int)msize,
979 memcpy(kern_mdata, mdata, msize);
985 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
991 for (i = 0; i < obj->nr_maps; i++) {
994 if (!bpf_map__is_struct_ops(map))
997 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1006 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1008 const struct btf_type *type, *datasec;
1009 const struct btf_var_secinfo *vsi;
1010 struct bpf_struct_ops *st_ops;
1011 const char *tname, *var_name;
1012 __s32 type_id, datasec_id;
1013 const struct btf *btf;
1014 struct bpf_map *map;
1017 if (obj->efile.st_ops_shndx == -1)
1021 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1023 if (datasec_id < 0) {
1024 pr_warn("struct_ops init: DATASEC %s not found\n",
1029 datasec = btf__type_by_id(btf, datasec_id);
1030 vsi = btf_var_secinfos(datasec);
1031 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1032 type = btf__type_by_id(obj->btf, vsi->type);
1033 var_name = btf__name_by_offset(obj->btf, type->name_off);
1035 type_id = btf__resolve_type(obj->btf, vsi->type);
1037 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1038 vsi->type, STRUCT_OPS_SEC);
1042 type = btf__type_by_id(obj->btf, type_id);
1043 tname = btf__name_by_offset(obj->btf, type->name_off);
1045 pr_warn("struct_ops init: anonymous type is not supported\n");
1048 if (!btf_is_struct(type)) {
1049 pr_warn("struct_ops init: %s is not a struct\n", tname);
1053 map = bpf_object__add_map(obj);
1055 return PTR_ERR(map);
1057 map->sec_idx = obj->efile.st_ops_shndx;
1058 map->sec_offset = vsi->offset;
1059 map->name = strdup(var_name);
1063 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1064 map->def.key_size = sizeof(int);
1065 map->def.value_size = type->size;
1066 map->def.max_entries = 1;
1068 map->st_ops = calloc(1, sizeof(*map->st_ops));
1071 st_ops = map->st_ops;
1072 st_ops->data = malloc(type->size);
1073 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1074 st_ops->kern_func_off = malloc(btf_vlen(type) *
1075 sizeof(*st_ops->kern_func_off));
1076 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1079 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1080 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1081 var_name, STRUCT_OPS_SEC);
1085 memcpy(st_ops->data,
1086 obj->efile.st_ops_data->d_buf + vsi->offset,
1088 st_ops->tname = tname;
1089 st_ops->type = type;
1090 st_ops->type_id = type_id;
1092 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1093 tname, type_id, var_name, vsi->offset);
1099 static struct bpf_object *bpf_object__new(const char *path,
1100 const void *obj_buf,
1102 const char *obj_name)
1104 struct bpf_object *obj;
1107 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1109 pr_warn("alloc memory failed for %s\n", path);
1110 return ERR_PTR(-ENOMEM);
1113 strcpy(obj->path, path);
1115 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1116 obj->name[sizeof(obj->name) - 1] = 0;
1118 /* Using basename() GNU version which doesn't modify arg. */
1119 strncpy(obj->name, basename((void *)path),
1120 sizeof(obj->name) - 1);
1121 end = strchr(obj->name, '.');
1128 * Caller of this function should also call
1129 * bpf_object__elf_finish() after data collection to return
1130 * obj_buf to user. If not, we should duplicate the buffer to
1131 * avoid user freeing them before elf finish.
1133 obj->efile.obj_buf = obj_buf;
1134 obj->efile.obj_buf_sz = obj_buf_sz;
1135 obj->efile.maps_shndx = -1;
1136 obj->efile.btf_maps_shndx = -1;
1137 obj->efile.data_shndx = -1;
1138 obj->efile.rodata_shndx = -1;
1139 obj->efile.bss_shndx = -1;
1140 obj->efile.st_ops_shndx = -1;
1141 obj->kconfig_map_idx = -1;
1142 obj->rodata_map_idx = -1;
1144 obj->kern_version = get_kernel_version();
1145 obj->loaded = false;
1147 INIT_LIST_HEAD(&obj->list);
1148 list_add(&obj->list, &bpf_objects_list);
1152 static void bpf_object__elf_finish(struct bpf_object *obj)
1154 if (!obj_elf_valid(obj))
1157 if (obj->efile.elf) {
1158 elf_end(obj->efile.elf);
1159 obj->efile.elf = NULL;
1161 obj->efile.symbols = NULL;
1162 obj->efile.data = NULL;
1163 obj->efile.rodata = NULL;
1164 obj->efile.bss = NULL;
1165 obj->efile.st_ops_data = NULL;
1167 zfree(&obj->efile.reloc_sects);
1168 obj->efile.nr_reloc_sects = 0;
1169 zclose(obj->efile.fd);
1170 obj->efile.obj_buf = NULL;
1171 obj->efile.obj_buf_sz = 0;
1174 static int bpf_object__elf_init(struct bpf_object *obj)
1179 if (obj_elf_valid(obj)) {
1180 pr_warn("elf: init internal error\n");
1181 return -LIBBPF_ERRNO__LIBELF;
1184 if (obj->efile.obj_buf_sz > 0) {
1186 * obj_buf should have been validated by
1187 * bpf_object__open_buffer().
1189 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1190 obj->efile.obj_buf_sz);
1192 obj->efile.fd = open(obj->path, O_RDONLY);
1193 if (obj->efile.fd < 0) {
1194 char errmsg[STRERR_BUFSIZE], *cp;
1197 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1198 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1202 obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1205 if (!obj->efile.elf) {
1206 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1207 err = -LIBBPF_ERRNO__LIBELF;
1211 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1212 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1213 err = -LIBBPF_ERRNO__FORMAT;
1216 ep = &obj->efile.ehdr;
1218 if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) {
1219 pr_warn("elf: failed to get section names section index for %s: %s\n",
1220 obj->path, elf_errmsg(-1));
1221 err = -LIBBPF_ERRNO__FORMAT;
1225 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1226 if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) {
1227 pr_warn("elf: failed to get section names strings from %s: %s\n",
1228 obj->path, elf_errmsg(-1));
1229 err = -LIBBPF_ERRNO__FORMAT;
1233 /* Old LLVM set e_machine to EM_NONE */
1234 if (ep->e_type != ET_REL ||
1235 (ep->e_machine && ep->e_machine != EM_BPF)) {
1236 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1237 err = -LIBBPF_ERRNO__FORMAT;
1243 bpf_object__elf_finish(obj);
1247 static int bpf_object__check_endianness(struct bpf_object *obj)
1249 #if __BYTE_ORDER == __LITTLE_ENDIAN
1250 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1252 #elif __BYTE_ORDER == __BIG_ENDIAN
1253 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1256 # error "Unrecognized __BYTE_ORDER__"
1258 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1259 return -LIBBPF_ERRNO__ENDIAN;
1263 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1265 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1266 pr_debug("license of %s is %s\n", obj->path, obj->license);
1271 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1275 if (size != sizeof(kver)) {
1276 pr_warn("invalid kver section in %s\n", obj->path);
1277 return -LIBBPF_ERRNO__FORMAT;
1279 memcpy(&kver, data, sizeof(kver));
1280 obj->kern_version = kver;
1281 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1285 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1287 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1288 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1293 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1301 } else if (!strcmp(name, DATA_SEC)) {
1302 if (obj->efile.data)
1303 *size = obj->efile.data->d_size;
1304 } else if (!strcmp(name, BSS_SEC)) {
1306 *size = obj->efile.bss->d_size;
1307 } else if (!strcmp(name, RODATA_SEC)) {
1308 if (obj->efile.rodata)
1309 *size = obj->efile.rodata->d_size;
1310 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1311 if (obj->efile.st_ops_data)
1312 *size = obj->efile.st_ops_data->d_size;
1314 Elf_Scn *scn = elf_sec_by_name(obj, name);
1315 Elf_Data *data = elf_sec_data(obj, scn);
1318 ret = 0; /* found it */
1319 *size = data->d_size;
1323 return *size ? 0 : ret;
1326 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1329 Elf_Data *symbols = obj->efile.symbols;
1336 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1339 if (!gelf_getsym(symbols, si, &sym))
1341 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1342 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1345 sname = elf_sym_str(obj, sym.st_name);
1347 pr_warn("failed to get sym name string for var %s\n",
1351 if (strcmp(name, sname) == 0) {
1352 *off = sym.st_value;
1360 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1362 struct bpf_map *new_maps;
1366 if (obj->nr_maps < obj->maps_cap)
1367 return &obj->maps[obj->nr_maps++];
1369 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1370 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1372 pr_warn("alloc maps for object failed\n");
1373 return ERR_PTR(-ENOMEM);
1376 obj->maps_cap = new_cap;
1377 obj->maps = new_maps;
1379 /* zero out new maps */
1380 memset(obj->maps + obj->nr_maps, 0,
1381 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1383 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1384 * when failure (zclose won't close negative fd)).
1386 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1387 obj->maps[i].fd = -1;
1388 obj->maps[i].inner_map_fd = -1;
1391 return &obj->maps[obj->nr_maps++];
1394 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1396 long page_sz = sysconf(_SC_PAGE_SIZE);
1399 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1400 map_sz = roundup(map_sz, page_sz);
1404 static char *internal_map_name(struct bpf_object *obj,
1405 enum libbpf_map_type type)
1407 char map_name[BPF_OBJ_NAME_LEN], *p;
1408 const char *sfx = libbpf_type_to_btf_name[type];
1409 int sfx_len = max((size_t)7, strlen(sfx));
1410 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1413 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1414 sfx_len, libbpf_type_to_btf_name[type]);
1416 /* sanitise map name to characters allowed by kernel */
1417 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1418 if (!isalnum(*p) && *p != '_' && *p != '.')
1421 return strdup(map_name);
1425 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1426 int sec_idx, void *data, size_t data_sz)
1428 struct bpf_map_def *def;
1429 struct bpf_map *map;
1432 map = bpf_object__add_map(obj);
1434 return PTR_ERR(map);
1436 map->libbpf_type = type;
1437 map->sec_idx = sec_idx;
1438 map->sec_offset = 0;
1439 map->name = internal_map_name(obj, type);
1441 pr_warn("failed to alloc map name\n");
1446 def->type = BPF_MAP_TYPE_ARRAY;
1447 def->key_size = sizeof(int);
1448 def->value_size = data_sz;
1449 def->max_entries = 1;
1450 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1451 ? BPF_F_RDONLY_PROG : 0;
1452 def->map_flags |= BPF_F_MMAPABLE;
1454 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1455 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1457 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1458 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1459 if (map->mmaped == MAP_FAILED) {
1462 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1469 memcpy(map->mmaped, data, data_sz);
1471 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1475 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1480 * Populate obj->maps with libbpf internal maps.
1482 if (obj->efile.data_shndx >= 0) {
1483 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1484 obj->efile.data_shndx,
1485 obj->efile.data->d_buf,
1486 obj->efile.data->d_size);
1490 if (obj->efile.rodata_shndx >= 0) {
1491 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1492 obj->efile.rodata_shndx,
1493 obj->efile.rodata->d_buf,
1494 obj->efile.rodata->d_size);
1498 obj->rodata_map_idx = obj->nr_maps - 1;
1500 if (obj->efile.bss_shndx >= 0) {
1501 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1502 obj->efile.bss_shndx,
1504 obj->efile.bss->d_size);
1512 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1517 for (i = 0; i < obj->nr_extern; i++) {
1518 if (strcmp(obj->externs[i].name, name) == 0)
1519 return &obj->externs[i];
1524 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1527 switch (ext->kcfg.type) {
1530 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1534 *(bool *)ext_val = value == 'y' ? true : false;
1538 *(enum libbpf_tristate *)ext_val = TRI_YES;
1539 else if (value == 'm')
1540 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1541 else /* value == 'n' */
1542 *(enum libbpf_tristate *)ext_val = TRI_NO;
1545 *(char *)ext_val = value;
1551 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1559 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1564 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1565 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1569 len = strlen(value);
1570 if (value[len - 1] != '"') {
1571 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1578 if (len >= ext->kcfg.sz) {
1579 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1580 ext->name, value, len, ext->kcfg.sz - 1);
1581 len = ext->kcfg.sz - 1;
1583 memcpy(ext_val, value + 1, len);
1584 ext_val[len] = '\0';
1589 static int parse_u64(const char *value, __u64 *res)
1595 *res = strtoull(value, &value_end, 0);
1598 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1602 pr_warn("failed to parse '%s' as integer completely\n", value);
1608 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1610 int bit_sz = ext->kcfg.sz * 8;
1612 if (ext->kcfg.sz == 8)
1615 /* Validate that value stored in u64 fits in integer of `ext->sz`
1616 * bytes size without any loss of information. If the target integer
1617 * is signed, we rely on the following limits of integer type of
1618 * Y bits and subsequent transformation:
1620 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1621 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1622 * 0 <= X + 2^(Y-1) < 2^Y
1624 * For unsigned target integer, check that all the (64 - Y) bits are
1627 if (ext->kcfg.is_signed)
1628 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1630 return (v >> bit_sz) == 0;
1633 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1636 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1637 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1638 ext->name, (unsigned long long)value);
1641 if (!is_kcfg_value_in_range(ext, value)) {
1642 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1643 ext->name, (unsigned long long)value, ext->kcfg.sz);
1646 switch (ext->kcfg.sz) {
1647 case 1: *(__u8 *)ext_val = value; break;
1648 case 2: *(__u16 *)ext_val = value; break;
1649 case 4: *(__u32 *)ext_val = value; break;
1650 case 8: *(__u64 *)ext_val = value; break;
1658 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1659 char *buf, void *data)
1661 struct extern_desc *ext;
1667 if (strncmp(buf, "CONFIG_", 7))
1670 sep = strchr(buf, '=');
1672 pr_warn("failed to parse '%s': no separator\n", buf);
1676 /* Trim ending '\n' */
1678 if (buf[len - 1] == '\n')
1679 buf[len - 1] = '\0';
1680 /* Split on '=' and ensure that a value is present. */
1684 pr_warn("failed to parse '%s': no value\n", buf);
1688 ext = find_extern_by_name(obj, buf);
1689 if (!ext || ext->is_set)
1692 ext_val = data + ext->kcfg.data_off;
1696 case 'y': case 'n': case 'm':
1697 err = set_kcfg_value_tri(ext, ext_val, *value);
1700 err = set_kcfg_value_str(ext, ext_val, value);
1703 /* assume integer */
1704 err = parse_u64(value, &num);
1706 pr_warn("extern (kcfg) %s=%s should be integer\n",
1710 err = set_kcfg_value_num(ext, ext_val, num);
1715 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1719 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1727 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1730 else if (len >= PATH_MAX)
1731 return -ENAMETOOLONG;
1733 /* gzopen also accepts uncompressed files. */
1734 file = gzopen(buf, "r");
1736 file = gzopen("/proc/config.gz", "r");
1739 pr_warn("failed to open system Kconfig\n");
1743 while (gzgets(file, buf, sizeof(buf))) {
1744 err = bpf_object__process_kconfig_line(obj, buf, data);
1746 pr_warn("error parsing system Kconfig line '%s': %d\n",
1757 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1758 const char *config, void *data)
1764 file = fmemopen((void *)config, strlen(config), "r");
1767 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1771 while (fgets(buf, sizeof(buf), file)) {
1772 err = bpf_object__process_kconfig_line(obj, buf, data);
1774 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1784 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1786 struct extern_desc *last_ext = NULL, *ext;
1790 for (i = 0; i < obj->nr_extern; i++) {
1791 ext = &obj->externs[i];
1792 if (ext->type == EXT_KCFG)
1799 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1800 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1801 obj->efile.symbols_shndx,
1806 obj->kconfig_map_idx = obj->nr_maps - 1;
1811 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1813 Elf_Data *symbols = obj->efile.symbols;
1814 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1815 Elf_Data *data = NULL;
1818 if (obj->efile.maps_shndx < 0)
1824 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1825 data = elf_sec_data(obj, scn);
1826 if (!scn || !data) {
1827 pr_warn("elf: failed to get legacy map definitions for %s\n",
1833 * Count number of maps. Each map has a name.
1834 * Array of maps is not supported: only the first element is
1837 * TODO: Detect array of map and report error.
1839 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1840 for (i = 0; i < nr_syms; i++) {
1843 if (!gelf_getsym(symbols, i, &sym))
1845 if (sym.st_shndx != obj->efile.maps_shndx)
1849 /* Assume equally sized map definitions */
1850 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1851 nr_maps, data->d_size, obj->path);
1853 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1854 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1858 map_def_sz = data->d_size / nr_maps;
1860 /* Fill obj->maps using data in "maps" section. */
1861 for (i = 0; i < nr_syms; i++) {
1863 const char *map_name;
1864 struct bpf_map_def *def;
1865 struct bpf_map *map;
1867 if (!gelf_getsym(symbols, i, &sym))
1869 if (sym.st_shndx != obj->efile.maps_shndx)
1872 map = bpf_object__add_map(obj);
1874 return PTR_ERR(map);
1876 map_name = elf_sym_str(obj, sym.st_name);
1878 pr_warn("failed to get map #%d name sym string for obj %s\n",
1880 return -LIBBPF_ERRNO__FORMAT;
1883 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION
1884 || GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
1885 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
1889 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1890 map->sec_idx = sym.st_shndx;
1891 map->sec_offset = sym.st_value;
1892 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1893 map_name, map->sec_idx, map->sec_offset);
1894 if (sym.st_value + map_def_sz > data->d_size) {
1895 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1896 obj->path, map_name);
1900 map->name = strdup(map_name);
1902 pr_warn("failed to alloc map name\n");
1905 pr_debug("map %d is \"%s\"\n", i, map->name);
1906 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1908 * If the definition of the map in the object file fits in
1909 * bpf_map_def, copy it. Any extra fields in our version
1910 * of bpf_map_def will default to zero as a result of the
1913 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1914 memcpy(&map->def, def, map_def_sz);
1917 * Here the map structure being read is bigger than what
1918 * we expect, truncate if the excess bits are all zero.
1919 * If they are not zero, reject this map as
1924 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1925 b < ((char *)def) + map_def_sz; b++) {
1927 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1928 obj->path, map_name);
1933 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1939 const struct btf_type *
1940 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1942 const struct btf_type *t = btf__type_by_id(btf, id);
1947 while (btf_is_mod(t) || btf_is_typedef(t)) {
1950 t = btf__type_by_id(btf, t->type);
1956 static const struct btf_type *
1957 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1959 const struct btf_type *t;
1961 t = skip_mods_and_typedefs(btf, id, NULL);
1965 t = skip_mods_and_typedefs(btf, t->type, res_id);
1967 return btf_is_func_proto(t) ? t : NULL;
1970 static const char *__btf_kind_str(__u16 kind)
1973 case BTF_KIND_UNKN: return "void";
1974 case BTF_KIND_INT: return "int";
1975 case BTF_KIND_PTR: return "ptr";
1976 case BTF_KIND_ARRAY: return "array";
1977 case BTF_KIND_STRUCT: return "struct";
1978 case BTF_KIND_UNION: return "union";
1979 case BTF_KIND_ENUM: return "enum";
1980 case BTF_KIND_FWD: return "fwd";
1981 case BTF_KIND_TYPEDEF: return "typedef";
1982 case BTF_KIND_VOLATILE: return "volatile";
1983 case BTF_KIND_CONST: return "const";
1984 case BTF_KIND_RESTRICT: return "restrict";
1985 case BTF_KIND_FUNC: return "func";
1986 case BTF_KIND_FUNC_PROTO: return "func_proto";
1987 case BTF_KIND_VAR: return "var";
1988 case BTF_KIND_DATASEC: return "datasec";
1989 case BTF_KIND_FLOAT: return "float";
1990 default: return "unknown";
1994 const char *btf_kind_str(const struct btf_type *t)
1996 return __btf_kind_str(btf_kind(t));
2000 * Fetch integer attribute of BTF map definition. Such attributes are
2001 * represented using a pointer to an array, in which dimensionality of array
2002 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2003 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2004 * type definition, while using only sizeof(void *) space in ELF data section.
2006 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2007 const struct btf_member *m, __u32 *res)
2009 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2010 const char *name = btf__name_by_offset(btf, m->name_off);
2011 const struct btf_array *arr_info;
2012 const struct btf_type *arr_t;
2014 if (!btf_is_ptr(t)) {
2015 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2016 map_name, name, btf_kind_str(t));
2020 arr_t = btf__type_by_id(btf, t->type);
2022 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2023 map_name, name, t->type);
2026 if (!btf_is_array(arr_t)) {
2027 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2028 map_name, name, btf_kind_str(arr_t));
2031 arr_info = btf_array(arr_t);
2032 *res = arr_info->nelems;
2036 static int build_map_pin_path(struct bpf_map *map, const char *path)
2042 path = "/sys/fs/bpf";
2044 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2047 else if (len >= PATH_MAX)
2048 return -ENAMETOOLONG;
2050 return bpf_map__set_pin_path(map, buf);
2053 int parse_btf_map_def(const char *map_name, struct btf *btf,
2054 const struct btf_type *def_t, bool strict,
2055 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2057 const struct btf_type *t;
2058 const struct btf_member *m;
2059 bool is_inner = inner_def == NULL;
2062 vlen = btf_vlen(def_t);
2063 m = btf_members(def_t);
2064 for (i = 0; i < vlen; i++, m++) {
2065 const char *name = btf__name_by_offset(btf, m->name_off);
2068 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2071 if (strcmp(name, "type") == 0) {
2072 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2074 map_def->parts |= MAP_DEF_MAP_TYPE;
2075 } else if (strcmp(name, "max_entries") == 0) {
2076 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2078 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2079 } else if (strcmp(name, "map_flags") == 0) {
2080 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2082 map_def->parts |= MAP_DEF_MAP_FLAGS;
2083 } else if (strcmp(name, "numa_node") == 0) {
2084 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2086 map_def->parts |= MAP_DEF_NUMA_NODE;
2087 } else if (strcmp(name, "key_size") == 0) {
2090 if (!get_map_field_int(map_name, btf, m, &sz))
2092 if (map_def->key_size && map_def->key_size != sz) {
2093 pr_warn("map '%s': conflicting key size %u != %u.\n",
2094 map_name, map_def->key_size, sz);
2097 map_def->key_size = sz;
2098 map_def->parts |= MAP_DEF_KEY_SIZE;
2099 } else if (strcmp(name, "key") == 0) {
2102 t = btf__type_by_id(btf, m->type);
2104 pr_warn("map '%s': key type [%d] not found.\n",
2108 if (!btf_is_ptr(t)) {
2109 pr_warn("map '%s': key spec is not PTR: %s.\n",
2110 map_name, btf_kind_str(t));
2113 sz = btf__resolve_size(btf, t->type);
2115 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2116 map_name, t->type, (ssize_t)sz);
2119 if (map_def->key_size && map_def->key_size != sz) {
2120 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2121 map_name, map_def->key_size, (ssize_t)sz);
2124 map_def->key_size = sz;
2125 map_def->key_type_id = t->type;
2126 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2127 } else if (strcmp(name, "value_size") == 0) {
2130 if (!get_map_field_int(map_name, btf, m, &sz))
2132 if (map_def->value_size && map_def->value_size != sz) {
2133 pr_warn("map '%s': conflicting value size %u != %u.\n",
2134 map_name, map_def->value_size, sz);
2137 map_def->value_size = sz;
2138 map_def->parts |= MAP_DEF_VALUE_SIZE;
2139 } else if (strcmp(name, "value") == 0) {
2142 t = btf__type_by_id(btf, m->type);
2144 pr_warn("map '%s': value type [%d] not found.\n",
2148 if (!btf_is_ptr(t)) {
2149 pr_warn("map '%s': value spec is not PTR: %s.\n",
2150 map_name, btf_kind_str(t));
2153 sz = btf__resolve_size(btf, t->type);
2155 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2156 map_name, t->type, (ssize_t)sz);
2159 if (map_def->value_size && map_def->value_size != sz) {
2160 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2161 map_name, map_def->value_size, (ssize_t)sz);
2164 map_def->value_size = sz;
2165 map_def->value_type_id = t->type;
2166 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2168 else if (strcmp(name, "values") == 0) {
2169 char inner_map_name[128];
2173 pr_warn("map '%s': multi-level inner maps not supported.\n",
2177 if (i != vlen - 1) {
2178 pr_warn("map '%s': '%s' member should be last.\n",
2182 if (!bpf_map_type__is_map_in_map(map_def->map_type)) {
2183 pr_warn("map '%s': should be map-in-map.\n",
2187 if (map_def->value_size && map_def->value_size != 4) {
2188 pr_warn("map '%s': conflicting value size %u != 4.\n",
2189 map_name, map_def->value_size);
2192 map_def->value_size = 4;
2193 t = btf__type_by_id(btf, m->type);
2195 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2199 if (!btf_is_array(t) || btf_array(t)->nelems) {
2200 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2204 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2205 if (!btf_is_ptr(t)) {
2206 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2207 map_name, btf_kind_str(t));
2210 t = skip_mods_and_typedefs(btf, t->type, NULL);
2211 if (!btf_is_struct(t)) {
2212 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2213 map_name, btf_kind_str(t));
2217 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2218 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2222 map_def->parts |= MAP_DEF_INNER_MAP;
2223 } else if (strcmp(name, "pinning") == 0) {
2227 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2230 if (!get_map_field_int(map_name, btf, m, &val))
2232 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2233 pr_warn("map '%s': invalid pinning value %u.\n",
2237 map_def->pinning = val;
2238 map_def->parts |= MAP_DEF_PINNING;
2241 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2244 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2248 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2249 pr_warn("map '%s': map type isn't specified.\n", map_name);
2256 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2258 map->def.type = def->map_type;
2259 map->def.key_size = def->key_size;
2260 map->def.value_size = def->value_size;
2261 map->def.max_entries = def->max_entries;
2262 map->def.map_flags = def->map_flags;
2264 map->numa_node = def->numa_node;
2265 map->btf_key_type_id = def->key_type_id;
2266 map->btf_value_type_id = def->value_type_id;
2268 if (def->parts & MAP_DEF_MAP_TYPE)
2269 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2271 if (def->parts & MAP_DEF_KEY_TYPE)
2272 pr_debug("map '%s': found key [%u], sz = %u.\n",
2273 map->name, def->key_type_id, def->key_size);
2274 else if (def->parts & MAP_DEF_KEY_SIZE)
2275 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2277 if (def->parts & MAP_DEF_VALUE_TYPE)
2278 pr_debug("map '%s': found value [%u], sz = %u.\n",
2279 map->name, def->value_type_id, def->value_size);
2280 else if (def->parts & MAP_DEF_VALUE_SIZE)
2281 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2283 if (def->parts & MAP_DEF_MAX_ENTRIES)
2284 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2285 if (def->parts & MAP_DEF_MAP_FLAGS)
2286 pr_debug("map '%s': found map_flags = %u.\n", map->name, def->map_flags);
2287 if (def->parts & MAP_DEF_PINNING)
2288 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2289 if (def->parts & MAP_DEF_NUMA_NODE)
2290 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2292 if (def->parts & MAP_DEF_INNER_MAP)
2293 pr_debug("map '%s': found inner map definition.\n", map->name);
2296 static const char *btf_var_linkage_str(__u32 linkage)
2299 case BTF_VAR_STATIC: return "static";
2300 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2301 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2302 default: return "unknown";
2306 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2307 const struct btf_type *sec,
2308 int var_idx, int sec_idx,
2309 const Elf_Data *data, bool strict,
2310 const char *pin_root_path)
2312 struct btf_map_def map_def = {}, inner_def = {};
2313 const struct btf_type *var, *def;
2314 const struct btf_var_secinfo *vi;
2315 const struct btf_var *var_extra;
2316 const char *map_name;
2317 struct bpf_map *map;
2320 vi = btf_var_secinfos(sec) + var_idx;
2321 var = btf__type_by_id(obj->btf, vi->type);
2322 var_extra = btf_var(var);
2323 map_name = btf__name_by_offset(obj->btf, var->name_off);
2325 if (map_name == NULL || map_name[0] == '\0') {
2326 pr_warn("map #%d: empty name.\n", var_idx);
2329 if ((__u64)vi->offset + vi->size > data->d_size) {
2330 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2333 if (!btf_is_var(var)) {
2334 pr_warn("map '%s': unexpected var kind %s.\n",
2335 map_name, btf_kind_str(var));
2338 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2339 pr_warn("map '%s': unsupported map linkage %s.\n",
2340 map_name, btf_var_linkage_str(var_extra->linkage));
2344 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2345 if (!btf_is_struct(def)) {
2346 pr_warn("map '%s': unexpected def kind %s.\n",
2347 map_name, btf_kind_str(var));
2350 if (def->size > vi->size) {
2351 pr_warn("map '%s': invalid def size.\n", map_name);
2355 map = bpf_object__add_map(obj);
2357 return PTR_ERR(map);
2358 map->name = strdup(map_name);
2360 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2363 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2364 map->def.type = BPF_MAP_TYPE_UNSPEC;
2365 map->sec_idx = sec_idx;
2366 map->sec_offset = vi->offset;
2367 map->btf_var_idx = var_idx;
2368 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2369 map_name, map->sec_idx, map->sec_offset);
2371 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2375 fill_map_from_def(map, &map_def);
2377 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2378 err = build_map_pin_path(map, pin_root_path);
2380 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2385 if (map_def.parts & MAP_DEF_INNER_MAP) {
2386 map->inner_map = calloc(1, sizeof(*map->inner_map));
2387 if (!map->inner_map)
2389 map->inner_map->fd = -1;
2390 map->inner_map->sec_idx = sec_idx;
2391 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2392 if (!map->inner_map->name)
2394 sprintf(map->inner_map->name, "%s.inner", map_name);
2396 fill_map_from_def(map->inner_map, &inner_def);
2402 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2403 const char *pin_root_path)
2405 const struct btf_type *sec = NULL;
2406 int nr_types, i, vlen, err;
2407 const struct btf_type *t;
2412 if (obj->efile.btf_maps_shndx < 0)
2415 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2416 data = elf_sec_data(obj, scn);
2417 if (!scn || !data) {
2418 pr_warn("elf: failed to get %s map definitions for %s\n",
2419 MAPS_ELF_SEC, obj->path);
2423 nr_types = btf__get_nr_types(obj->btf);
2424 for (i = 1; i <= nr_types; i++) {
2425 t = btf__type_by_id(obj->btf, i);
2426 if (!btf_is_datasec(t))
2428 name = btf__name_by_offset(obj->btf, t->name_off);
2429 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2431 obj->efile.btf_maps_sec_btf_id = i;
2437 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2441 vlen = btf_vlen(sec);
2442 for (i = 0; i < vlen; i++) {
2443 err = bpf_object__init_user_btf_map(obj, sec, i,
2444 obj->efile.btf_maps_shndx,
2454 static int bpf_object__init_maps(struct bpf_object *obj,
2455 const struct bpf_object_open_opts *opts)
2457 const char *pin_root_path;
2461 strict = !OPTS_GET(opts, relaxed_maps, false);
2462 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2464 err = bpf_object__init_user_maps(obj, strict);
2465 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2466 err = err ?: bpf_object__init_global_data_maps(obj);
2467 err = err ?: bpf_object__init_kconfig_map(obj);
2468 err = err ?: bpf_object__init_struct_ops_maps(obj);
2473 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2477 if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh))
2480 return sh.sh_flags & SHF_EXECINSTR;
2483 static bool btf_needs_sanitization(struct bpf_object *obj)
2485 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2486 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2487 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2488 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2490 return !has_func || !has_datasec || !has_func_global || !has_float;
2493 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2495 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2496 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2497 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2498 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2502 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2503 t = (struct btf_type *)btf__type_by_id(btf, i);
2505 if (!has_datasec && btf_is_var(t)) {
2506 /* replace VAR with INT */
2507 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2509 * using size = 1 is the safest choice, 4 will be too
2510 * big and cause kernel BTF validation failure if
2511 * original variable took less than 4 bytes
2514 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2515 } else if (!has_datasec && btf_is_datasec(t)) {
2516 /* replace DATASEC with STRUCT */
2517 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2518 struct btf_member *m = btf_members(t);
2519 struct btf_type *vt;
2522 name = (char *)btf__name_by_offset(btf, t->name_off);
2530 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2531 for (j = 0; j < vlen; j++, v++, m++) {
2532 /* order of field assignments is important */
2533 m->offset = v->offset * 8;
2535 /* preserve variable name as member name */
2536 vt = (void *)btf__type_by_id(btf, v->type);
2537 m->name_off = vt->name_off;
2539 } else if (!has_func && btf_is_func_proto(t)) {
2540 /* replace FUNC_PROTO with ENUM */
2542 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2543 t->size = sizeof(__u32); /* kernel enforced */
2544 } else if (!has_func && btf_is_func(t)) {
2545 /* replace FUNC with TYPEDEF */
2546 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2547 } else if (!has_func_global && btf_is_func(t)) {
2548 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2549 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2550 } else if (!has_float && btf_is_float(t)) {
2551 /* replace FLOAT with an equally-sized empty STRUCT;
2552 * since C compilers do not accept e.g. "float" as a
2553 * valid struct name, make it anonymous
2556 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2561 static bool libbpf_needs_btf(const struct bpf_object *obj)
2563 return obj->efile.btf_maps_shndx >= 0 ||
2564 obj->efile.st_ops_shndx >= 0 ||
2568 static bool kernel_needs_btf(const struct bpf_object *obj)
2570 return obj->efile.st_ops_shndx >= 0;
2573 static int bpf_object__init_btf(struct bpf_object *obj,
2575 Elf_Data *btf_ext_data)
2580 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2581 err = libbpf_get_error(obj->btf);
2584 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2587 /* enforce 8-byte pointers for BPF-targeted BTFs */
2588 btf__set_pointer_size(obj->btf, 8);
2592 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2593 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2596 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2597 err = libbpf_get_error(obj->btf_ext);
2599 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2600 BTF_EXT_ELF_SEC, err);
2601 obj->btf_ext = NULL;
2606 if (err && libbpf_needs_btf(obj)) {
2607 pr_warn("BTF is required, but is missing or corrupted.\n");
2613 static int bpf_object__finalize_btf(struct bpf_object *obj)
2620 err = btf__finalize_data(obj, obj->btf);
2622 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2629 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2631 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2632 prog->type == BPF_PROG_TYPE_LSM)
2635 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2636 * also need vmlinux BTF
2638 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2644 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2646 struct bpf_program *prog;
2649 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2652 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2655 /* Support for typed ksyms needs kernel BTF */
2656 for (i = 0; i < obj->nr_extern; i++) {
2657 const struct extern_desc *ext;
2659 ext = &obj->externs[i];
2660 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2664 bpf_object__for_each_program(prog, obj) {
2667 if (prog_needs_vmlinux_btf(prog))
2674 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2678 /* btf_vmlinux could be loaded earlier */
2679 if (obj->btf_vmlinux || obj->gen_loader)
2682 if (!force && !obj_needs_vmlinux_btf(obj))
2685 obj->btf_vmlinux = btf__load_vmlinux_btf();
2686 err = libbpf_get_error(obj->btf_vmlinux);
2688 pr_warn("Error loading vmlinux BTF: %d\n", err);
2689 obj->btf_vmlinux = NULL;
2695 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2697 struct btf *kern_btf = obj->btf;
2698 bool btf_mandatory, sanitize;
2704 if (!kernel_supports(obj, FEAT_BTF)) {
2705 if (kernel_needs_btf(obj)) {
2709 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2713 /* Even though some subprogs are global/weak, user might prefer more
2714 * permissive BPF verification process that BPF verifier performs for
2715 * static functions, taking into account more context from the caller
2716 * functions. In such case, they need to mark such subprogs with
2717 * __attribute__((visibility("hidden"))) and libbpf will adjust
2718 * corresponding FUNC BTF type to be marked as static and trigger more
2719 * involved BPF verification process.
2721 for (i = 0; i < obj->nr_programs; i++) {
2722 struct bpf_program *prog = &obj->programs[i];
2727 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2730 n = btf__get_nr_types(obj->btf);
2731 for (j = 1; j <= n; j++) {
2732 t = btf_type_by_id(obj->btf, j);
2733 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2736 name = btf__str_by_offset(obj->btf, t->name_off);
2737 if (strcmp(name, prog->name) != 0)
2740 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2745 sanitize = btf_needs_sanitization(obj);
2747 const void *raw_data;
2750 /* clone BTF to sanitize a copy and leave the original intact */
2751 raw_data = btf__get_raw_data(obj->btf, &sz);
2752 kern_btf = btf__new(raw_data, sz);
2753 err = libbpf_get_error(kern_btf);
2757 /* enforce 8-byte pointers for BPF-targeted BTFs */
2758 btf__set_pointer_size(obj->btf, 8);
2759 bpf_object__sanitize_btf(obj, kern_btf);
2762 if (obj->gen_loader) {
2764 const void *raw_data = btf__get_raw_data(kern_btf, &raw_size);
2768 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
2769 /* Pretend to have valid FD to pass various fd >= 0 checks.
2770 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
2772 btf__set_fd(kern_btf, 0);
2774 err = btf__load_into_kernel(kern_btf);
2778 /* move fd to libbpf's BTF */
2779 btf__set_fd(obj->btf, btf__fd(kern_btf));
2780 btf__set_fd(kern_btf, -1);
2782 btf__free(kern_btf);
2786 btf_mandatory = kernel_needs_btf(obj);
2787 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2788 btf_mandatory ? "BTF is mandatory, can't proceed."
2789 : "BTF is optional, ignoring.");
2796 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
2800 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
2802 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2803 off, obj->path, elf_errmsg(-1));
2810 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
2814 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
2816 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2817 off, obj->path, elf_errmsg(-1));
2824 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
2828 scn = elf_getscn(obj->efile.elf, idx);
2830 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
2831 idx, obj->path, elf_errmsg(-1));
2837 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
2839 Elf_Scn *scn = NULL;
2840 Elf *elf = obj->efile.elf;
2841 const char *sec_name;
2843 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2844 sec_name = elf_sec_name(obj, scn);
2848 if (strcmp(sec_name, name) != 0)
2856 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr)
2861 if (gelf_getshdr(scn, hdr) != hdr) {
2862 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
2863 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2870 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
2878 if (elf_sec_hdr(obj, scn, &sh))
2881 name = elf_sec_str(obj, sh.sh_name);
2883 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
2884 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2891 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
2898 data = elf_getdata(scn, 0);
2900 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
2901 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
2902 obj->path, elf_errmsg(-1));
2909 static bool is_sec_name_dwarf(const char *name)
2911 /* approximation, but the actual list is too long */
2912 return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
2915 static bool ignore_elf_section(GElf_Shdr *hdr, const char *name)
2917 /* no special handling of .strtab */
2918 if (hdr->sh_type == SHT_STRTAB)
2921 /* ignore .llvm_addrsig section as well */
2922 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
2925 /* no subprograms will lead to an empty .text section, ignore it */
2926 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
2927 strcmp(name, ".text") == 0)
2930 /* DWARF sections */
2931 if (is_sec_name_dwarf(name))
2934 if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
2935 name += sizeof(".rel") - 1;
2936 /* DWARF section relocations */
2937 if (is_sec_name_dwarf(name))
2940 /* .BTF and .BTF.ext don't need relocations */
2941 if (strcmp(name, BTF_ELF_SEC) == 0 ||
2942 strcmp(name, BTF_EXT_ELF_SEC) == 0)
2949 static int cmp_progs(const void *_a, const void *_b)
2951 const struct bpf_program *a = _a;
2952 const struct bpf_program *b = _b;
2954 if (a->sec_idx != b->sec_idx)
2955 return a->sec_idx < b->sec_idx ? -1 : 1;
2957 /* sec_insn_off can't be the same within the section */
2958 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
2961 static int bpf_object__elf_collect(struct bpf_object *obj)
2963 Elf *elf = obj->efile.elf;
2964 Elf_Data *btf_ext_data = NULL;
2965 Elf_Data *btf_data = NULL;
2966 int idx = 0, err = 0;
2972 /* a bunch of ELF parsing functionality depends on processing symbols,
2973 * so do the first pass and find the symbol table
2976 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2977 if (elf_sec_hdr(obj, scn, &sh))
2978 return -LIBBPF_ERRNO__FORMAT;
2980 if (sh.sh_type == SHT_SYMTAB) {
2981 if (obj->efile.symbols) {
2982 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
2983 return -LIBBPF_ERRNO__FORMAT;
2986 data = elf_sec_data(obj, scn);
2988 return -LIBBPF_ERRNO__FORMAT;
2990 obj->efile.symbols = data;
2991 obj->efile.symbols_shndx = elf_ndxscn(scn);
2992 obj->efile.strtabidx = sh.sh_link;
2997 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3000 if (elf_sec_hdr(obj, scn, &sh))
3001 return -LIBBPF_ERRNO__FORMAT;
3003 name = elf_sec_str(obj, sh.sh_name);
3005 return -LIBBPF_ERRNO__FORMAT;
3007 if (ignore_elf_section(&sh, name))
3010 data = elf_sec_data(obj, scn);
3012 return -LIBBPF_ERRNO__FORMAT;
3014 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3015 idx, name, (unsigned long)data->d_size,
3016 (int)sh.sh_link, (unsigned long)sh.sh_flags,
3019 if (strcmp(name, "license") == 0) {
3020 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3023 } else if (strcmp(name, "version") == 0) {
3024 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3027 } else if (strcmp(name, "maps") == 0) {
3028 obj->efile.maps_shndx = idx;
3029 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3030 obj->efile.btf_maps_shndx = idx;
3031 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3033 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3034 btf_ext_data = data;
3035 } else if (sh.sh_type == SHT_SYMTAB) {
3036 /* already processed during the first pass above */
3037 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
3038 if (sh.sh_flags & SHF_EXECINSTR) {
3039 if (strcmp(name, ".text") == 0)
3040 obj->efile.text_shndx = idx;
3041 err = bpf_object__add_programs(obj, data, name, idx);
3044 } else if (strcmp(name, DATA_SEC) == 0) {
3045 obj->efile.data = data;
3046 obj->efile.data_shndx = idx;
3047 } else if (strcmp(name, RODATA_SEC) == 0) {
3048 obj->efile.rodata = data;
3049 obj->efile.rodata_shndx = idx;
3050 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3051 obj->efile.st_ops_data = data;
3052 obj->efile.st_ops_shndx = idx;
3054 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3057 } else if (sh.sh_type == SHT_REL) {
3058 int nr_sects = obj->efile.nr_reloc_sects;
3059 void *sects = obj->efile.reloc_sects;
3060 int sec = sh.sh_info; /* points to other section */
3062 /* Only do relo for section with exec instructions */
3063 if (!section_have_execinstr(obj, sec) &&
3064 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3065 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3066 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3068 elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>");
3072 sects = libbpf_reallocarray(sects, nr_sects + 1,
3073 sizeof(*obj->efile.reloc_sects));
3077 obj->efile.reloc_sects = sects;
3078 obj->efile.nr_reloc_sects++;
3080 obj->efile.reloc_sects[nr_sects].shdr = sh;
3081 obj->efile.reloc_sects[nr_sects].data = data;
3082 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3083 obj->efile.bss = data;
3084 obj->efile.bss_shndx = idx;
3086 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3087 (size_t)sh.sh_size);
3091 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3092 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3093 return -LIBBPF_ERRNO__FORMAT;
3096 /* sort BPF programs by section name and in-section instruction offset
3097 * for faster search */
3098 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3100 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3103 static bool sym_is_extern(const GElf_Sym *sym)
3105 int bind = GELF_ST_BIND(sym->st_info);
3106 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3107 return sym->st_shndx == SHN_UNDEF &&
3108 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3109 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
3112 static bool sym_is_subprog(const GElf_Sym *sym, int text_shndx)
3114 int bind = GELF_ST_BIND(sym->st_info);
3115 int type = GELF_ST_TYPE(sym->st_info);
3117 /* in .text section */
3118 if (sym->st_shndx != text_shndx)
3121 /* local function */
3122 if (bind == STB_LOCAL && type == STT_SECTION)
3125 /* global function */
3126 return bind == STB_GLOBAL && type == STT_FUNC;
3129 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3131 const struct btf_type *t;
3138 n = btf__get_nr_types(btf);
3139 for (i = 1; i <= n; i++) {
3140 t = btf__type_by_id(btf, i);
3142 if (!btf_is_var(t) && !btf_is_func(t))
3145 tname = btf__name_by_offset(btf, t->name_off);
3146 if (strcmp(tname, ext_name))
3149 if (btf_is_var(t) &&
3150 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3153 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3162 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3163 const struct btf_var_secinfo *vs;
3164 const struct btf_type *t;
3170 n = btf__get_nr_types(btf);
3171 for (i = 1; i <= n; i++) {
3172 t = btf__type_by_id(btf, i);
3174 if (!btf_is_datasec(t))
3177 vs = btf_var_secinfos(t);
3178 for (j = 0; j < btf_vlen(t); j++, vs++) {
3179 if (vs->type == ext_btf_id)
3187 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3190 const struct btf_type *t;
3193 t = skip_mods_and_typedefs(btf, id, NULL);
3194 name = btf__name_by_offset(btf, t->name_off);
3198 switch (btf_kind(t)) {
3199 case BTF_KIND_INT: {
3200 int enc = btf_int_encoding(t);
3202 if (enc & BTF_INT_BOOL)
3203 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3205 *is_signed = enc & BTF_INT_SIGNED;
3208 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3209 return KCFG_UNKNOWN;
3214 return KCFG_UNKNOWN;
3215 if (strcmp(name, "libbpf_tristate"))
3216 return KCFG_UNKNOWN;
3217 return KCFG_TRISTATE;
3218 case BTF_KIND_ARRAY:
3219 if (btf_array(t)->nelems == 0)
3220 return KCFG_UNKNOWN;
3221 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3222 return KCFG_UNKNOWN;
3223 return KCFG_CHAR_ARR;
3225 return KCFG_UNKNOWN;
3229 static int cmp_externs(const void *_a, const void *_b)
3231 const struct extern_desc *a = _a;
3232 const struct extern_desc *b = _b;
3234 if (a->type != b->type)
3235 return a->type < b->type ? -1 : 1;
3237 if (a->type == EXT_KCFG) {
3238 /* descending order by alignment requirements */
3239 if (a->kcfg.align != b->kcfg.align)
3240 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3241 /* ascending order by size, within same alignment class */
3242 if (a->kcfg.sz != b->kcfg.sz)
3243 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3246 /* resolve ties by name */
3247 return strcmp(a->name, b->name);
3250 static int find_int_btf_id(const struct btf *btf)
3252 const struct btf_type *t;
3255 n = btf__get_nr_types(btf);
3256 for (i = 1; i <= n; i++) {
3257 t = btf__type_by_id(btf, i);
3259 if (btf_is_int(t) && btf_int_bits(t) == 32)
3266 static int add_dummy_ksym_var(struct btf *btf)
3268 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3269 const struct btf_var_secinfo *vs;
3270 const struct btf_type *sec;
3275 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3280 sec = btf__type_by_id(btf, sec_btf_id);
3281 vs = btf_var_secinfos(sec);
3282 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3283 const struct btf_type *vt;
3285 vt = btf__type_by_id(btf, vs->type);
3286 if (btf_is_func(vt))
3290 /* No func in ksyms sec. No need to add dummy var. */
3291 if (i == btf_vlen(sec))
3294 int_btf_id = find_int_btf_id(btf);
3295 dummy_var_btf_id = btf__add_var(btf,
3297 BTF_VAR_GLOBAL_ALLOCATED,
3299 if (dummy_var_btf_id < 0)
3300 pr_warn("cannot create a dummy_ksym var\n");
3302 return dummy_var_btf_id;
3305 static int bpf_object__collect_externs(struct bpf_object *obj)
3307 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3308 const struct btf_type *t;
3309 struct extern_desc *ext;
3310 int i, n, off, dummy_var_btf_id;
3311 const char *ext_name, *sec_name;
3315 if (!obj->efile.symbols)
3318 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3319 if (elf_sec_hdr(obj, scn, &sh))
3320 return -LIBBPF_ERRNO__FORMAT;
3322 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3323 if (dummy_var_btf_id < 0)
3324 return dummy_var_btf_id;
3326 n = sh.sh_size / sh.sh_entsize;
3327 pr_debug("looking for externs among %d symbols...\n", n);
3329 for (i = 0; i < n; i++) {
3332 if (!gelf_getsym(obj->efile.symbols, i, &sym))
3333 return -LIBBPF_ERRNO__FORMAT;
3334 if (!sym_is_extern(&sym))
3336 ext_name = elf_sym_str(obj, sym.st_name);
3337 if (!ext_name || !ext_name[0])
3341 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3345 ext = &ext[obj->nr_extern];
3346 memset(ext, 0, sizeof(*ext));
3349 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3350 if (ext->btf_id <= 0) {
3351 pr_warn("failed to find BTF for extern '%s': %d\n",
3352 ext_name, ext->btf_id);
3355 t = btf__type_by_id(obj->btf, ext->btf_id);
3356 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3358 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
3360 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3361 if (ext->sec_btf_id <= 0) {
3362 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3363 ext_name, ext->btf_id, ext->sec_btf_id);
3364 return ext->sec_btf_id;
3366 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3367 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3369 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3370 if (btf_is_func(t)) {
3371 pr_warn("extern function %s is unsupported under %s section\n",
3372 ext->name, KCONFIG_SEC);
3376 ext->type = EXT_KCFG;
3377 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3378 if (ext->kcfg.sz <= 0) {
3379 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3380 ext_name, ext->kcfg.sz);
3381 return ext->kcfg.sz;
3383 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3384 if (ext->kcfg.align <= 0) {
3385 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3386 ext_name, ext->kcfg.align);
3389 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3390 &ext->kcfg.is_signed);
3391 if (ext->kcfg.type == KCFG_UNKNOWN) {
3392 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3395 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3396 if (btf_is_func(t) && ext->is_weak) {
3397 pr_warn("extern weak function %s is unsupported\n",
3402 ext->type = EXT_KSYM;
3403 skip_mods_and_typedefs(obj->btf, t->type,
3404 &ext->ksym.type_id);
3406 pr_warn("unrecognized extern section '%s'\n", sec_name);
3410 pr_debug("collected %d externs total\n", obj->nr_extern);
3412 if (!obj->nr_extern)
3415 /* sort externs by type, for kcfg ones also by (align, size, name) */
3416 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3418 /* for .ksyms section, we need to turn all externs into allocated
3419 * variables in BTF to pass kernel verification; we do this by
3420 * pretending that each extern is a 8-byte variable
3423 /* find existing 4-byte integer type in BTF to use for fake
3424 * extern variables in DATASEC
3426 int int_btf_id = find_int_btf_id(obj->btf);
3427 /* For extern function, a dummy_var added earlier
3428 * will be used to replace the vs->type and
3429 * its name string will be used to refill
3430 * the missing param's name.
3432 const struct btf_type *dummy_var;
3434 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3435 for (i = 0; i < obj->nr_extern; i++) {
3436 ext = &obj->externs[i];
3437 if (ext->type != EXT_KSYM)
3439 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3440 i, ext->sym_idx, ext->name);
3445 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3446 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3447 struct btf_type *vt;
3449 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3450 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3451 ext = find_extern_by_name(obj, ext_name);
3453 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3454 btf_kind_str(vt), ext_name);
3457 if (btf_is_func(vt)) {
3458 const struct btf_type *func_proto;
3459 struct btf_param *param;
3462 func_proto = btf__type_by_id(obj->btf,
3464 param = btf_params(func_proto);
3465 /* Reuse the dummy_var string if the
3466 * func proto does not have param name.
3468 for (j = 0; j < btf_vlen(func_proto); j++)
3469 if (param[j].type && !param[j].name_off)
3471 dummy_var->name_off;
3472 vs->type = dummy_var_btf_id;
3473 vt->info &= ~0xffff;
3474 vt->info |= BTF_FUNC_GLOBAL;
3476 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3477 vt->type = int_btf_id;
3480 vs->size = sizeof(int);
3487 /* for kcfg externs calculate their offsets within a .kconfig map */
3489 for (i = 0; i < obj->nr_extern; i++) {
3490 ext = &obj->externs[i];
3491 if (ext->type != EXT_KCFG)
3494 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3495 off = ext->kcfg.data_off + ext->kcfg.sz;
3496 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3497 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3501 for (i = 0; i < n; i++) {
3502 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3504 t = btf__type_by_id(obj->btf, vs->type);
3505 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3506 ext = find_extern_by_name(obj, ext_name);
3508 pr_warn("failed to find extern definition for BTF var '%s'\n",
3512 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3513 vs->offset = ext->kcfg.data_off;
3519 struct bpf_program *
3520 bpf_object__find_program_by_title(const struct bpf_object *obj,
3523 struct bpf_program *pos;
3525 bpf_object__for_each_program(pos, obj) {
3526 if (pos->sec_name && !strcmp(pos->sec_name, title))
3529 return errno = ENOENT, NULL;
3532 static bool prog_is_subprog(const struct bpf_object *obj,
3533 const struct bpf_program *prog)
3535 /* For legacy reasons, libbpf supports an entry-point BPF programs
3536 * without SEC() attribute, i.e., those in the .text section. But if
3537 * there are 2 or more such programs in the .text section, they all
3538 * must be subprograms called from entry-point BPF programs in
3539 * designated SEC()'tions, otherwise there is no way to distinguish
3540 * which of those programs should be loaded vs which are a subprogram.
3541 * Similarly, if there is a function/program in .text and at least one
3542 * other BPF program with custom SEC() attribute, then we just assume
3543 * .text programs are subprograms (even if they are not called from
3544 * other programs), because libbpf never explicitly supported mixing
3545 * SEC()-designated BPF programs and .text entry-point BPF programs.
3547 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3550 struct bpf_program *
3551 bpf_object__find_program_by_name(const struct bpf_object *obj,
3554 struct bpf_program *prog;
3556 bpf_object__for_each_program(prog, obj) {
3557 if (prog_is_subprog(obj, prog))
3559 if (!strcmp(prog->name, name))
3562 return errno = ENOENT, NULL;
3565 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3568 return shndx == obj->efile.data_shndx ||
3569 shndx == obj->efile.bss_shndx ||
3570 shndx == obj->efile.rodata_shndx;
3573 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3576 return shndx == obj->efile.maps_shndx ||
3577 shndx == obj->efile.btf_maps_shndx;
3580 static enum libbpf_map_type
3581 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3583 if (shndx == obj->efile.data_shndx)
3584 return LIBBPF_MAP_DATA;
3585 else if (shndx == obj->efile.bss_shndx)
3586 return LIBBPF_MAP_BSS;
3587 else if (shndx == obj->efile.rodata_shndx)
3588 return LIBBPF_MAP_RODATA;
3589 else if (shndx == obj->efile.symbols_shndx)
3590 return LIBBPF_MAP_KCONFIG;
3592 return LIBBPF_MAP_UNSPEC;
3595 static int bpf_program__record_reloc(struct bpf_program *prog,
3596 struct reloc_desc *reloc_desc,
3597 __u32 insn_idx, const char *sym_name,
3598 const GElf_Sym *sym, const GElf_Rel *rel)
3600 struct bpf_insn *insn = &prog->insns[insn_idx];
3601 size_t map_idx, nr_maps = prog->obj->nr_maps;
3602 struct bpf_object *obj = prog->obj;
3603 __u32 shdr_idx = sym->st_shndx;
3604 enum libbpf_map_type type;
3605 const char *sym_sec_name;
3606 struct bpf_map *map;
3608 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3609 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3610 prog->name, sym_name, insn_idx, insn->code);
3611 return -LIBBPF_ERRNO__RELOC;
3614 if (sym_is_extern(sym)) {
3615 int sym_idx = GELF_R_SYM(rel->r_info);
3616 int i, n = obj->nr_extern;
3617 struct extern_desc *ext;
3619 for (i = 0; i < n; i++) {
3620 ext = &obj->externs[i];
3621 if (ext->sym_idx == sym_idx)
3625 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3626 prog->name, sym_name, sym_idx);
3627 return -LIBBPF_ERRNO__RELOC;
3629 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3630 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3631 if (insn->code == (BPF_JMP | BPF_CALL))
3632 reloc_desc->type = RELO_EXTERN_FUNC;
3634 reloc_desc->type = RELO_EXTERN_VAR;
3635 reloc_desc->insn_idx = insn_idx;
3636 reloc_desc->sym_off = i; /* sym_off stores extern index */
3640 /* sub-program call relocation */
3641 if (is_call_insn(insn)) {
3642 if (insn->src_reg != BPF_PSEUDO_CALL) {
3643 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3644 return -LIBBPF_ERRNO__RELOC;
3646 /* text_shndx can be 0, if no default "main" program exists */
3647 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3648 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3649 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3650 prog->name, sym_name, sym_sec_name);
3651 return -LIBBPF_ERRNO__RELOC;
3653 if (sym->st_value % BPF_INSN_SZ) {
3654 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3655 prog->name, sym_name, (size_t)sym->st_value);
3656 return -LIBBPF_ERRNO__RELOC;
3658 reloc_desc->type = RELO_CALL;
3659 reloc_desc->insn_idx = insn_idx;
3660 reloc_desc->sym_off = sym->st_value;
3664 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3665 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3666 prog->name, sym_name, shdr_idx);
3667 return -LIBBPF_ERRNO__RELOC;
3670 /* loading subprog addresses */
3671 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3672 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3673 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3675 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3676 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3677 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3678 return -LIBBPF_ERRNO__RELOC;
3681 reloc_desc->type = RELO_SUBPROG_ADDR;
3682 reloc_desc->insn_idx = insn_idx;
3683 reloc_desc->sym_off = sym->st_value;
3687 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3688 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3690 /* generic map reference relocation */
3691 if (type == LIBBPF_MAP_UNSPEC) {
3692 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3693 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3694 prog->name, sym_name, sym_sec_name);
3695 return -LIBBPF_ERRNO__RELOC;
3697 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3698 map = &obj->maps[map_idx];
3699 if (map->libbpf_type != type ||
3700 map->sec_idx != sym->st_shndx ||
3701 map->sec_offset != sym->st_value)
3703 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
3704 prog->name, map_idx, map->name, map->sec_idx,
3705 map->sec_offset, insn_idx);
3708 if (map_idx >= nr_maps) {
3709 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
3710 prog->name, sym_sec_name, (size_t)sym->st_value);
3711 return -LIBBPF_ERRNO__RELOC;
3713 reloc_desc->type = RELO_LD64;
3714 reloc_desc->insn_idx = insn_idx;
3715 reloc_desc->map_idx = map_idx;
3716 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3720 /* global data map relocation */
3721 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3722 pr_warn("prog '%s': bad data relo against section '%s'\n",
3723 prog->name, sym_sec_name);
3724 return -LIBBPF_ERRNO__RELOC;
3726 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3727 map = &obj->maps[map_idx];
3728 if (map->libbpf_type != type)
3730 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3731 prog->name, map_idx, map->name, map->sec_idx,
3732 map->sec_offset, insn_idx);
3735 if (map_idx >= nr_maps) {
3736 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
3737 prog->name, sym_sec_name);
3738 return -LIBBPF_ERRNO__RELOC;
3741 reloc_desc->type = RELO_DATA;
3742 reloc_desc->insn_idx = insn_idx;
3743 reloc_desc->map_idx = map_idx;
3744 reloc_desc->sym_off = sym->st_value;
3748 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
3750 return insn_idx >= prog->sec_insn_off &&
3751 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
3754 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
3755 size_t sec_idx, size_t insn_idx)
3757 int l = 0, r = obj->nr_programs - 1, m;
3758 struct bpf_program *prog;
3761 m = l + (r - l + 1) / 2;
3762 prog = &obj->programs[m];
3764 if (prog->sec_idx < sec_idx ||
3765 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
3770 /* matching program could be at index l, but it still might be the
3771 * wrong one, so we need to double check conditions for the last time
3773 prog = &obj->programs[l];
3774 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
3780 bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data)
3782 Elf_Data *symbols = obj->efile.symbols;
3783 const char *relo_sec_name, *sec_name;
3784 size_t sec_idx = shdr->sh_info;
3785 struct bpf_program *prog;
3786 struct reloc_desc *relos;
3788 const char *sym_name;
3795 scn = elf_sec_by_idx(obj, sec_idx);
3796 scn_data = elf_sec_data(obj, scn);
3798 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
3799 sec_name = elf_sec_name(obj, scn);
3800 if (!relo_sec_name || !sec_name)
3803 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
3804 relo_sec_name, sec_idx, sec_name);
3805 nrels = shdr->sh_size / shdr->sh_entsize;
3807 for (i = 0; i < nrels; i++) {
3808 if (!gelf_getrel(data, i, &rel)) {
3809 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
3810 return -LIBBPF_ERRNO__FORMAT;
3812 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3813 pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n",
3814 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3815 return -LIBBPF_ERRNO__FORMAT;
3818 if (rel.r_offset % BPF_INSN_SZ || rel.r_offset >= scn_data->d_size) {
3819 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
3820 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3821 return -LIBBPF_ERRNO__FORMAT;
3824 insn_idx = rel.r_offset / BPF_INSN_SZ;
3825 /* relocations against static functions are recorded as
3826 * relocations against the section that contains a function;
3827 * in such case, symbol will be STT_SECTION and sym.st_name
3828 * will point to empty string (0), so fetch section name
3831 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0)
3832 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx));
3834 sym_name = elf_sym_str(obj, sym.st_name);
3835 sym_name = sym_name ?: "<?";
3837 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
3838 relo_sec_name, i, insn_idx, sym_name);
3840 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
3842 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
3843 relo_sec_name, i, sec_name, insn_idx);
3847 relos = libbpf_reallocarray(prog->reloc_desc,
3848 prog->nr_reloc + 1, sizeof(*relos));
3851 prog->reloc_desc = relos;
3853 /* adjust insn_idx to local BPF program frame of reference */
3854 insn_idx -= prog->sec_insn_off;
3855 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
3856 insn_idx, sym_name, &sym, &rel);
3865 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3867 struct bpf_map_def *def = &map->def;
3868 __u32 key_type_id = 0, value_type_id = 0;
3871 /* if it's BTF-defined map, we don't need to search for type IDs.
3872 * For struct_ops map, it does not need btf_key_type_id and
3873 * btf_value_type_id.
3875 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3876 bpf_map__is_struct_ops(map))
3879 if (!bpf_map__is_internal(map)) {
3880 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3881 def->value_size, &key_type_id,
3885 * LLVM annotates global data differently in BTF, that is,
3886 * only as '.data', '.bss' or '.rodata'.
3888 ret = btf__find_by_name(obj->btf,
3889 libbpf_type_to_btf_name[map->libbpf_type]);
3894 map->btf_key_type_id = key_type_id;
3895 map->btf_value_type_id = bpf_map__is_internal(map) ?
3896 ret : value_type_id;
3900 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
3902 char file[PATH_MAX], buff[4096];
3907 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
3908 memset(info, 0, sizeof(*info));
3910 fp = fopen(file, "r");
3913 pr_warn("failed to open %s: %d. No procfs support?\n", file,
3918 while (fgets(buff, sizeof(buff), fp)) {
3919 if (sscanf(buff, "map_type:\t%u", &val) == 1)
3921 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
3922 info->key_size = val;
3923 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
3924 info->value_size = val;
3925 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
3926 info->max_entries = val;
3927 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
3928 info->map_flags = val;
3936 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3938 struct bpf_map_info info = {};
3939 __u32 len = sizeof(info);
3943 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3944 if (err && errno == EINVAL)
3945 err = bpf_get_map_info_from_fdinfo(fd, &info);
3947 return libbpf_err(err);
3949 new_name = strdup(info.name);
3951 return libbpf_err(-errno);
3953 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3956 goto err_free_new_name;
3959 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3962 goto err_close_new_fd;
3965 err = zclose(map->fd);
3968 goto err_close_new_fd;
3973 map->name = new_name;
3974 map->def.type = info.type;
3975 map->def.key_size = info.key_size;
3976 map->def.value_size = info.value_size;
3977 map->def.max_entries = info.max_entries;
3978 map->def.map_flags = info.map_flags;
3979 map->btf_key_type_id = info.btf_key_type_id;
3980 map->btf_value_type_id = info.btf_value_type_id;
3989 return libbpf_err(err);
3992 __u32 bpf_map__max_entries(const struct bpf_map *map)
3994 return map->def.max_entries;
3997 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
3999 if (!bpf_map_type__is_map_in_map(map->def.type))
4000 return errno = EINVAL, NULL;
4002 return map->inner_map;
4005 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4008 return libbpf_err(-EBUSY);
4009 map->def.max_entries = max_entries;
4013 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4015 if (!map || !max_entries)
4016 return libbpf_err(-EINVAL);
4018 return bpf_map__set_max_entries(map, max_entries);
4022 bpf_object__probe_loading(struct bpf_object *obj)
4024 struct bpf_load_program_attr attr;
4025 char *cp, errmsg[STRERR_BUFSIZE];
4026 struct bpf_insn insns[] = {
4027 BPF_MOV64_IMM(BPF_REG_0, 0),
4032 if (obj->gen_loader)
4035 /* make sure basic loading works */
4037 memset(&attr, 0, sizeof(attr));
4038 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4040 attr.insns_cnt = ARRAY_SIZE(insns);
4041 attr.license = "GPL";
4043 ret = bpf_load_program_xattr(&attr, NULL, 0);
4045 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4046 ret = bpf_load_program_xattr(&attr, NULL, 0);
4050 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4051 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4052 "program. Make sure your kernel supports BPF "
4053 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4054 "set to big enough value.\n", __func__, cp, ret);
4062 static int probe_fd(int fd)
4069 static int probe_kern_prog_name(void)
4071 struct bpf_load_program_attr attr;
4072 struct bpf_insn insns[] = {
4073 BPF_MOV64_IMM(BPF_REG_0, 0),
4078 /* make sure loading with name works */
4080 memset(&attr, 0, sizeof(attr));
4081 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4083 attr.insns_cnt = ARRAY_SIZE(insns);
4084 attr.license = "GPL";
4086 ret = bpf_load_program_xattr(&attr, NULL, 0);
4087 return probe_fd(ret);
4090 static int probe_kern_global_data(void)
4092 struct bpf_load_program_attr prg_attr;
4093 struct bpf_create_map_attr map_attr;
4094 char *cp, errmsg[STRERR_BUFSIZE];
4095 struct bpf_insn insns[] = {
4096 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4097 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4098 BPF_MOV64_IMM(BPF_REG_0, 0),
4103 memset(&map_attr, 0, sizeof(map_attr));
4104 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4105 map_attr.key_size = sizeof(int);
4106 map_attr.value_size = 32;
4107 map_attr.max_entries = 1;
4109 map = bpf_create_map_xattr(&map_attr);
4112 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4113 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4114 __func__, cp, -ret);
4120 memset(&prg_attr, 0, sizeof(prg_attr));
4121 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4122 prg_attr.insns = insns;
4123 prg_attr.insns_cnt = ARRAY_SIZE(insns);
4124 prg_attr.license = "GPL";
4126 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
4128 return probe_fd(ret);
4131 static int probe_kern_btf(void)
4133 static const char strs[] = "\0int";
4136 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4139 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4140 strs, sizeof(strs)));
4143 static int probe_kern_btf_func(void)
4145 static const char strs[] = "\0int\0x\0a";
4146 /* void x(int a) {} */
4149 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4150 /* FUNC_PROTO */ /* [2] */
4151 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4152 BTF_PARAM_ENC(7, 1),
4153 /* FUNC x */ /* [3] */
4154 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4157 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4158 strs, sizeof(strs)));
4161 static int probe_kern_btf_func_global(void)
4163 static const char strs[] = "\0int\0x\0a";
4164 /* static void x(int a) {} */
4167 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4168 /* FUNC_PROTO */ /* [2] */
4169 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4170 BTF_PARAM_ENC(7, 1),
4171 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4172 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4175 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4176 strs, sizeof(strs)));
4179 static int probe_kern_btf_datasec(void)
4181 static const char strs[] = "\0x\0.data";
4185 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4186 /* VAR x */ /* [2] */
4187 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4189 /* DATASEC val */ /* [3] */
4190 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4191 BTF_VAR_SECINFO_ENC(2, 0, 4),
4194 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4195 strs, sizeof(strs)));
4198 static int probe_kern_btf_float(void)
4200 static const char strs[] = "\0float";
4203 BTF_TYPE_FLOAT_ENC(1, 4),
4206 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4207 strs, sizeof(strs)));
4210 static int probe_kern_array_mmap(void)
4212 struct bpf_create_map_attr attr = {
4213 .map_type = BPF_MAP_TYPE_ARRAY,
4214 .map_flags = BPF_F_MMAPABLE,
4215 .key_size = sizeof(int),
4216 .value_size = sizeof(int),
4220 return probe_fd(bpf_create_map_xattr(&attr));
4223 static int probe_kern_exp_attach_type(void)
4225 struct bpf_load_program_attr attr;
4226 struct bpf_insn insns[] = {
4227 BPF_MOV64_IMM(BPF_REG_0, 0),
4231 memset(&attr, 0, sizeof(attr));
4232 /* use any valid combination of program type and (optional)
4233 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4234 * to see if kernel supports expected_attach_type field for
4235 * BPF_PROG_LOAD command
4237 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
4238 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
4240 attr.insns_cnt = ARRAY_SIZE(insns);
4241 attr.license = "GPL";
4243 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4246 static int probe_kern_probe_read_kernel(void)
4248 struct bpf_load_program_attr attr;
4249 struct bpf_insn insns[] = {
4250 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4251 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4252 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4253 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4254 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4258 memset(&attr, 0, sizeof(attr));
4259 attr.prog_type = BPF_PROG_TYPE_KPROBE;
4261 attr.insns_cnt = ARRAY_SIZE(insns);
4262 attr.license = "GPL";
4264 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4267 static int probe_prog_bind_map(void)
4269 struct bpf_load_program_attr prg_attr;
4270 struct bpf_create_map_attr map_attr;
4271 char *cp, errmsg[STRERR_BUFSIZE];
4272 struct bpf_insn insns[] = {
4273 BPF_MOV64_IMM(BPF_REG_0, 0),
4278 memset(&map_attr, 0, sizeof(map_attr));
4279 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4280 map_attr.key_size = sizeof(int);
4281 map_attr.value_size = 32;
4282 map_attr.max_entries = 1;
4284 map = bpf_create_map_xattr(&map_attr);
4287 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4288 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4289 __func__, cp, -ret);
4293 memset(&prg_attr, 0, sizeof(prg_attr));
4294 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4295 prg_attr.insns = insns;
4296 prg_attr.insns_cnt = ARRAY_SIZE(insns);
4297 prg_attr.license = "GPL";
4299 prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
4305 ret = bpf_prog_bind_map(prog, map, NULL);
4313 static int probe_module_btf(void)
4315 static const char strs[] = "\0int";
4318 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4320 struct bpf_btf_info info;
4321 __u32 len = sizeof(info);
4325 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4327 return 0; /* BTF not supported at all */
4329 memset(&info, 0, sizeof(info));
4330 info.name = ptr_to_u64(name);
4331 info.name_len = sizeof(name);
4333 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4334 * kernel's module BTF support coincides with support for
4335 * name/name_len fields in struct bpf_btf_info.
4337 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4342 static int probe_perf_link(void)
4344 struct bpf_load_program_attr attr;
4345 struct bpf_insn insns[] = {
4346 BPF_MOV64_IMM(BPF_REG_0, 0),
4349 int prog_fd, link_fd, err;
4351 memset(&attr, 0, sizeof(attr));
4352 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4354 attr.insns_cnt = ARRAY_SIZE(insns);
4355 attr.license = "GPL";
4356 prog_fd = bpf_load_program_xattr(&attr, NULL, 0);
4360 /* use invalid perf_event FD to get EBADF, if link is supported;
4361 * otherwise EINVAL should be returned
4363 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4364 err = -errno; /* close() can clobber errno */
4370 return link_fd < 0 && err == -EBADF;
4373 enum kern_feature_result {
4379 typedef int (*feature_probe_fn)(void);
4381 static struct kern_feature_desc {
4383 feature_probe_fn probe;
4384 enum kern_feature_result res;
4385 } feature_probes[__FEAT_CNT] = {
4386 [FEAT_PROG_NAME] = {
4387 "BPF program name", probe_kern_prog_name,
4389 [FEAT_GLOBAL_DATA] = {
4390 "global variables", probe_kern_global_data,
4393 "minimal BTF", probe_kern_btf,
4396 "BTF functions", probe_kern_btf_func,
4398 [FEAT_BTF_GLOBAL_FUNC] = {
4399 "BTF global function", probe_kern_btf_func_global,
4401 [FEAT_BTF_DATASEC] = {
4402 "BTF data section and variable", probe_kern_btf_datasec,
4404 [FEAT_ARRAY_MMAP] = {
4405 "ARRAY map mmap()", probe_kern_array_mmap,
4407 [FEAT_EXP_ATTACH_TYPE] = {
4408 "BPF_PROG_LOAD expected_attach_type attribute",
4409 probe_kern_exp_attach_type,
4411 [FEAT_PROBE_READ_KERN] = {
4412 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4414 [FEAT_PROG_BIND_MAP] = {
4415 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4417 [FEAT_MODULE_BTF] = {
4418 "module BTF support", probe_module_btf,
4420 [FEAT_BTF_FLOAT] = {
4421 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4423 [FEAT_PERF_LINK] = {
4424 "BPF perf link support", probe_perf_link,
4428 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4430 struct kern_feature_desc *feat = &feature_probes[feat_id];
4433 if (obj->gen_loader)
4434 /* To generate loader program assume the latest kernel
4435 * to avoid doing extra prog_load, map_create syscalls.
4439 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4440 ret = feat->probe();
4442 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4443 } else if (ret == 0) {
4444 WRITE_ONCE(feat->res, FEAT_MISSING);
4446 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4447 WRITE_ONCE(feat->res, FEAT_MISSING);
4451 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4454 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4456 struct bpf_map_info map_info = {};
4457 char msg[STRERR_BUFSIZE];
4461 map_info_len = sizeof(map_info);
4463 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4464 if (err && errno == EINVAL)
4465 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4467 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4468 libbpf_strerror_r(errno, msg, sizeof(msg)));
4472 return (map_info.type == map->def.type &&
4473 map_info.key_size == map->def.key_size &&
4474 map_info.value_size == map->def.value_size &&
4475 map_info.max_entries == map->def.max_entries &&
4476 map_info.map_flags == map->def.map_flags);
4480 bpf_object__reuse_map(struct bpf_map *map)
4482 char *cp, errmsg[STRERR_BUFSIZE];
4485 pin_fd = bpf_obj_get(map->pin_path);
4488 if (err == -ENOENT) {
4489 pr_debug("found no pinned map to reuse at '%s'\n",
4494 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4495 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4500 if (!map_is_reuse_compat(map, pin_fd)) {
4501 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4507 err = bpf_map__reuse_fd(map, pin_fd);
4513 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4519 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4521 enum libbpf_map_type map_type = map->libbpf_type;
4522 char *cp, errmsg[STRERR_BUFSIZE];
4525 if (obj->gen_loader) {
4526 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4527 map->mmaped, map->def.value_size);
4528 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4529 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4532 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4535 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4536 pr_warn("Error setting initial map(%s) contents: %s\n",
4541 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4542 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4543 err = bpf_map_freeze(map->fd);
4546 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4547 pr_warn("Error freezing map(%s) as read-only: %s\n",
4555 static void bpf_map__destroy(struct bpf_map *map);
4557 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4559 struct bpf_create_map_attr create_attr;
4560 struct bpf_map_def *def = &map->def;
4563 memset(&create_attr, 0, sizeof(create_attr));
4565 if (kernel_supports(obj, FEAT_PROG_NAME))
4566 create_attr.name = map->name;
4567 create_attr.map_ifindex = map->map_ifindex;
4568 create_attr.map_type = def->type;
4569 create_attr.map_flags = def->map_flags;
4570 create_attr.key_size = def->key_size;
4571 create_attr.value_size = def->value_size;
4572 create_attr.numa_node = map->numa_node;
4574 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4577 nr_cpus = libbpf_num_possible_cpus();
4579 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4580 map->name, nr_cpus);
4583 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4584 create_attr.max_entries = nr_cpus;
4586 create_attr.max_entries = def->max_entries;
4589 if (bpf_map__is_struct_ops(map))
4590 create_attr.btf_vmlinux_value_type_id =
4591 map->btf_vmlinux_value_type_id;
4593 create_attr.btf_fd = 0;
4594 create_attr.btf_key_type_id = 0;
4595 create_attr.btf_value_type_id = 0;
4596 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4597 create_attr.btf_fd = btf__fd(obj->btf);
4598 create_attr.btf_key_type_id = map->btf_key_type_id;
4599 create_attr.btf_value_type_id = map->btf_value_type_id;
4602 if (bpf_map_type__is_map_in_map(def->type)) {
4603 if (map->inner_map) {
4604 err = bpf_object__create_map(obj, map->inner_map, true);
4606 pr_warn("map '%s': failed to create inner map: %d\n",
4610 map->inner_map_fd = bpf_map__fd(map->inner_map);
4612 if (map->inner_map_fd >= 0)
4613 create_attr.inner_map_fd = map->inner_map_fd;
4616 if (obj->gen_loader) {
4617 bpf_gen__map_create(obj->gen_loader, &create_attr, is_inner ? -1 : map - obj->maps);
4618 /* Pretend to have valid FD to pass various fd >= 0 checks.
4619 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4623 map->fd = bpf_create_map_xattr(&create_attr);
4625 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4626 create_attr.btf_value_type_id)) {
4627 char *cp, errmsg[STRERR_BUFSIZE];
4630 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4631 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4632 map->name, cp, err);
4633 create_attr.btf_fd = 0;
4634 create_attr.btf_key_type_id = 0;
4635 create_attr.btf_value_type_id = 0;
4636 map->btf_key_type_id = 0;
4637 map->btf_value_type_id = 0;
4638 map->fd = bpf_create_map_xattr(&create_attr);
4641 err = map->fd < 0 ? -errno : 0;
4643 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4644 if (obj->gen_loader)
4645 map->inner_map->fd = -1;
4646 bpf_map__destroy(map->inner_map);
4647 zfree(&map->inner_map);
4653 static int init_map_slots(struct bpf_object *obj, struct bpf_map *map)
4655 const struct bpf_map *targ_map;
4659 for (i = 0; i < map->init_slots_sz; i++) {
4660 if (!map->init_slots[i])
4663 targ_map = map->init_slots[i];
4664 fd = bpf_map__fd(targ_map);
4665 if (obj->gen_loader) {
4666 pr_warn("// TODO map_update_elem: idx %td key %d value==map_idx %td\n",
4667 map - obj->maps, i, targ_map - obj->maps);
4670 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4674 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4675 map->name, i, targ_map->name,
4679 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4680 map->name, i, targ_map->name, fd);
4683 zfree(&map->init_slots);
4684 map->init_slots_sz = 0;
4690 bpf_object__create_maps(struct bpf_object *obj)
4692 struct bpf_map *map;
4693 char *cp, errmsg[STRERR_BUFSIZE];
4698 for (i = 0; i < obj->nr_maps; i++) {
4699 map = &obj->maps[i];
4703 if (map->pin_path) {
4704 err = bpf_object__reuse_map(map);
4706 pr_warn("map '%s': error reusing pinned map\n",
4710 if (retried && map->fd < 0) {
4711 pr_warn("map '%s': cannot find pinned map\n",
4719 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
4720 map->name, map->fd);
4722 err = bpf_object__create_map(obj, map, false);
4726 pr_debug("map '%s': created successfully, fd=%d\n",
4727 map->name, map->fd);
4729 if (bpf_map__is_internal(map)) {
4730 err = bpf_object__populate_internal_map(obj, map);
4737 if (map->init_slots_sz) {
4738 err = init_map_slots(obj, map);
4746 if (map->pin_path && !map->pinned) {
4747 err = bpf_map__pin(map, NULL);
4750 if (!retried && err == -EEXIST) {
4754 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
4755 map->name, map->pin_path, err);
4764 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4765 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
4767 for (j = 0; j < i; j++)
4768 zclose(obj->maps[j].fd);
4772 static bool bpf_core_is_flavor_sep(const char *s)
4774 /* check X___Y name pattern, where X and Y are not underscores */
4775 return s[0] != '_' && /* X */
4776 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4777 s[4] != '_'; /* Y */
4780 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4781 * before last triple underscore. Struct name part after last triple
4782 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4784 size_t bpf_core_essential_name_len(const char *name)
4786 size_t n = strlen(name);
4789 for (i = n - 5; i >= 0; i--) {
4790 if (bpf_core_is_flavor_sep(name + i))
4796 static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
4802 static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
4803 size_t local_essent_len,
4804 const struct btf *targ_btf,
4805 const char *targ_btf_name,
4807 struct bpf_core_cand_list *cands)
4809 struct bpf_core_cand *new_cands, *cand;
4810 const struct btf_type *t;
4811 const char *targ_name;
4812 size_t targ_essent_len;
4815 n = btf__get_nr_types(targ_btf);
4816 for (i = targ_start_id; i <= n; i++) {
4817 t = btf__type_by_id(targ_btf, i);
4818 if (btf_kind(t) != btf_kind(local_cand->t))
4821 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4822 if (str_is_empty(targ_name))
4825 targ_essent_len = bpf_core_essential_name_len(targ_name);
4826 if (targ_essent_len != local_essent_len)
4829 if (strncmp(local_cand->name, targ_name, local_essent_len) != 0)
4832 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
4833 local_cand->id, btf_kind_str(local_cand->t),
4834 local_cand->name, i, btf_kind_str(t), targ_name,
4836 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
4837 sizeof(*cands->cands));
4841 cand = &new_cands[cands->len];
4842 cand->btf = targ_btf;
4844 cand->name = targ_name;
4847 cands->cands = new_cands;
4853 static int load_module_btfs(struct bpf_object *obj)
4855 struct bpf_btf_info info;
4856 struct module_btf *mod_btf;
4862 if (obj->btf_modules_loaded)
4865 if (obj->gen_loader)
4868 /* don't do this again, even if we find no module BTFs */
4869 obj->btf_modules_loaded = true;
4871 /* kernel too old to support module BTFs */
4872 if (!kernel_supports(obj, FEAT_MODULE_BTF))
4876 err = bpf_btf_get_next_id(id, &id);
4877 if (err && errno == ENOENT)
4881 pr_warn("failed to iterate BTF objects: %d\n", err);
4885 fd = bpf_btf_get_fd_by_id(id);
4887 if (errno == ENOENT)
4888 continue; /* expected race: BTF was unloaded */
4890 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
4895 memset(&info, 0, sizeof(info));
4896 info.name = ptr_to_u64(name);
4897 info.name_len = sizeof(name);
4899 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4902 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
4906 /* ignore non-module BTFs */
4907 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
4912 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
4913 err = libbpf_get_error(btf);
4915 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
4920 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
4921 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4925 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
4930 mod_btf->name = strdup(name);
4931 if (!mod_btf->name) {
4945 static struct bpf_core_cand_list *
4946 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
4948 struct bpf_core_cand local_cand = {};
4949 struct bpf_core_cand_list *cands;
4950 const struct btf *main_btf;
4951 size_t local_essent_len;
4954 local_cand.btf = local_btf;
4955 local_cand.t = btf__type_by_id(local_btf, local_type_id);
4957 return ERR_PTR(-EINVAL);
4959 local_cand.name = btf__name_by_offset(local_btf, local_cand.t->name_off);
4960 if (str_is_empty(local_cand.name))
4961 return ERR_PTR(-EINVAL);
4962 local_essent_len = bpf_core_essential_name_len(local_cand.name);
4964 cands = calloc(1, sizeof(*cands));
4966 return ERR_PTR(-ENOMEM);
4968 /* Attempt to find target candidates in vmlinux BTF first */
4969 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
4970 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
4974 /* if vmlinux BTF has any candidate, don't got for module BTFs */
4978 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
4979 if (obj->btf_vmlinux_override)
4982 /* now look through module BTFs, trying to still find candidates */
4983 err = load_module_btfs(obj);
4987 for (i = 0; i < obj->btf_module_cnt; i++) {
4988 err = bpf_core_add_cands(&local_cand, local_essent_len,
4989 obj->btf_modules[i].btf,
4990 obj->btf_modules[i].name,
4991 btf__get_nr_types(obj->btf_vmlinux) + 1,
4999 bpf_core_free_cands(cands);
5000 return ERR_PTR(err);
5003 /* Check local and target types for compatibility. This check is used for
5004 * type-based CO-RE relocations and follow slightly different rules than
5005 * field-based relocations. This function assumes that root types were already
5006 * checked for name match. Beyond that initial root-level name check, names
5007 * are completely ignored. Compatibility rules are as follows:
5008 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5009 * kind should match for local and target types (i.e., STRUCT is not
5010 * compatible with UNION);
5011 * - for ENUMs, the size is ignored;
5012 * - for INT, size and signedness are ignored;
5013 * - for ARRAY, dimensionality is ignored, element types are checked for
5014 * compatibility recursively;
5015 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5016 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5017 * - FUNC_PROTOs are compatible if they have compatible signature: same
5018 * number of input args and compatible return and argument types.
5019 * These rules are not set in stone and probably will be adjusted as we get
5020 * more experience with using BPF CO-RE relocations.
5022 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5023 const struct btf *targ_btf, __u32 targ_id)
5025 const struct btf_type *local_type, *targ_type;
5026 int depth = 32; /* max recursion depth */
5028 /* caller made sure that names match (ignoring flavor suffix) */
5029 local_type = btf__type_by_id(local_btf, local_id);
5030 targ_type = btf__type_by_id(targ_btf, targ_id);
5031 if (btf_kind(local_type) != btf_kind(targ_type))
5039 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5040 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5041 if (!local_type || !targ_type)
5044 if (btf_kind(local_type) != btf_kind(targ_type))
5047 switch (btf_kind(local_type)) {
5049 case BTF_KIND_STRUCT:
5050 case BTF_KIND_UNION:
5055 /* just reject deprecated bitfield-like integers; all other
5056 * integers are by default compatible between each other
5058 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5060 local_id = local_type->type;
5061 targ_id = targ_type->type;
5063 case BTF_KIND_ARRAY:
5064 local_id = btf_array(local_type)->type;
5065 targ_id = btf_array(targ_type)->type;
5067 case BTF_KIND_FUNC_PROTO: {
5068 struct btf_param *local_p = btf_params(local_type);
5069 struct btf_param *targ_p = btf_params(targ_type);
5070 __u16 local_vlen = btf_vlen(local_type);
5071 __u16 targ_vlen = btf_vlen(targ_type);
5074 if (local_vlen != targ_vlen)
5077 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5078 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5079 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5080 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5085 /* tail recurse for return type check */
5086 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5087 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5091 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5092 btf_kind_str(local_type), local_id, targ_id);
5097 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5102 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5107 static void *u32_as_hash_key(__u32 x)
5109 return (void *)(uintptr_t)x;
5112 static int bpf_core_apply_relo(struct bpf_program *prog,
5113 const struct bpf_core_relo *relo,
5115 const struct btf *local_btf,
5116 struct hashmap *cand_cache)
5118 const void *type_key = u32_as_hash_key(relo->type_id);
5119 struct bpf_core_cand_list *cands = NULL;
5120 const char *prog_name = prog->name;
5121 const struct btf_type *local_type;
5122 const char *local_name;
5123 __u32 local_id = relo->type_id;
5124 struct bpf_insn *insn;
5127 if (relo->insn_off % BPF_INSN_SZ)
5129 insn_idx = relo->insn_off / BPF_INSN_SZ;
5130 /* adjust insn_idx from section frame of reference to the local
5131 * program's frame of reference; (sub-)program code is not yet
5132 * relocated, so it's enough to just subtract in-section offset
5134 insn_idx = insn_idx - prog->sec_insn_off;
5135 if (insn_idx > prog->insns_cnt)
5137 insn = &prog->insns[insn_idx];
5139 local_type = btf__type_by_id(local_btf, local_id);
5143 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5147 if (prog->obj->gen_loader) {
5148 pr_warn("// TODO core_relo: prog %td insn[%d] %s kind %d\n",
5149 prog - prog->obj->programs, relo->insn_off / 8,
5150 local_name, relo->kind);
5154 if (relo->kind != BPF_TYPE_ID_LOCAL &&
5155 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5156 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5157 if (IS_ERR(cands)) {
5158 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5159 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5160 local_name, PTR_ERR(cands));
5161 return PTR_ERR(cands);
5163 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5165 bpf_core_free_cands(cands);
5170 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo, relo_idx, local_btf, cands);
5174 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5176 const struct btf_ext_info_sec *sec;
5177 const struct bpf_core_relo *rec;
5178 const struct btf_ext_info *seg;
5179 struct hashmap_entry *entry;
5180 struct hashmap *cand_cache = NULL;
5181 struct bpf_program *prog;
5182 const char *sec_name;
5183 int i, err = 0, insn_idx, sec_idx;
5185 if (obj->btf_ext->core_relo_info.len == 0)
5188 if (targ_btf_path) {
5189 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5190 err = libbpf_get_error(obj->btf_vmlinux_override);
5192 pr_warn("failed to parse target BTF: %d\n", err);
5197 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5198 if (IS_ERR(cand_cache)) {
5199 err = PTR_ERR(cand_cache);
5203 seg = &obj->btf_ext->core_relo_info;
5204 for_each_btf_ext_sec(seg, sec) {
5205 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5206 if (str_is_empty(sec_name)) {
5210 /* bpf_object's ELF is gone by now so it's not easy to find
5211 * section index by section name, but we can find *any*
5212 * bpf_program within desired section name and use it's
5213 * prog->sec_idx to do a proper search by section index and
5214 * instruction offset
5217 for (i = 0; i < obj->nr_programs; i++) {
5218 prog = &obj->programs[i];
5219 if (strcmp(prog->sec_name, sec_name) == 0)
5223 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5226 sec_idx = prog->sec_idx;
5228 pr_debug("sec '%s': found %d CO-RE relocations\n",
5229 sec_name, sec->num_info);
5231 for_each_btf_ext_rec(seg, sec, i, rec) {
5232 insn_idx = rec->insn_off / BPF_INSN_SZ;
5233 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5235 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5236 sec_name, insn_idx, i);
5240 /* no need to apply CO-RE relocation if the program is
5241 * not going to be loaded
5246 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
5248 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5249 prog->name, i, err);
5256 /* obj->btf_vmlinux and module BTFs are freed after object load */
5257 btf__free(obj->btf_vmlinux_override);
5258 obj->btf_vmlinux_override = NULL;
5260 if (!IS_ERR_OR_NULL(cand_cache)) {
5261 hashmap__for_each_entry(cand_cache, entry, i) {
5262 bpf_core_free_cands(entry->value);
5264 hashmap__free(cand_cache);
5269 /* Relocate data references within program code:
5271 * - global variable references;
5272 * - extern references.
5275 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5279 for (i = 0; i < prog->nr_reloc; i++) {
5280 struct reloc_desc *relo = &prog->reloc_desc[i];
5281 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5282 struct extern_desc *ext;
5284 switch (relo->type) {
5286 if (obj->gen_loader) {
5287 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5288 insn[0].imm = relo->map_idx;
5290 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5291 insn[0].imm = obj->maps[relo->map_idx].fd;
5295 insn[1].imm = insn[0].imm + relo->sym_off;
5296 if (obj->gen_loader) {
5297 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5298 insn[0].imm = relo->map_idx;
5300 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5301 insn[0].imm = obj->maps[relo->map_idx].fd;
5304 case RELO_EXTERN_VAR:
5305 ext = &obj->externs[relo->sym_off];
5306 if (ext->type == EXT_KCFG) {
5307 if (obj->gen_loader) {
5308 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5309 insn[0].imm = obj->kconfig_map_idx;
5311 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5312 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5314 insn[1].imm = ext->kcfg.data_off;
5315 } else /* EXT_KSYM */ {
5316 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5317 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5318 insn[0].imm = ext->ksym.kernel_btf_id;
5319 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5320 } else { /* typeless ksyms or unresolved typed ksyms */
5321 insn[0].imm = (__u32)ext->ksym.addr;
5322 insn[1].imm = ext->ksym.addr >> 32;
5326 case RELO_EXTERN_FUNC:
5327 ext = &obj->externs[relo->sym_off];
5328 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5329 insn[0].imm = ext->ksym.kernel_btf_id;
5331 case RELO_SUBPROG_ADDR:
5332 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5333 pr_warn("prog '%s': relo #%d: bad insn\n",
5337 /* handled already */
5340 /* handled already */
5343 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5344 prog->name, i, relo->type);
5352 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5353 const struct bpf_program *prog,
5354 const struct btf_ext_info *ext_info,
5355 void **prog_info, __u32 *prog_rec_cnt,
5358 void *copy_start = NULL, *copy_end = NULL;
5359 void *rec, *rec_end, *new_prog_info;
5360 const struct btf_ext_info_sec *sec;
5361 size_t old_sz, new_sz;
5362 const char *sec_name;
5365 for_each_btf_ext_sec(ext_info, sec) {
5366 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5369 if (strcmp(sec_name, prog->sec_name) != 0)
5372 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5373 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5375 if (insn_off < prog->sec_insn_off)
5377 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5382 copy_end = rec + ext_info->rec_size;
5388 /* append func/line info of a given (sub-)program to the main
5389 * program func/line info
5391 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5392 new_sz = old_sz + (copy_end - copy_start);
5393 new_prog_info = realloc(*prog_info, new_sz);
5396 *prog_info = new_prog_info;
5397 *prog_rec_cnt = new_sz / ext_info->rec_size;
5398 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5400 /* Kernel instruction offsets are in units of 8-byte
5401 * instructions, while .BTF.ext instruction offsets generated
5402 * by Clang are in units of bytes. So convert Clang offsets
5403 * into kernel offsets and adjust offset according to program
5404 * relocated position.
5406 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5407 rec = new_prog_info + old_sz;
5408 rec_end = new_prog_info + new_sz;
5409 for (; rec < rec_end; rec += ext_info->rec_size) {
5410 __u32 *insn_off = rec;
5412 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5414 *prog_rec_sz = ext_info->rec_size;
5422 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5423 struct bpf_program *main_prog,
5424 const struct bpf_program *prog)
5428 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5429 * supprot func/line info
5431 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5434 /* only attempt func info relocation if main program's func_info
5435 * relocation was successful
5437 if (main_prog != prog && !main_prog->func_info)
5440 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5441 &main_prog->func_info,
5442 &main_prog->func_info_cnt,
5443 &main_prog->func_info_rec_size);
5445 if (err != -ENOENT) {
5446 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5450 if (main_prog->func_info) {
5452 * Some info has already been found but has problem
5453 * in the last btf_ext reloc. Must have to error out.
5455 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5458 /* Have problem loading the very first info. Ignore the rest. */
5459 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5464 /* don't relocate line info if main program's relocation failed */
5465 if (main_prog != prog && !main_prog->line_info)
5468 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5469 &main_prog->line_info,
5470 &main_prog->line_info_cnt,
5471 &main_prog->line_info_rec_size);
5473 if (err != -ENOENT) {
5474 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5478 if (main_prog->line_info) {
5480 * Some info has already been found but has problem
5481 * in the last btf_ext reloc. Must have to error out.
5483 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5486 /* Have problem loading the very first info. Ignore the rest. */
5487 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5493 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5495 size_t insn_idx = *(const size_t *)key;
5496 const struct reloc_desc *relo = elem;
5498 if (insn_idx == relo->insn_idx)
5500 return insn_idx < relo->insn_idx ? -1 : 1;
5503 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5505 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5506 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5509 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5511 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5512 struct reloc_desc *relos;
5515 if (main_prog == subprog)
5517 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5520 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5521 sizeof(*relos) * subprog->nr_reloc);
5523 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5524 relos[i].insn_idx += subprog->sub_insn_off;
5525 /* After insn_idx adjustment the 'relos' array is still sorted
5526 * by insn_idx and doesn't break bsearch.
5528 main_prog->reloc_desc = relos;
5529 main_prog->nr_reloc = new_cnt;
5534 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5535 struct bpf_program *prog)
5537 size_t sub_insn_idx, insn_idx, new_cnt;
5538 struct bpf_program *subprog;
5539 struct bpf_insn *insns, *insn;
5540 struct reloc_desc *relo;
5543 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5547 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5548 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5549 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
5552 relo = find_prog_insn_relo(prog, insn_idx);
5553 if (relo && relo->type == RELO_EXTERN_FUNC)
5554 /* kfunc relocations will be handled later
5555 * in bpf_object__relocate_data()
5558 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
5559 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
5560 prog->name, insn_idx, relo->type);
5561 return -LIBBPF_ERRNO__RELOC;
5564 /* sub-program instruction index is a combination of
5565 * an offset of a symbol pointed to by relocation and
5566 * call instruction's imm field; for global functions,
5567 * call always has imm = -1, but for static functions
5568 * relocation is against STT_SECTION and insn->imm
5569 * points to a start of a static function
5571 * for subprog addr relocation, the relo->sym_off + insn->imm is
5572 * the byte offset in the corresponding section.
5574 if (relo->type == RELO_CALL)
5575 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
5577 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
5578 } else if (insn_is_pseudo_func(insn)) {
5580 * RELO_SUBPROG_ADDR relo is always emitted even if both
5581 * functions are in the same section, so it shouldn't reach here.
5583 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
5584 prog->name, insn_idx);
5585 return -LIBBPF_ERRNO__RELOC;
5587 /* if subprogram call is to a static function within
5588 * the same ELF section, there won't be any relocation
5589 * emitted, but it also means there is no additional
5590 * offset necessary, insns->imm is relative to
5591 * instruction's original position within the section
5593 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
5596 /* we enforce that sub-programs should be in .text section */
5597 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
5599 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
5601 return -LIBBPF_ERRNO__RELOC;
5604 /* if it's the first call instruction calling into this
5605 * subprogram (meaning this subprog hasn't been processed
5606 * yet) within the context of current main program:
5607 * - append it at the end of main program's instructions blog;
5608 * - process is recursively, while current program is put on hold;
5609 * - if that subprogram calls some other not yet processes
5610 * subprogram, same thing will happen recursively until
5611 * there are no more unprocesses subprograms left to append
5614 if (subprog->sub_insn_off == 0) {
5615 subprog->sub_insn_off = main_prog->insns_cnt;
5617 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
5618 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
5620 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
5623 main_prog->insns = insns;
5624 main_prog->insns_cnt = new_cnt;
5626 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
5627 subprog->insns_cnt * sizeof(*insns));
5629 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
5630 main_prog->name, subprog->insns_cnt, subprog->name);
5632 /* The subprog insns are now appended. Append its relos too. */
5633 err = append_subprog_relos(main_prog, subprog);
5636 err = bpf_object__reloc_code(obj, main_prog, subprog);
5641 /* main_prog->insns memory could have been re-allocated, so
5642 * calculate pointer again
5644 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5645 /* calculate correct instruction position within current main
5646 * prog; each main prog can have a different set of
5647 * subprograms appended (potentially in different order as
5648 * well), so position of any subprog can be different for
5649 * different main programs */
5650 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
5652 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
5653 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
5660 * Relocate sub-program calls.
5662 * Algorithm operates as follows. Each entry-point BPF program (referred to as
5663 * main prog) is processed separately. For each subprog (non-entry functions,
5664 * that can be called from either entry progs or other subprogs) gets their
5665 * sub_insn_off reset to zero. This serves as indicator that this subprogram
5666 * hasn't been yet appended and relocated within current main prog. Once its
5667 * relocated, sub_insn_off will point at the position within current main prog
5668 * where given subprog was appended. This will further be used to relocate all
5669 * the call instructions jumping into this subprog.
5671 * We start with main program and process all call instructions. If the call
5672 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
5673 * is zero), subprog instructions are appended at the end of main program's
5674 * instruction array. Then main program is "put on hold" while we recursively
5675 * process newly appended subprogram. If that subprogram calls into another
5676 * subprogram that hasn't been appended, new subprogram is appended again to
5677 * the *main* prog's instructions (subprog's instructions are always left
5678 * untouched, as they need to be in unmodified state for subsequent main progs
5679 * and subprog instructions are always sent only as part of a main prog) and
5680 * the process continues recursively. Once all the subprogs called from a main
5681 * prog or any of its subprogs are appended (and relocated), all their
5682 * positions within finalized instructions array are known, so it's easy to
5683 * rewrite call instructions with correct relative offsets, corresponding to
5684 * desired target subprog.
5686 * Its important to realize that some subprogs might not be called from some
5687 * main prog and any of its called/used subprogs. Those will keep their
5688 * subprog->sub_insn_off as zero at all times and won't be appended to current
5689 * main prog and won't be relocated within the context of current main prog.
5690 * They might still be used from other main progs later.
5692 * Visually this process can be shown as below. Suppose we have two main
5693 * programs mainA and mainB and BPF object contains three subprogs: subA,
5694 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
5695 * subC both call subB:
5697 * +--------+ +-------+
5699 * +--+---+ +--+-+-+ +---+--+
5700 * | subA | | subB | | subC |
5701 * +--+---+ +------+ +---+--+
5704 * +---+-------+ +------+----+
5705 * | mainA | | mainB |
5706 * +-----------+ +-----------+
5708 * We'll start relocating mainA, will find subA, append it and start
5709 * processing sub A recursively:
5711 * +-----------+------+
5713 * +-----------+------+
5715 * At this point we notice that subB is used from subA, so we append it and
5716 * relocate (there are no further subcalls from subB):
5718 * +-----------+------+------+
5719 * | mainA | subA | subB |
5720 * +-----------+------+------+
5722 * At this point, we relocate subA calls, then go one level up and finish with
5723 * relocatin mainA calls. mainA is done.
5725 * For mainB process is similar but results in different order. We start with
5726 * mainB and skip subA and subB, as mainB never calls them (at least
5727 * directly), but we see subC is needed, so we append and start processing it:
5729 * +-----------+------+
5731 * +-----------+------+
5732 * Now we see subC needs subB, so we go back to it, append and relocate it:
5734 * +-----------+------+------+
5735 * | mainB | subC | subB |
5736 * +-----------+------+------+
5738 * At this point we unwind recursion, relocate calls in subC, then in mainB.
5741 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
5743 struct bpf_program *subprog;
5746 /* mark all subprogs as not relocated (yet) within the context of
5747 * current main program
5749 for (i = 0; i < obj->nr_programs; i++) {
5750 subprog = &obj->programs[i];
5751 if (!prog_is_subprog(obj, subprog))
5754 subprog->sub_insn_off = 0;
5757 err = bpf_object__reloc_code(obj, prog, prog);
5766 bpf_object__free_relocs(struct bpf_object *obj)
5768 struct bpf_program *prog;
5771 /* free up relocation descriptors */
5772 for (i = 0; i < obj->nr_programs; i++) {
5773 prog = &obj->programs[i];
5774 zfree(&prog->reloc_desc);
5780 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
5782 struct bpf_program *prog;
5787 err = bpf_object__relocate_core(obj, targ_btf_path);
5789 pr_warn("failed to perform CO-RE relocations: %d\n",
5795 /* Before relocating calls pre-process relocations and mark
5796 * few ld_imm64 instructions that points to subprogs.
5797 * Otherwise bpf_object__reloc_code() later would have to consider
5798 * all ld_imm64 insns as relocation candidates. That would
5799 * reduce relocation speed, since amount of find_prog_insn_relo()
5800 * would increase and most of them will fail to find a relo.
5802 for (i = 0; i < obj->nr_programs; i++) {
5803 prog = &obj->programs[i];
5804 for (j = 0; j < prog->nr_reloc; j++) {
5805 struct reloc_desc *relo = &prog->reloc_desc[j];
5806 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5808 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
5809 if (relo->type == RELO_SUBPROG_ADDR)
5810 insn[0].src_reg = BPF_PSEUDO_FUNC;
5814 /* relocate subprogram calls and append used subprograms to main
5815 * programs; each copy of subprogram code needs to be relocated
5816 * differently for each main program, because its code location might
5818 * Append subprog relos to main programs to allow data relos to be
5819 * processed after text is completely relocated.
5821 for (i = 0; i < obj->nr_programs; i++) {
5822 prog = &obj->programs[i];
5823 /* sub-program's sub-calls are relocated within the context of
5824 * its main program only
5826 if (prog_is_subprog(obj, prog))
5829 err = bpf_object__relocate_calls(obj, prog);
5831 pr_warn("prog '%s': failed to relocate calls: %d\n",
5836 /* Process data relos for main programs */
5837 for (i = 0; i < obj->nr_programs; i++) {
5838 prog = &obj->programs[i];
5839 if (prog_is_subprog(obj, prog))
5841 err = bpf_object__relocate_data(obj, prog);
5843 pr_warn("prog '%s': failed to relocate data references: %d\n",
5848 if (!obj->gen_loader)
5849 bpf_object__free_relocs(obj);
5853 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5854 GElf_Shdr *shdr, Elf_Data *data);
5856 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5857 GElf_Shdr *shdr, Elf_Data *data)
5859 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
5860 int i, j, nrels, new_sz;
5861 const struct btf_var_secinfo *vi = NULL;
5862 const struct btf_type *sec, *var, *def;
5863 struct bpf_map *map = NULL, *targ_map;
5864 const struct btf_member *member;
5865 const char *name, *mname;
5872 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5874 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5878 symbols = obj->efile.symbols;
5879 nrels = shdr->sh_size / shdr->sh_entsize;
5880 for (i = 0; i < nrels; i++) {
5881 if (!gelf_getrel(data, i, &rel)) {
5882 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5883 return -LIBBPF_ERRNO__FORMAT;
5885 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5886 pr_warn(".maps relo #%d: symbol %zx not found\n",
5887 i, (size_t)GELF_R_SYM(rel.r_info));
5888 return -LIBBPF_ERRNO__FORMAT;
5890 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
5891 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5892 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5894 return -LIBBPF_ERRNO__RELOC;
5897 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5898 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5899 (size_t)rel.r_offset, sym.st_name, name);
5901 for (j = 0; j < obj->nr_maps; j++) {
5902 map = &obj->maps[j];
5903 if (map->sec_idx != obj->efile.btf_maps_shndx)
5906 vi = btf_var_secinfos(sec) + map->btf_var_idx;
5907 if (vi->offset <= rel.r_offset &&
5908 rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
5911 if (j == obj->nr_maps) {
5912 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5913 i, name, (size_t)rel.r_offset);
5917 if (!bpf_map_type__is_map_in_map(map->def.type))
5919 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5920 map->def.key_size != sizeof(int)) {
5921 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5922 i, map->name, sizeof(int));
5926 targ_map = bpf_object__find_map_by_name(obj, name);
5930 var = btf__type_by_id(obj->btf, vi->type);
5931 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5932 if (btf_vlen(def) == 0)
5934 member = btf_members(def) + btf_vlen(def) - 1;
5935 mname = btf__name_by_offset(obj->btf, member->name_off);
5936 if (strcmp(mname, "values"))
5939 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5940 if (rel.r_offset - vi->offset < moff)
5943 moff = rel.r_offset - vi->offset - moff;
5944 /* here we use BPF pointer size, which is always 64 bit, as we
5945 * are parsing ELF that was built for BPF target
5947 if (moff % bpf_ptr_sz)
5950 if (moff >= map->init_slots_sz) {
5952 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
5955 map->init_slots = tmp;
5956 memset(map->init_slots + map->init_slots_sz, 0,
5957 (new_sz - map->init_slots_sz) * host_ptr_sz);
5958 map->init_slots_sz = new_sz;
5960 map->init_slots[moff] = targ_map;
5962 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5963 i, map->name, moff, name);
5969 static int cmp_relocs(const void *_a, const void *_b)
5971 const struct reloc_desc *a = _a;
5972 const struct reloc_desc *b = _b;
5974 if (a->insn_idx != b->insn_idx)
5975 return a->insn_idx < b->insn_idx ? -1 : 1;
5977 /* no two relocations should have the same insn_idx, but ... */
5978 if (a->type != b->type)
5979 return a->type < b->type ? -1 : 1;
5984 static int bpf_object__collect_relos(struct bpf_object *obj)
5988 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5989 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5990 Elf_Data *data = obj->efile.reloc_sects[i].data;
5991 int idx = shdr->sh_info;
5993 if (shdr->sh_type != SHT_REL) {
5994 pr_warn("internal error at %d\n", __LINE__);
5995 return -LIBBPF_ERRNO__INTERNAL;
5998 if (idx == obj->efile.st_ops_shndx)
5999 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6000 else if (idx == obj->efile.btf_maps_shndx)
6001 err = bpf_object__collect_map_relos(obj, shdr, data);
6003 err = bpf_object__collect_prog_relos(obj, shdr, data);
6008 for (i = 0; i < obj->nr_programs; i++) {
6009 struct bpf_program *p = &obj->programs[i];
6014 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6019 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6021 if (BPF_CLASS(insn->code) == BPF_JMP &&
6022 BPF_OP(insn->code) == BPF_CALL &&
6023 BPF_SRC(insn->code) == BPF_K &&
6024 insn->src_reg == 0 &&
6025 insn->dst_reg == 0) {
6026 *func_id = insn->imm;
6032 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6034 struct bpf_insn *insn = prog->insns;
6035 enum bpf_func_id func_id;
6038 if (obj->gen_loader)
6041 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6042 if (!insn_is_helper_call(insn, &func_id))
6045 /* on kernels that don't yet support
6046 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6047 * to bpf_probe_read() which works well for old kernels
6050 case BPF_FUNC_probe_read_kernel:
6051 case BPF_FUNC_probe_read_user:
6052 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6053 insn->imm = BPF_FUNC_probe_read;
6055 case BPF_FUNC_probe_read_kernel_str:
6056 case BPF_FUNC_probe_read_user_str:
6057 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6058 insn->imm = BPF_FUNC_probe_read_str;
6068 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
6069 char *license, __u32 kern_version, int *pfd)
6071 struct bpf_prog_load_params load_attr = {};
6072 char *cp, errmsg[STRERR_BUFSIZE];
6073 size_t log_buf_size = 0;
6074 char *log_buf = NULL;
6077 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6079 * The program type must be set. Most likely we couldn't find a proper
6080 * section definition at load time, and thus we didn't infer the type.
6082 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6083 prog->name, prog->sec_name);
6087 if (!insns || !insns_cnt)
6090 load_attr.prog_type = prog->type;
6091 /* old kernels might not support specifying expected_attach_type */
6092 if (!kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE) && prog->sec_def &&
6093 prog->sec_def->is_exp_attach_type_optional)
6094 load_attr.expected_attach_type = 0;
6096 load_attr.expected_attach_type = prog->expected_attach_type;
6097 if (kernel_supports(prog->obj, FEAT_PROG_NAME))
6098 load_attr.name = prog->name;
6099 load_attr.insns = insns;
6100 load_attr.insn_cnt = insns_cnt;
6101 load_attr.license = license;
6102 load_attr.attach_btf_id = prog->attach_btf_id;
6103 if (prog->attach_prog_fd)
6104 load_attr.attach_prog_fd = prog->attach_prog_fd;
6106 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6107 load_attr.attach_btf_id = prog->attach_btf_id;
6108 load_attr.kern_version = kern_version;
6109 load_attr.prog_ifindex = prog->prog_ifindex;
6111 /* specify func_info/line_info only if kernel supports them */
6112 btf_fd = bpf_object__btf_fd(prog->obj);
6113 if (btf_fd >= 0 && kernel_supports(prog->obj, FEAT_BTF_FUNC)) {
6114 load_attr.prog_btf_fd = btf_fd;
6115 load_attr.func_info = prog->func_info;
6116 load_attr.func_info_rec_size = prog->func_info_rec_size;
6117 load_attr.func_info_cnt = prog->func_info_cnt;
6118 load_attr.line_info = prog->line_info;
6119 load_attr.line_info_rec_size = prog->line_info_rec_size;
6120 load_attr.line_info_cnt = prog->line_info_cnt;
6122 load_attr.log_level = prog->log_level;
6123 load_attr.prog_flags = prog->prog_flags;
6125 if (prog->obj->gen_loader) {
6126 bpf_gen__prog_load(prog->obj->gen_loader, &load_attr,
6127 prog - prog->obj->programs);
6133 log_buf = malloc(log_buf_size);
6140 load_attr.log_buf = log_buf;
6141 load_attr.log_buf_sz = log_buf_size;
6142 ret = libbpf__bpf_prog_load(&load_attr);
6145 if (log_buf && load_attr.log_level)
6146 pr_debug("verifier log:\n%s", log_buf);
6148 if (prog->obj->rodata_map_idx >= 0 &&
6149 kernel_supports(prog->obj, FEAT_PROG_BIND_MAP)) {
6150 struct bpf_map *rodata_map =
6151 &prog->obj->maps[prog->obj->rodata_map_idx];
6153 if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) {
6154 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6155 pr_warn("prog '%s': failed to bind .rodata map: %s\n",
6157 /* Don't fail hard if can't bind rodata. */
6166 if (!log_buf || errno == ENOSPC) {
6167 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
6173 ret = errno ? -errno : -LIBBPF_ERRNO__LOAD;
6174 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6175 pr_warn("load bpf program failed: %s\n", cp);
6178 if (log_buf && log_buf[0] != '\0') {
6179 ret = -LIBBPF_ERRNO__VERIFY;
6180 pr_warn("-- BEGIN DUMP LOG ---\n");
6181 pr_warn("\n%s\n", log_buf);
6182 pr_warn("-- END LOG --\n");
6183 } else if (load_attr.insn_cnt >= BPF_MAXINSNS) {
6184 pr_warn("Program too large (%zu insns), at most %d insns\n",
6185 load_attr.insn_cnt, BPF_MAXINSNS);
6186 ret = -LIBBPF_ERRNO__PROG2BIG;
6187 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
6188 /* Wrong program type? */
6191 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
6192 load_attr.expected_attach_type = 0;
6193 load_attr.log_buf = NULL;
6194 load_attr.log_buf_sz = 0;
6195 fd = libbpf__bpf_prog_load(&load_attr);
6198 ret = -LIBBPF_ERRNO__PROGTYPE;
6208 static int bpf_program__record_externs(struct bpf_program *prog)
6210 struct bpf_object *obj = prog->obj;
6213 for (i = 0; i < prog->nr_reloc; i++) {
6214 struct reloc_desc *relo = &prog->reloc_desc[i];
6215 struct extern_desc *ext = &obj->externs[relo->sym_off];
6217 switch (relo->type) {
6218 case RELO_EXTERN_VAR:
6219 if (ext->type != EXT_KSYM)
6221 if (!ext->ksym.type_id) {
6222 pr_warn("typeless ksym %s is not supported yet\n",
6226 bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_VAR,
6229 case RELO_EXTERN_FUNC:
6230 bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_FUNC,
6240 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id);
6242 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
6246 if (prog->obj->loaded) {
6247 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6248 return libbpf_err(-EINVAL);
6251 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6252 prog->type == BPF_PROG_TYPE_LSM ||
6253 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6254 int btf_obj_fd = 0, btf_type_id = 0;
6256 err = libbpf_find_attach_btf_id(prog, &btf_obj_fd, &btf_type_id);
6258 return libbpf_err(err);
6260 prog->attach_btf_obj_fd = btf_obj_fd;
6261 prog->attach_btf_id = btf_type_id;
6264 if (prog->instances.nr < 0 || !prog->instances.fds) {
6265 if (prog->preprocessor) {
6266 pr_warn("Internal error: can't load program '%s'\n",
6268 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
6271 prog->instances.fds = malloc(sizeof(int));
6272 if (!prog->instances.fds) {
6273 pr_warn("Not enough memory for BPF fds\n");
6274 return libbpf_err(-ENOMEM);
6276 prog->instances.nr = 1;
6277 prog->instances.fds[0] = -1;
6280 if (!prog->preprocessor) {
6281 if (prog->instances.nr != 1) {
6282 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6283 prog->name, prog->instances.nr);
6285 if (prog->obj->gen_loader)
6286 bpf_program__record_externs(prog);
6287 err = load_program(prog, prog->insns, prog->insns_cnt,
6288 license, kern_ver, &fd);
6290 prog->instances.fds[0] = fd;
6294 for (i = 0; i < prog->instances.nr; i++) {
6295 struct bpf_prog_prep_result result;
6296 bpf_program_prep_t preprocessor = prog->preprocessor;
6298 memset(&result, 0, sizeof(result));
6299 err = preprocessor(prog, i, prog->insns,
6300 prog->insns_cnt, &result);
6302 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6307 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6308 pr_debug("Skip loading the %dth instance of program '%s'\n",
6310 prog->instances.fds[i] = -1;
6316 err = load_program(prog, result.new_insn_ptr,
6317 result.new_insn_cnt, license, kern_ver, &fd);
6319 pr_warn("Loading the %dth instance of program '%s' failed\n",
6326 prog->instances.fds[i] = fd;
6330 pr_warn("failed to load program '%s'\n", prog->name);
6331 zfree(&prog->insns);
6332 prog->insns_cnt = 0;
6333 return libbpf_err(err);
6337 bpf_object__load_progs(struct bpf_object *obj, int log_level)
6339 struct bpf_program *prog;
6343 for (i = 0; i < obj->nr_programs; i++) {
6344 prog = &obj->programs[i];
6345 err = bpf_object__sanitize_prog(obj, prog);
6350 for (i = 0; i < obj->nr_programs; i++) {
6351 prog = &obj->programs[i];
6352 if (prog_is_subprog(obj, prog))
6355 pr_debug("prog '%s': skipped loading\n", prog->name);
6358 prog->log_level |= log_level;
6359 err = bpf_program__load(prog, obj->license, obj->kern_version);
6363 if (obj->gen_loader)
6364 bpf_object__free_relocs(obj);
6368 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6370 static struct bpf_object *
6371 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6372 const struct bpf_object_open_opts *opts)
6374 const char *obj_name, *kconfig, *btf_tmp_path;
6375 struct bpf_program *prog;
6376 struct bpf_object *obj;
6380 if (elf_version(EV_CURRENT) == EV_NONE) {
6381 pr_warn("failed to init libelf for %s\n",
6382 path ? : "(mem buf)");
6383 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6386 if (!OPTS_VALID(opts, bpf_object_open_opts))
6387 return ERR_PTR(-EINVAL);
6389 obj_name = OPTS_GET(opts, object_name, NULL);
6392 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6393 (unsigned long)obj_buf,
6394 (unsigned long)obj_buf_sz);
6395 obj_name = tmp_name;
6398 pr_debug("loading object '%s' from buffer\n", obj_name);
6401 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6405 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
6407 if (strlen(btf_tmp_path) >= PATH_MAX) {
6408 err = -ENAMETOOLONG;
6411 obj->btf_custom_path = strdup(btf_tmp_path);
6412 if (!obj->btf_custom_path) {
6418 kconfig = OPTS_GET(opts, kconfig, NULL);
6420 obj->kconfig = strdup(kconfig);
6421 if (!obj->kconfig) {
6427 err = bpf_object__elf_init(obj);
6428 err = err ? : bpf_object__check_endianness(obj);
6429 err = err ? : bpf_object__elf_collect(obj);
6430 err = err ? : bpf_object__collect_externs(obj);
6431 err = err ? : bpf_object__finalize_btf(obj);
6432 err = err ? : bpf_object__init_maps(obj, opts);
6433 err = err ? : bpf_object__collect_relos(obj);
6436 bpf_object__elf_finish(obj);
6438 bpf_object__for_each_program(prog, obj) {
6439 prog->sec_def = find_sec_def(prog->sec_name);
6440 if (!prog->sec_def) {
6441 /* couldn't guess, but user might manually specify */
6442 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6443 prog->name, prog->sec_name);
6447 if (prog->sec_def->is_sleepable)
6448 prog->prog_flags |= BPF_F_SLEEPABLE;
6449 bpf_program__set_type(prog, prog->sec_def->prog_type);
6450 bpf_program__set_expected_attach_type(prog,
6451 prog->sec_def->expected_attach_type);
6453 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6454 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6455 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6460 bpf_object__close(obj);
6461 return ERR_PTR(err);
6464 static struct bpf_object *
6465 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
6467 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6468 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
6471 /* param validation */
6475 pr_debug("loading %s\n", attr->file);
6476 return __bpf_object__open(attr->file, NULL, 0, &opts);
6479 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
6481 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
6484 struct bpf_object *bpf_object__open(const char *path)
6486 struct bpf_object_open_attr attr = {
6488 .prog_type = BPF_PROG_TYPE_UNSPEC,
6491 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6495 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
6498 return libbpf_err_ptr(-EINVAL);
6500 pr_debug("loading %s\n", path);
6502 return libbpf_ptr(__bpf_object__open(path, NULL, 0, opts));
6506 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
6507 const struct bpf_object_open_opts *opts)
6509 if (!obj_buf || obj_buf_sz == 0)
6510 return libbpf_err_ptr(-EINVAL);
6512 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, opts));
6516 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
6519 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6520 .object_name = name,
6521 /* wrong default, but backwards-compatible */
6522 .relaxed_maps = true,
6525 /* returning NULL is wrong, but backwards-compatible */
6526 if (!obj_buf || obj_buf_sz == 0)
6527 return errno = EINVAL, NULL;
6529 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, &opts));
6532 int bpf_object__unload(struct bpf_object *obj)
6537 return libbpf_err(-EINVAL);
6539 for (i = 0; i < obj->nr_maps; i++) {
6540 zclose(obj->maps[i].fd);
6541 if (obj->maps[i].st_ops)
6542 zfree(&obj->maps[i].st_ops->kern_vdata);
6545 for (i = 0; i < obj->nr_programs; i++)
6546 bpf_program__unload(&obj->programs[i]);
6551 static int bpf_object__sanitize_maps(struct bpf_object *obj)
6555 bpf_object__for_each_map(m, obj) {
6556 if (!bpf_map__is_internal(m))
6558 if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) {
6559 pr_warn("kernel doesn't support global data\n");
6562 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
6563 m->def.map_flags ^= BPF_F_MMAPABLE;
6569 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
6571 char sym_type, sym_name[500];
6572 unsigned long long sym_addr;
6573 const struct btf_type *t;
6574 struct extern_desc *ext;
6578 f = fopen("/proc/kallsyms", "r");
6581 pr_warn("failed to open /proc/kallsyms: %d\n", err);
6586 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
6587 &sym_addr, &sym_type, sym_name);
6588 if (ret == EOF && feof(f))
6591 pr_warn("failed to read kallsyms entry: %d\n", ret);
6596 ext = find_extern_by_name(obj, sym_name);
6597 if (!ext || ext->type != EXT_KSYM)
6600 t = btf__type_by_id(obj->btf, ext->btf_id);
6604 if (ext->is_set && ext->ksym.addr != sym_addr) {
6605 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
6606 sym_name, ext->ksym.addr, sym_addr);
6612 ext->ksym.addr = sym_addr;
6613 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
6622 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
6623 __u16 kind, struct btf **res_btf,
6626 int i, id, btf_fd, err;
6629 btf = obj->btf_vmlinux;
6631 id = btf__find_by_name_kind(btf, ksym_name, kind);
6633 if (id == -ENOENT) {
6634 err = load_module_btfs(obj);
6638 for (i = 0; i < obj->btf_module_cnt; i++) {
6639 btf = obj->btf_modules[i].btf;
6640 /* we assume module BTF FD is always >0 */
6641 btf_fd = obj->btf_modules[i].fd;
6642 id = btf__find_by_name_kind(btf, ksym_name, kind);
6651 *res_btf_fd = btf_fd;
6655 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
6656 struct extern_desc *ext)
6658 const struct btf_type *targ_var, *targ_type;
6659 __u32 targ_type_id, local_type_id;
6660 const char *targ_var_name;
6661 int id, btf_fd = 0, err;
6662 struct btf *btf = NULL;
6664 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &btf_fd);
6665 if (id == -ESRCH && ext->is_weak) {
6667 } else if (id < 0) {
6668 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
6673 /* find local type_id */
6674 local_type_id = ext->ksym.type_id;
6676 /* find target type_id */
6677 targ_var = btf__type_by_id(btf, id);
6678 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
6679 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
6681 err = bpf_core_types_are_compat(obj->btf, local_type_id,
6684 const struct btf_type *local_type;
6685 const char *targ_name, *local_name;
6687 local_type = btf__type_by_id(obj->btf, local_type_id);
6688 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
6689 targ_name = btf__name_by_offset(btf, targ_type->name_off);
6691 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
6692 ext->name, local_type_id,
6693 btf_kind_str(local_type), local_name, targ_type_id,
6694 btf_kind_str(targ_type), targ_name);
6699 ext->ksym.kernel_btf_obj_fd = btf_fd;
6700 ext->ksym.kernel_btf_id = id;
6701 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
6702 ext->name, id, btf_kind_str(targ_var), targ_var_name);
6707 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
6708 struct extern_desc *ext)
6710 int local_func_proto_id, kfunc_proto_id, kfunc_id;
6711 const struct btf_type *kern_func;
6712 struct btf *kern_btf = NULL;
6713 int ret, kern_btf_fd = 0;
6715 local_func_proto_id = ext->ksym.type_id;
6717 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC,
6718 &kern_btf, &kern_btf_fd);
6720 pr_warn("extern (func ksym) '%s': not found in kernel BTF\n",
6725 if (kern_btf != obj->btf_vmlinux) {
6726 pr_warn("extern (func ksym) '%s': function in kernel module is not supported\n",
6731 kern_func = btf__type_by_id(kern_btf, kfunc_id);
6732 kfunc_proto_id = kern_func->type;
6734 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
6735 kern_btf, kfunc_proto_id);
6737 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
6738 ext->name, local_func_proto_id, kfunc_proto_id);
6743 ext->ksym.kernel_btf_obj_fd = kern_btf_fd;
6744 ext->ksym.kernel_btf_id = kfunc_id;
6745 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
6746 ext->name, kfunc_id);
6751 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
6753 const struct btf_type *t;
6754 struct extern_desc *ext;
6757 for (i = 0; i < obj->nr_extern; i++) {
6758 ext = &obj->externs[i];
6759 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
6762 if (obj->gen_loader) {
6764 ext->ksym.kernel_btf_obj_fd = 0;
6765 ext->ksym.kernel_btf_id = 0;
6768 t = btf__type_by_id(obj->btf, ext->btf_id);
6770 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
6772 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
6779 static int bpf_object__resolve_externs(struct bpf_object *obj,
6780 const char *extra_kconfig)
6782 bool need_config = false, need_kallsyms = false;
6783 bool need_vmlinux_btf = false;
6784 struct extern_desc *ext;
6785 void *kcfg_data = NULL;
6788 if (obj->nr_extern == 0)
6791 if (obj->kconfig_map_idx >= 0)
6792 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
6794 for (i = 0; i < obj->nr_extern; i++) {
6795 ext = &obj->externs[i];
6797 if (ext->type == EXT_KCFG &&
6798 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
6799 void *ext_val = kcfg_data + ext->kcfg.data_off;
6800 __u32 kver = get_kernel_version();
6803 pr_warn("failed to get kernel version\n");
6806 err = set_kcfg_value_num(ext, ext_val, kver);
6809 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
6810 } else if (ext->type == EXT_KCFG &&
6811 strncmp(ext->name, "CONFIG_", 7) == 0) {
6813 } else if (ext->type == EXT_KSYM) {
6814 if (ext->ksym.type_id)
6815 need_vmlinux_btf = true;
6817 need_kallsyms = true;
6819 pr_warn("unrecognized extern '%s'\n", ext->name);
6823 if (need_config && extra_kconfig) {
6824 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
6827 need_config = false;
6828 for (i = 0; i < obj->nr_extern; i++) {
6829 ext = &obj->externs[i];
6830 if (ext->type == EXT_KCFG && !ext->is_set) {
6837 err = bpf_object__read_kconfig_file(obj, kcfg_data);
6841 if (need_kallsyms) {
6842 err = bpf_object__read_kallsyms_file(obj);
6846 if (need_vmlinux_btf) {
6847 err = bpf_object__resolve_ksyms_btf_id(obj);
6851 for (i = 0; i < obj->nr_extern; i++) {
6852 ext = &obj->externs[i];
6854 if (!ext->is_set && !ext->is_weak) {
6855 pr_warn("extern %s (strong) not resolved\n", ext->name);
6857 } else if (!ext->is_set) {
6858 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
6866 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
6868 struct bpf_object *obj;
6872 return libbpf_err(-EINVAL);
6875 return libbpf_err(-EINVAL);
6878 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
6879 return libbpf_err(-EINVAL);
6882 if (obj->gen_loader)
6883 bpf_gen__init(obj->gen_loader, attr->log_level);
6885 err = bpf_object__probe_loading(obj);
6886 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
6887 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
6888 err = err ? : bpf_object__sanitize_and_load_btf(obj);
6889 err = err ? : bpf_object__sanitize_maps(obj);
6890 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
6891 err = err ? : bpf_object__create_maps(obj);
6892 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : attr->target_btf_path);
6893 err = err ? : bpf_object__load_progs(obj, attr->log_level);
6895 if (obj->gen_loader) {
6898 btf__set_fd(obj->btf, -1);
6899 for (i = 0; i < obj->nr_maps; i++)
6900 obj->maps[i].fd = -1;
6902 err = bpf_gen__finish(obj->gen_loader);
6905 /* clean up module BTFs */
6906 for (i = 0; i < obj->btf_module_cnt; i++) {
6907 close(obj->btf_modules[i].fd);
6908 btf__free(obj->btf_modules[i].btf);
6909 free(obj->btf_modules[i].name);
6911 free(obj->btf_modules);
6913 /* clean up vmlinux BTF */
6914 btf__free(obj->btf_vmlinux);
6915 obj->btf_vmlinux = NULL;
6917 obj->loaded = true; /* doesn't matter if successfully or not */
6924 /* unpin any maps that were auto-pinned during load */
6925 for (i = 0; i < obj->nr_maps; i++)
6926 if (obj->maps[i].pinned && !obj->maps[i].reused)
6927 bpf_map__unpin(&obj->maps[i], NULL);
6929 bpf_object__unload(obj);
6930 pr_warn("failed to load object '%s'\n", obj->path);
6931 return libbpf_err(err);
6934 int bpf_object__load(struct bpf_object *obj)
6936 struct bpf_object_load_attr attr = {
6940 return bpf_object__load_xattr(&attr);
6943 static int make_parent_dir(const char *path)
6945 char *cp, errmsg[STRERR_BUFSIZE];
6949 dname = strdup(path);
6953 dir = dirname(dname);
6954 if (mkdir(dir, 0700) && errno != EEXIST)
6959 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
6960 pr_warn("failed to mkdir %s: %s\n", path, cp);
6965 static int check_path(const char *path)
6967 char *cp, errmsg[STRERR_BUFSIZE];
6968 struct statfs st_fs;
6975 dname = strdup(path);
6979 dir = dirname(dname);
6980 if (statfs(dir, &st_fs)) {
6981 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6982 pr_warn("failed to statfs %s: %s\n", dir, cp);
6987 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
6988 pr_warn("specified path %s is not on BPF FS\n", path);
6995 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
6998 char *cp, errmsg[STRERR_BUFSIZE];
7001 err = make_parent_dir(path);
7003 return libbpf_err(err);
7005 err = check_path(path);
7007 return libbpf_err(err);
7010 pr_warn("invalid program pointer\n");
7011 return libbpf_err(-EINVAL);
7014 if (instance < 0 || instance >= prog->instances.nr) {
7015 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7016 instance, prog->name, prog->instances.nr);
7017 return libbpf_err(-EINVAL);
7020 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
7022 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7023 pr_warn("failed to pin program: %s\n", cp);
7024 return libbpf_err(err);
7026 pr_debug("pinned program '%s'\n", path);
7031 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
7036 err = check_path(path);
7038 return libbpf_err(err);
7041 pr_warn("invalid program pointer\n");
7042 return libbpf_err(-EINVAL);
7045 if (instance < 0 || instance >= prog->instances.nr) {
7046 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7047 instance, prog->name, prog->instances.nr);
7048 return libbpf_err(-EINVAL);
7053 return libbpf_err(-errno);
7055 pr_debug("unpinned program '%s'\n", path);
7060 int bpf_program__pin(struct bpf_program *prog, const char *path)
7064 err = make_parent_dir(path);
7066 return libbpf_err(err);
7068 err = check_path(path);
7070 return libbpf_err(err);
7073 pr_warn("invalid program pointer\n");
7074 return libbpf_err(-EINVAL);
7077 if (prog->instances.nr <= 0) {
7078 pr_warn("no instances of prog %s to pin\n", prog->name);
7079 return libbpf_err(-EINVAL);
7082 if (prog->instances.nr == 1) {
7083 /* don't create subdirs when pinning single instance */
7084 return bpf_program__pin_instance(prog, path, 0);
7087 for (i = 0; i < prog->instances.nr; i++) {
7091 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7095 } else if (len >= PATH_MAX) {
7096 err = -ENAMETOOLONG;
7100 err = bpf_program__pin_instance(prog, buf, i);
7108 for (i = i - 1; i >= 0; i--) {
7112 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7115 else if (len >= PATH_MAX)
7118 bpf_program__unpin_instance(prog, buf, i);
7123 return libbpf_err(err);
7126 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7130 err = check_path(path);
7132 return libbpf_err(err);
7135 pr_warn("invalid program pointer\n");
7136 return libbpf_err(-EINVAL);
7139 if (prog->instances.nr <= 0) {
7140 pr_warn("no instances of prog %s to pin\n", prog->name);
7141 return libbpf_err(-EINVAL);
7144 if (prog->instances.nr == 1) {
7145 /* don't create subdirs when pinning single instance */
7146 return bpf_program__unpin_instance(prog, path, 0);
7149 for (i = 0; i < prog->instances.nr; i++) {
7153 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7155 return libbpf_err(-EINVAL);
7156 else if (len >= PATH_MAX)
7157 return libbpf_err(-ENAMETOOLONG);
7159 err = bpf_program__unpin_instance(prog, buf, i);
7166 return libbpf_err(-errno);
7171 int bpf_map__pin(struct bpf_map *map, const char *path)
7173 char *cp, errmsg[STRERR_BUFSIZE];
7177 pr_warn("invalid map pointer\n");
7178 return libbpf_err(-EINVAL);
7181 if (map->pin_path) {
7182 if (path && strcmp(path, map->pin_path)) {
7183 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7184 bpf_map__name(map), map->pin_path, path);
7185 return libbpf_err(-EINVAL);
7186 } else if (map->pinned) {
7187 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7188 bpf_map__name(map), map->pin_path);
7193 pr_warn("missing a path to pin map '%s' at\n",
7194 bpf_map__name(map));
7195 return libbpf_err(-EINVAL);
7196 } else if (map->pinned) {
7197 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7198 return libbpf_err(-EEXIST);
7201 map->pin_path = strdup(path);
7202 if (!map->pin_path) {
7208 err = make_parent_dir(map->pin_path);
7210 return libbpf_err(err);
7212 err = check_path(map->pin_path);
7214 return libbpf_err(err);
7216 if (bpf_obj_pin(map->fd, map->pin_path)) {
7222 pr_debug("pinned map '%s'\n", map->pin_path);
7227 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7228 pr_warn("failed to pin map: %s\n", cp);
7229 return libbpf_err(err);
7232 int bpf_map__unpin(struct bpf_map *map, const char *path)
7237 pr_warn("invalid map pointer\n");
7238 return libbpf_err(-EINVAL);
7241 if (map->pin_path) {
7242 if (path && strcmp(path, map->pin_path)) {
7243 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7244 bpf_map__name(map), map->pin_path, path);
7245 return libbpf_err(-EINVAL);
7247 path = map->pin_path;
7249 pr_warn("no path to unpin map '%s' from\n",
7250 bpf_map__name(map));
7251 return libbpf_err(-EINVAL);
7254 err = check_path(path);
7256 return libbpf_err(err);
7260 return libbpf_err(-errno);
7262 map->pinned = false;
7263 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7268 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7275 return libbpf_err(-errno);
7278 free(map->pin_path);
7279 map->pin_path = new;
7283 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7285 return map->pin_path;
7288 const char *bpf_map__pin_path(const struct bpf_map *map)
7290 return map->pin_path;
7293 bool bpf_map__is_pinned(const struct bpf_map *map)
7298 static void sanitize_pin_path(char *s)
7300 /* bpffs disallows periods in path names */
7308 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7310 struct bpf_map *map;
7314 return libbpf_err(-ENOENT);
7317 pr_warn("object not yet loaded; load it first\n");
7318 return libbpf_err(-ENOENT);
7321 bpf_object__for_each_map(map, obj) {
7322 char *pin_path = NULL;
7328 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7329 bpf_map__name(map));
7332 goto err_unpin_maps;
7333 } else if (len >= PATH_MAX) {
7334 err = -ENAMETOOLONG;
7335 goto err_unpin_maps;
7337 sanitize_pin_path(buf);
7339 } else if (!map->pin_path) {
7343 err = bpf_map__pin(map, pin_path);
7345 goto err_unpin_maps;
7351 while ((map = bpf_map__prev(map, obj))) {
7355 bpf_map__unpin(map, NULL);
7358 return libbpf_err(err);
7361 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7363 struct bpf_map *map;
7367 return libbpf_err(-ENOENT);
7369 bpf_object__for_each_map(map, obj) {
7370 char *pin_path = NULL;
7376 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7377 bpf_map__name(map));
7379 return libbpf_err(-EINVAL);
7380 else if (len >= PATH_MAX)
7381 return libbpf_err(-ENAMETOOLONG);
7382 sanitize_pin_path(buf);
7384 } else if (!map->pin_path) {
7388 err = bpf_map__unpin(map, pin_path);
7390 return libbpf_err(err);
7396 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
7398 struct bpf_program *prog;
7402 return libbpf_err(-ENOENT);
7405 pr_warn("object not yet loaded; load it first\n");
7406 return libbpf_err(-ENOENT);
7409 bpf_object__for_each_program(prog, obj) {
7413 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7417 goto err_unpin_programs;
7418 } else if (len >= PATH_MAX) {
7419 err = -ENAMETOOLONG;
7420 goto err_unpin_programs;
7423 err = bpf_program__pin(prog, buf);
7425 goto err_unpin_programs;
7431 while ((prog = bpf_program__prev(prog, obj))) {
7435 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7439 else if (len >= PATH_MAX)
7442 bpf_program__unpin(prog, buf);
7445 return libbpf_err(err);
7448 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
7450 struct bpf_program *prog;
7454 return libbpf_err(-ENOENT);
7456 bpf_object__for_each_program(prog, obj) {
7460 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7463 return libbpf_err(-EINVAL);
7464 else if (len >= PATH_MAX)
7465 return libbpf_err(-ENAMETOOLONG);
7467 err = bpf_program__unpin(prog, buf);
7469 return libbpf_err(err);
7475 int bpf_object__pin(struct bpf_object *obj, const char *path)
7479 err = bpf_object__pin_maps(obj, path);
7481 return libbpf_err(err);
7483 err = bpf_object__pin_programs(obj, path);
7485 bpf_object__unpin_maps(obj, path);
7486 return libbpf_err(err);
7492 static void bpf_map__destroy(struct bpf_map *map)
7494 if (map->clear_priv)
7495 map->clear_priv(map, map->priv);
7497 map->clear_priv = NULL;
7499 if (map->inner_map) {
7500 bpf_map__destroy(map->inner_map);
7501 zfree(&map->inner_map);
7504 zfree(&map->init_slots);
7505 map->init_slots_sz = 0;
7508 munmap(map->mmaped, bpf_map_mmap_sz(map));
7513 zfree(&map->st_ops->data);
7514 zfree(&map->st_ops->progs);
7515 zfree(&map->st_ops->kern_func_off);
7516 zfree(&map->st_ops);
7520 zfree(&map->pin_path);
7526 void bpf_object__close(struct bpf_object *obj)
7530 if (IS_ERR_OR_NULL(obj))
7533 if (obj->clear_priv)
7534 obj->clear_priv(obj, obj->priv);
7536 bpf_gen__free(obj->gen_loader);
7537 bpf_object__elf_finish(obj);
7538 bpf_object__unload(obj);
7539 btf__free(obj->btf);
7540 btf_ext__free(obj->btf_ext);
7542 for (i = 0; i < obj->nr_maps; i++)
7543 bpf_map__destroy(&obj->maps[i]);
7545 zfree(&obj->btf_custom_path);
7546 zfree(&obj->kconfig);
7547 zfree(&obj->externs);
7553 if (obj->programs && obj->nr_programs) {
7554 for (i = 0; i < obj->nr_programs; i++)
7555 bpf_program__exit(&obj->programs[i]);
7557 zfree(&obj->programs);
7559 list_del(&obj->list);
7564 bpf_object__next(struct bpf_object *prev)
7566 struct bpf_object *next;
7569 next = list_first_entry(&bpf_objects_list,
7573 next = list_next_entry(prev, list);
7575 /* Empty list is noticed here so don't need checking on entry. */
7576 if (&next->list == &bpf_objects_list)
7582 const char *bpf_object__name(const struct bpf_object *obj)
7584 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
7587 unsigned int bpf_object__kversion(const struct bpf_object *obj)
7589 return obj ? obj->kern_version : 0;
7592 struct btf *bpf_object__btf(const struct bpf_object *obj)
7594 return obj ? obj->btf : NULL;
7597 int bpf_object__btf_fd(const struct bpf_object *obj)
7599 return obj->btf ? btf__fd(obj->btf) : -1;
7602 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
7605 return libbpf_err(-EINVAL);
7607 obj->kern_version = kern_version;
7612 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
7613 bpf_object_clear_priv_t clear_priv)
7615 if (obj->priv && obj->clear_priv)
7616 obj->clear_priv(obj, obj->priv);
7619 obj->clear_priv = clear_priv;
7623 void *bpf_object__priv(const struct bpf_object *obj)
7625 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
7628 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
7630 struct bpf_gen *gen;
7634 if (!OPTS_VALID(opts, gen_loader_opts))
7636 gen = calloc(sizeof(*gen), 1);
7640 obj->gen_loader = gen;
7644 static struct bpf_program *
7645 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
7648 size_t nr_programs = obj->nr_programs;
7655 /* Iter from the beginning */
7656 return forward ? &obj->programs[0] :
7657 &obj->programs[nr_programs - 1];
7659 if (p->obj != obj) {
7660 pr_warn("error: program handler doesn't match object\n");
7661 return errno = EINVAL, NULL;
7664 idx = (p - obj->programs) + (forward ? 1 : -1);
7665 if (idx >= obj->nr_programs || idx < 0)
7667 return &obj->programs[idx];
7670 struct bpf_program *
7671 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
7673 struct bpf_program *prog = prev;
7676 prog = __bpf_program__iter(prog, obj, true);
7677 } while (prog && prog_is_subprog(obj, prog));
7682 struct bpf_program *
7683 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
7685 struct bpf_program *prog = next;
7688 prog = __bpf_program__iter(prog, obj, false);
7689 } while (prog && prog_is_subprog(obj, prog));
7694 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
7695 bpf_program_clear_priv_t clear_priv)
7697 if (prog->priv && prog->clear_priv)
7698 prog->clear_priv(prog, prog->priv);
7701 prog->clear_priv = clear_priv;
7705 void *bpf_program__priv(const struct bpf_program *prog)
7707 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
7710 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
7712 prog->prog_ifindex = ifindex;
7715 const char *bpf_program__name(const struct bpf_program *prog)
7720 const char *bpf_program__section_name(const struct bpf_program *prog)
7722 return prog->sec_name;
7725 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
7729 title = prog->sec_name;
7731 title = strdup(title);
7733 pr_warn("failed to strdup program title\n");
7734 return libbpf_err_ptr(-ENOMEM);
7741 bool bpf_program__autoload(const struct bpf_program *prog)
7746 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
7748 if (prog->obj->loaded)
7749 return libbpf_err(-EINVAL);
7751 prog->load = autoload;
7755 int bpf_program__fd(const struct bpf_program *prog)
7757 return bpf_program__nth_fd(prog, 0);
7760 size_t bpf_program__size(const struct bpf_program *prog)
7762 return prog->insns_cnt * BPF_INSN_SZ;
7765 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
7766 bpf_program_prep_t prep)
7770 if (nr_instances <= 0 || !prep)
7771 return libbpf_err(-EINVAL);
7773 if (prog->instances.nr > 0 || prog->instances.fds) {
7774 pr_warn("Can't set pre-processor after loading\n");
7775 return libbpf_err(-EINVAL);
7778 instances_fds = malloc(sizeof(int) * nr_instances);
7779 if (!instances_fds) {
7780 pr_warn("alloc memory failed for fds\n");
7781 return libbpf_err(-ENOMEM);
7784 /* fill all fd with -1 */
7785 memset(instances_fds, -1, sizeof(int) * nr_instances);
7787 prog->instances.nr = nr_instances;
7788 prog->instances.fds = instances_fds;
7789 prog->preprocessor = prep;
7793 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
7798 return libbpf_err(-EINVAL);
7800 if (n >= prog->instances.nr || n < 0) {
7801 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
7802 n, prog->name, prog->instances.nr);
7803 return libbpf_err(-EINVAL);
7806 fd = prog->instances.fds[n];
7808 pr_warn("%dth instance of program '%s' is invalid\n",
7810 return libbpf_err(-ENOENT);
7816 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
7821 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
7826 static bool bpf_program__is_type(const struct bpf_program *prog,
7827 enum bpf_prog_type type)
7829 return prog ? (prog->type == type) : false;
7832 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
7833 int bpf_program__set_##NAME(struct bpf_program *prog) \
7836 return libbpf_err(-EINVAL); \
7837 bpf_program__set_type(prog, TYPE); \
7841 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
7843 return bpf_program__is_type(prog, TYPE); \
7846 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
7847 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
7848 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7849 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
7850 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
7851 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
7852 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7853 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
7854 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
7855 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
7856 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
7857 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
7858 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
7860 enum bpf_attach_type
7861 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
7863 return prog->expected_attach_type;
7866 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
7867 enum bpf_attach_type type)
7869 prog->expected_attach_type = type;
7872 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
7873 attachable, attach_btf) \
7876 .len = sizeof(string) - 1, \
7877 .prog_type = ptype, \
7878 .expected_attach_type = eatype, \
7879 .is_exp_attach_type_optional = eatype_optional, \
7880 .is_attachable = attachable, \
7881 .is_attach_btf = attach_btf, \
7884 /* Programs that can NOT be attached. */
7885 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
7887 /* Programs that can be attached. */
7888 #define BPF_APROG_SEC(string, ptype, atype) \
7889 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
7891 /* Programs that must specify expected attach type at load time. */
7892 #define BPF_EAPROG_SEC(string, ptype, eatype) \
7893 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
7895 /* Programs that use BTF to identify attach point */
7896 #define BPF_PROG_BTF(string, ptype, eatype) \
7897 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
7899 /* Programs that can be attached but attach type can't be identified by section
7900 * name. Kept for backward compatibility.
7902 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
7904 #define SEC_DEF(sec_pfx, ptype, ...) { \
7906 .len = sizeof(sec_pfx) - 1, \
7907 .prog_type = BPF_PROG_TYPE_##ptype, \
7911 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7912 struct bpf_program *prog);
7913 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7914 struct bpf_program *prog);
7915 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7916 struct bpf_program *prog);
7917 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7918 struct bpf_program *prog);
7919 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
7920 struct bpf_program *prog);
7921 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
7922 struct bpf_program *prog);
7924 static const struct bpf_sec_def section_defs[] = {
7925 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
7926 BPF_EAPROG_SEC("sk_reuseport/migrate", BPF_PROG_TYPE_SK_REUSEPORT,
7927 BPF_SK_REUSEPORT_SELECT_OR_MIGRATE),
7928 BPF_EAPROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT,
7929 BPF_SK_REUSEPORT_SELECT),
7930 SEC_DEF("kprobe/", KPROBE,
7931 .attach_fn = attach_kprobe),
7932 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
7933 SEC_DEF("kretprobe/", KPROBE,
7934 .attach_fn = attach_kprobe),
7935 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
7936 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
7937 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
7938 SEC_DEF("tracepoint/", TRACEPOINT,
7939 .attach_fn = attach_tp),
7940 SEC_DEF("tp/", TRACEPOINT,
7941 .attach_fn = attach_tp),
7942 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
7943 .attach_fn = attach_raw_tp),
7944 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
7945 .attach_fn = attach_raw_tp),
7946 SEC_DEF("tp_btf/", TRACING,
7947 .expected_attach_type = BPF_TRACE_RAW_TP,
7948 .is_attach_btf = true,
7949 .attach_fn = attach_trace),
7950 SEC_DEF("fentry/", TRACING,
7951 .expected_attach_type = BPF_TRACE_FENTRY,
7952 .is_attach_btf = true,
7953 .attach_fn = attach_trace),
7954 SEC_DEF("fmod_ret/", TRACING,
7955 .expected_attach_type = BPF_MODIFY_RETURN,
7956 .is_attach_btf = true,
7957 .attach_fn = attach_trace),
7958 SEC_DEF("fexit/", TRACING,
7959 .expected_attach_type = BPF_TRACE_FEXIT,
7960 .is_attach_btf = true,
7961 .attach_fn = attach_trace),
7962 SEC_DEF("fentry.s/", TRACING,
7963 .expected_attach_type = BPF_TRACE_FENTRY,
7964 .is_attach_btf = true,
7965 .is_sleepable = true,
7966 .attach_fn = attach_trace),
7967 SEC_DEF("fmod_ret.s/", TRACING,
7968 .expected_attach_type = BPF_MODIFY_RETURN,
7969 .is_attach_btf = true,
7970 .is_sleepable = true,
7971 .attach_fn = attach_trace),
7972 SEC_DEF("fexit.s/", TRACING,
7973 .expected_attach_type = BPF_TRACE_FEXIT,
7974 .is_attach_btf = true,
7975 .is_sleepable = true,
7976 .attach_fn = attach_trace),
7977 SEC_DEF("freplace/", EXT,
7978 .is_attach_btf = true,
7979 .attach_fn = attach_trace),
7980 SEC_DEF("lsm/", LSM,
7981 .is_attach_btf = true,
7982 .expected_attach_type = BPF_LSM_MAC,
7983 .attach_fn = attach_lsm),
7984 SEC_DEF("lsm.s/", LSM,
7985 .is_attach_btf = true,
7986 .is_sleepable = true,
7987 .expected_attach_type = BPF_LSM_MAC,
7988 .attach_fn = attach_lsm),
7989 SEC_DEF("iter/", TRACING,
7990 .expected_attach_type = BPF_TRACE_ITER,
7991 .is_attach_btf = true,
7992 .attach_fn = attach_iter),
7993 SEC_DEF("syscall", SYSCALL,
7994 .is_sleepable = true),
7995 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
7997 BPF_EAPROG_SEC("xdp_cpumap/", BPF_PROG_TYPE_XDP,
7999 BPF_APROG_SEC("xdp", BPF_PROG_TYPE_XDP,
8001 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
8002 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
8003 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
8004 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
8005 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
8006 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
8007 BPF_CGROUP_INET_INGRESS),
8008 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
8009 BPF_CGROUP_INET_EGRESS),
8010 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
8011 BPF_EAPROG_SEC("cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK,
8012 BPF_CGROUP_INET_SOCK_CREATE),
8013 BPF_EAPROG_SEC("cgroup/sock_release", BPF_PROG_TYPE_CGROUP_SOCK,
8014 BPF_CGROUP_INET_SOCK_RELEASE),
8015 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
8016 BPF_CGROUP_INET_SOCK_CREATE),
8017 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
8018 BPF_CGROUP_INET4_POST_BIND),
8019 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
8020 BPF_CGROUP_INET6_POST_BIND),
8021 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
8023 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
8024 BPF_CGROUP_SOCK_OPS),
8025 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
8026 BPF_SK_SKB_STREAM_PARSER),
8027 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
8028 BPF_SK_SKB_STREAM_VERDICT),
8029 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
8030 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
8031 BPF_SK_MSG_VERDICT),
8032 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
8034 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
8035 BPF_FLOW_DISSECTOR),
8036 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8037 BPF_CGROUP_INET4_BIND),
8038 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8039 BPF_CGROUP_INET6_BIND),
8040 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8041 BPF_CGROUP_INET4_CONNECT),
8042 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8043 BPF_CGROUP_INET6_CONNECT),
8044 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8045 BPF_CGROUP_UDP4_SENDMSG),
8046 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8047 BPF_CGROUP_UDP6_SENDMSG),
8048 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8049 BPF_CGROUP_UDP4_RECVMSG),
8050 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8051 BPF_CGROUP_UDP6_RECVMSG),
8052 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8053 BPF_CGROUP_INET4_GETPEERNAME),
8054 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8055 BPF_CGROUP_INET6_GETPEERNAME),
8056 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8057 BPF_CGROUP_INET4_GETSOCKNAME),
8058 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8059 BPF_CGROUP_INET6_GETSOCKNAME),
8060 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
8062 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8063 BPF_CGROUP_GETSOCKOPT),
8064 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8065 BPF_CGROUP_SETSOCKOPT),
8066 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
8067 BPF_EAPROG_SEC("sk_lookup/", BPF_PROG_TYPE_SK_LOOKUP,
8071 #undef BPF_PROG_SEC_IMPL
8073 #undef BPF_APROG_SEC
8074 #undef BPF_EAPROG_SEC
8075 #undef BPF_APROG_COMPAT
8078 #define MAX_TYPE_NAME_SIZE 32
8080 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8082 int i, n = ARRAY_SIZE(section_defs);
8084 for (i = 0; i < n; i++) {
8085 if (strncmp(sec_name,
8086 section_defs[i].sec, section_defs[i].len))
8088 return §ion_defs[i];
8093 static char *libbpf_get_type_names(bool attach_type)
8095 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8103 /* Forge string buf with all available names */
8104 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8105 if (attach_type && !section_defs[i].is_attachable)
8108 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8113 strcat(buf, section_defs[i].sec);
8119 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8120 enum bpf_attach_type *expected_attach_type)
8122 const struct bpf_sec_def *sec_def;
8126 return libbpf_err(-EINVAL);
8128 sec_def = find_sec_def(name);
8130 *prog_type = sec_def->prog_type;
8131 *expected_attach_type = sec_def->expected_attach_type;
8135 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8136 type_names = libbpf_get_type_names(false);
8137 if (type_names != NULL) {
8138 pr_debug("supported section(type) names are:%s\n", type_names);
8142 return libbpf_err(-ESRCH);
8145 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8148 struct bpf_map *map;
8151 for (i = 0; i < obj->nr_maps; i++) {
8152 map = &obj->maps[i];
8153 if (!bpf_map__is_struct_ops(map))
8155 if (map->sec_offset <= offset &&
8156 offset - map->sec_offset < map->def.value_size)
8163 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8164 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8165 GElf_Shdr *shdr, Elf_Data *data)
8167 const struct btf_member *member;
8168 struct bpf_struct_ops *st_ops;
8169 struct bpf_program *prog;
8170 unsigned int shdr_idx;
8171 const struct btf *btf;
8172 struct bpf_map *map;
8174 unsigned int moff, insn_idx;
8181 symbols = obj->efile.symbols;
8183 nrels = shdr->sh_size / shdr->sh_entsize;
8184 for (i = 0; i < nrels; i++) {
8185 if (!gelf_getrel(data, i, &rel)) {
8186 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8187 return -LIBBPF_ERRNO__FORMAT;
8190 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
8191 pr_warn("struct_ops reloc: symbol %zx not found\n",
8192 (size_t)GELF_R_SYM(rel.r_info));
8193 return -LIBBPF_ERRNO__FORMAT;
8196 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
8197 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
8199 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
8200 (size_t)rel.r_offset);
8204 moff = rel.r_offset - map->sec_offset;
8205 shdr_idx = sym.st_shndx;
8206 st_ops = map->st_ops;
8207 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",
8209 (long long)(rel.r_info >> 32),
8210 (long long)sym.st_value,
8211 shdr_idx, (size_t)rel.r_offset,
8212 map->sec_offset, sym.st_name, name);
8214 if (shdr_idx >= SHN_LORESERVE) {
8215 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
8216 map->name, (size_t)rel.r_offset, shdr_idx);
8217 return -LIBBPF_ERRNO__RELOC;
8219 if (sym.st_value % BPF_INSN_SZ) {
8220 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8221 map->name, (unsigned long long)sym.st_value);
8222 return -LIBBPF_ERRNO__FORMAT;
8224 insn_idx = sym.st_value / BPF_INSN_SZ;
8226 member = find_member_by_offset(st_ops->type, moff * 8);
8228 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8232 member_idx = member - btf_members(st_ops->type);
8233 name = btf__name_by_offset(btf, member->name_off);
8235 if (!resolve_func_ptr(btf, member->type, NULL)) {
8236 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8241 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8243 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8244 map->name, shdr_idx, name);
8248 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
8249 const struct bpf_sec_def *sec_def;
8251 sec_def = find_sec_def(prog->sec_name);
8253 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
8255 prog->type = sec_def->prog_type;
8259 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
8260 prog->attach_btf_id = st_ops->type_id;
8261 prog->expected_attach_type = member_idx;
8262 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
8263 prog->attach_btf_id != st_ops->type_id ||
8264 prog->expected_attach_type != member_idx) {
8267 st_ops->progs[member_idx] = prog;
8273 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",
8274 map->name, prog->name, prog->sec_name, prog->type,
8275 prog->attach_btf_id, prog->expected_attach_type, name);
8279 #define BTF_TRACE_PREFIX "btf_trace_"
8280 #define BTF_LSM_PREFIX "bpf_lsm_"
8281 #define BTF_ITER_PREFIX "bpf_iter_"
8282 #define BTF_MAX_NAME_SIZE 128
8284 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8285 const char **prefix, int *kind)
8287 switch (attach_type) {
8288 case BPF_TRACE_RAW_TP:
8289 *prefix = BTF_TRACE_PREFIX;
8290 *kind = BTF_KIND_TYPEDEF;
8293 *prefix = BTF_LSM_PREFIX;
8294 *kind = BTF_KIND_FUNC;
8296 case BPF_TRACE_ITER:
8297 *prefix = BTF_ITER_PREFIX;
8298 *kind = BTF_KIND_FUNC;
8302 *kind = BTF_KIND_FUNC;
8306 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8307 const char *name, __u32 kind)
8309 char btf_type_name[BTF_MAX_NAME_SIZE];
8312 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8313 "%s%s", prefix, name);
8314 /* snprintf returns the number of characters written excluding the
8315 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8316 * indicates truncation.
8318 if (ret < 0 || ret >= sizeof(btf_type_name))
8319 return -ENAMETOOLONG;
8320 return btf__find_by_name_kind(btf, btf_type_name, kind);
8323 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8324 enum bpf_attach_type attach_type)
8329 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8330 return find_btf_by_prefix_kind(btf, prefix, name, kind);
8333 int libbpf_find_vmlinux_btf_id(const char *name,
8334 enum bpf_attach_type attach_type)
8339 btf = btf__load_vmlinux_btf();
8340 err = libbpf_get_error(btf);
8342 pr_warn("vmlinux BTF is not found\n");
8343 return libbpf_err(err);
8346 err = find_attach_btf_id(btf, name, attach_type);
8348 pr_warn("%s is not found in vmlinux BTF\n", name);
8351 return libbpf_err(err);
8354 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8356 struct bpf_prog_info_linear *info_linear;
8357 struct bpf_prog_info *info;
8361 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
8362 err = libbpf_get_error(info_linear);
8364 pr_warn("failed get_prog_info_linear for FD %d\n",
8370 info = &info_linear->info;
8371 if (!info->btf_id) {
8372 pr_warn("The target program doesn't have BTF\n");
8375 btf = btf__load_from_kernel_by_id(info->btf_id);
8376 if (libbpf_get_error(btf)) {
8377 pr_warn("Failed to get BTF of the program\n");
8380 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8383 pr_warn("%s is not found in prog's BTF\n", name);
8391 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
8392 enum bpf_attach_type attach_type,
8393 int *btf_obj_fd, int *btf_type_id)
8397 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
8399 *btf_obj_fd = 0; /* vmlinux BTF */
8406 ret = load_module_btfs(obj);
8410 for (i = 0; i < obj->btf_module_cnt; i++) {
8411 const struct module_btf *mod = &obj->btf_modules[i];
8413 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
8415 *btf_obj_fd = mod->fd;
8428 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id)
8430 enum bpf_attach_type attach_type = prog->expected_attach_type;
8431 __u32 attach_prog_fd = prog->attach_prog_fd;
8432 const char *name = prog->sec_name, *attach_name;
8433 const struct bpf_sec_def *sec = NULL;
8439 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8440 if (!section_defs[i].is_attach_btf)
8442 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8445 sec = §ion_defs[i];
8450 pr_warn("failed to identify BTF ID based on ELF section name '%s'\n", name);
8453 attach_name = name + sec->len;
8455 /* BPF program's BTF ID */
8456 if (attach_prog_fd) {
8457 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
8459 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
8460 attach_prog_fd, attach_name, err);
8468 /* kernel/module BTF ID */
8469 if (prog->obj->gen_loader) {
8470 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
8474 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
8477 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
8483 int libbpf_attach_type_by_name(const char *name,
8484 enum bpf_attach_type *attach_type)
8490 return libbpf_err(-EINVAL);
8492 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8493 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8495 if (!section_defs[i].is_attachable)
8496 return libbpf_err(-EINVAL);
8497 *attach_type = section_defs[i].expected_attach_type;
8500 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
8501 type_names = libbpf_get_type_names(true);
8502 if (type_names != NULL) {
8503 pr_debug("attachable section(type) names are:%s\n", type_names);
8507 return libbpf_err(-EINVAL);
8510 int bpf_map__fd(const struct bpf_map *map)
8512 return map ? map->fd : libbpf_err(-EINVAL);
8515 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
8517 return map ? &map->def : libbpf_err_ptr(-EINVAL);
8520 const char *bpf_map__name(const struct bpf_map *map)
8522 return map ? map->name : NULL;
8525 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
8527 return map->def.type;
8530 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
8533 return libbpf_err(-EBUSY);
8534 map->def.type = type;
8538 __u32 bpf_map__map_flags(const struct bpf_map *map)
8540 return map->def.map_flags;
8543 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
8546 return libbpf_err(-EBUSY);
8547 map->def.map_flags = flags;
8551 __u32 bpf_map__numa_node(const struct bpf_map *map)
8553 return map->numa_node;
8556 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
8559 return libbpf_err(-EBUSY);
8560 map->numa_node = numa_node;
8564 __u32 bpf_map__key_size(const struct bpf_map *map)
8566 return map->def.key_size;
8569 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
8572 return libbpf_err(-EBUSY);
8573 map->def.key_size = size;
8577 __u32 bpf_map__value_size(const struct bpf_map *map)
8579 return map->def.value_size;
8582 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
8585 return libbpf_err(-EBUSY);
8586 map->def.value_size = size;
8590 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8592 return map ? map->btf_key_type_id : 0;
8595 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8597 return map ? map->btf_value_type_id : 0;
8600 int bpf_map__set_priv(struct bpf_map *map, void *priv,
8601 bpf_map_clear_priv_t clear_priv)
8604 return libbpf_err(-EINVAL);
8607 if (map->clear_priv)
8608 map->clear_priv(map, map->priv);
8612 map->clear_priv = clear_priv;
8616 void *bpf_map__priv(const struct bpf_map *map)
8618 return map ? map->priv : libbpf_err_ptr(-EINVAL);
8621 int bpf_map__set_initial_value(struct bpf_map *map,
8622 const void *data, size_t size)
8624 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
8625 size != map->def.value_size || map->fd >= 0)
8626 return libbpf_err(-EINVAL);
8628 memcpy(map->mmaped, data, size);
8632 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
8636 *psize = map->def.value_size;
8640 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
8642 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
8645 bool bpf_map__is_internal(const struct bpf_map *map)
8647 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
8650 __u32 bpf_map__ifindex(const struct bpf_map *map)
8652 return map->map_ifindex;
8655 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
8658 return libbpf_err(-EBUSY);
8659 map->map_ifindex = ifindex;
8663 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
8665 if (!bpf_map_type__is_map_in_map(map->def.type)) {
8666 pr_warn("error: unsupported map type\n");
8667 return libbpf_err(-EINVAL);
8669 if (map->inner_map_fd != -1) {
8670 pr_warn("error: inner_map_fd already specified\n");
8671 return libbpf_err(-EINVAL);
8673 zfree(&map->inner_map);
8674 map->inner_map_fd = fd;
8678 static struct bpf_map *
8679 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
8682 struct bpf_map *s, *e;
8684 if (!obj || !obj->maps)
8685 return errno = EINVAL, NULL;
8688 e = obj->maps + obj->nr_maps;
8690 if ((m < s) || (m >= e)) {
8691 pr_warn("error in %s: map handler doesn't belong to object\n",
8693 return errno = EINVAL, NULL;
8696 idx = (m - obj->maps) + i;
8697 if (idx >= obj->nr_maps || idx < 0)
8699 return &obj->maps[idx];
8703 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
8708 return __bpf_map__iter(prev, obj, 1);
8712 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
8717 return obj->maps + obj->nr_maps - 1;
8720 return __bpf_map__iter(next, obj, -1);
8724 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
8726 struct bpf_map *pos;
8728 bpf_object__for_each_map(pos, obj) {
8729 if (pos->name && !strcmp(pos->name, name))
8732 return errno = ENOENT, NULL;
8736 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
8738 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
8742 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
8744 return libbpf_err_ptr(-ENOTSUP);
8747 long libbpf_get_error(const void *ptr)
8749 if (!IS_ERR_OR_NULL(ptr))
8753 errno = -PTR_ERR(ptr);
8755 /* If ptr == NULL, then errno should be already set by the failing
8756 * API, because libbpf never returns NULL on success and it now always
8757 * sets errno on error. So no extra errno handling for ptr == NULL
8763 int bpf_prog_load(const char *file, enum bpf_prog_type type,
8764 struct bpf_object **pobj, int *prog_fd)
8766 struct bpf_prog_load_attr attr;
8768 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
8770 attr.prog_type = type;
8771 attr.expected_attach_type = 0;
8773 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
8776 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
8777 struct bpf_object **pobj, int *prog_fd)
8779 struct bpf_object_open_attr open_attr = {};
8780 struct bpf_program *prog, *first_prog = NULL;
8781 struct bpf_object *obj;
8782 struct bpf_map *map;
8786 return libbpf_err(-EINVAL);
8788 return libbpf_err(-EINVAL);
8790 open_attr.file = attr->file;
8791 open_attr.prog_type = attr->prog_type;
8793 obj = bpf_object__open_xattr(&open_attr);
8794 err = libbpf_get_error(obj);
8796 return libbpf_err(-ENOENT);
8798 bpf_object__for_each_program(prog, obj) {
8799 enum bpf_attach_type attach_type = attr->expected_attach_type;
8801 * to preserve backwards compatibility, bpf_prog_load treats
8802 * attr->prog_type, if specified, as an override to whatever
8803 * bpf_object__open guessed
8805 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
8806 bpf_program__set_type(prog, attr->prog_type);
8807 bpf_program__set_expected_attach_type(prog,
8810 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
8812 * we haven't guessed from section name and user
8813 * didn't provide a fallback type, too bad...
8815 bpf_object__close(obj);
8816 return libbpf_err(-EINVAL);
8819 prog->prog_ifindex = attr->ifindex;
8820 prog->log_level = attr->log_level;
8821 prog->prog_flags |= attr->prog_flags;
8826 bpf_object__for_each_map(map, obj) {
8827 if (!bpf_map__is_offload_neutral(map))
8828 map->map_ifindex = attr->ifindex;
8832 pr_warn("object file doesn't contain bpf program\n");
8833 bpf_object__close(obj);
8834 return libbpf_err(-ENOENT);
8837 err = bpf_object__load(obj);
8839 bpf_object__close(obj);
8840 return libbpf_err(err);
8844 *prog_fd = bpf_program__fd(first_prog);
8849 int (*detach)(struct bpf_link *link);
8850 void (*dealloc)(struct bpf_link *link);
8851 char *pin_path; /* NULL, if not pinned */
8852 int fd; /* hook FD, -1 if not applicable */
8856 /* Replace link's underlying BPF program with the new one */
8857 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
8861 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
8862 return libbpf_err_errno(ret);
8865 /* Release "ownership" of underlying BPF resource (typically, BPF program
8866 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
8867 * link, when destructed through bpf_link__destroy() call won't attempt to
8868 * detach/unregisted that BPF resource. This is useful in situations where,
8869 * say, attached BPF program has to outlive userspace program that attached it
8870 * in the system. Depending on type of BPF program, though, there might be
8871 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
8872 * exit of userspace program doesn't trigger automatic detachment and clean up
8873 * inside the kernel.
8875 void bpf_link__disconnect(struct bpf_link *link)
8877 link->disconnected = true;
8880 int bpf_link__destroy(struct bpf_link *link)
8884 if (IS_ERR_OR_NULL(link))
8887 if (!link->disconnected && link->detach)
8888 err = link->detach(link);
8890 free(link->pin_path);
8892 link->dealloc(link);
8896 return libbpf_err(err);
8899 int bpf_link__fd(const struct bpf_link *link)
8904 const char *bpf_link__pin_path(const struct bpf_link *link)
8906 return link->pin_path;
8909 static int bpf_link__detach_fd(struct bpf_link *link)
8911 return libbpf_err_errno(close(link->fd));
8914 struct bpf_link *bpf_link__open(const char *path)
8916 struct bpf_link *link;
8919 fd = bpf_obj_get(path);
8922 pr_warn("failed to open link at %s: %d\n", path, fd);
8923 return libbpf_err_ptr(fd);
8926 link = calloc(1, sizeof(*link));
8929 return libbpf_err_ptr(-ENOMEM);
8931 link->detach = &bpf_link__detach_fd;
8934 link->pin_path = strdup(path);
8935 if (!link->pin_path) {
8936 bpf_link__destroy(link);
8937 return libbpf_err_ptr(-ENOMEM);
8943 int bpf_link__detach(struct bpf_link *link)
8945 return bpf_link_detach(link->fd) ? -errno : 0;
8948 int bpf_link__pin(struct bpf_link *link, const char *path)
8953 return libbpf_err(-EBUSY);
8954 err = make_parent_dir(path);
8956 return libbpf_err(err);
8957 err = check_path(path);
8959 return libbpf_err(err);
8961 link->pin_path = strdup(path);
8962 if (!link->pin_path)
8963 return libbpf_err(-ENOMEM);
8965 if (bpf_obj_pin(link->fd, link->pin_path)) {
8967 zfree(&link->pin_path);
8968 return libbpf_err(err);
8971 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
8975 int bpf_link__unpin(struct bpf_link *link)
8979 if (!link->pin_path)
8980 return libbpf_err(-EINVAL);
8982 err = unlink(link->pin_path);
8986 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
8987 zfree(&link->pin_path);
8991 struct bpf_link_perf {
8992 struct bpf_link link;
8996 static int bpf_link_perf_detach(struct bpf_link *link)
8998 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9001 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9004 if (perf_link->perf_event_fd != link->fd)
9005 close(perf_link->perf_event_fd);
9008 return libbpf_err(err);
9011 static void bpf_link_perf_dealloc(struct bpf_link *link)
9013 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9018 struct bpf_link *bpf_program__attach_perf_event_opts(struct bpf_program *prog, int pfd,
9019 const struct bpf_perf_event_opts *opts)
9021 char errmsg[STRERR_BUFSIZE];
9022 struct bpf_link_perf *link;
9023 int prog_fd, link_fd = -1, err;
9025 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9026 return libbpf_err_ptr(-EINVAL);
9029 pr_warn("prog '%s': invalid perf event FD %d\n",
9031 return libbpf_err_ptr(-EINVAL);
9033 prog_fd = bpf_program__fd(prog);
9035 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9037 return libbpf_err_ptr(-EINVAL);
9040 link = calloc(1, sizeof(*link));
9042 return libbpf_err_ptr(-ENOMEM);
9043 link->link.detach = &bpf_link_perf_detach;
9044 link->link.dealloc = &bpf_link_perf_dealloc;
9045 link->perf_event_fd = pfd;
9047 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9048 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9049 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9051 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9054 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9056 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9059 link->link.fd = link_fd;
9061 if (OPTS_GET(opts, bpf_cookie, 0)) {
9062 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9067 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9069 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9070 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9072 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9076 link->link.fd = pfd;
9078 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9080 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9081 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9090 return libbpf_err_ptr(err);
9093 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog, int pfd)
9095 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9099 * this function is expected to parse integer in the range of [0, 2^31-1] from
9100 * given file using scanf format string fmt. If actual parsed value is
9101 * negative, the result might be indistinguishable from error
9103 static int parse_uint_from_file(const char *file, const char *fmt)
9105 char buf[STRERR_BUFSIZE];
9109 f = fopen(file, "r");
9112 pr_debug("failed to open '%s': %s\n", file,
9113 libbpf_strerror_r(err, buf, sizeof(buf)));
9116 err = fscanf(f, fmt, &ret);
9118 err = err == EOF ? -EIO : -errno;
9119 pr_debug("failed to parse '%s': %s\n", file,
9120 libbpf_strerror_r(err, buf, sizeof(buf)));
9128 static int determine_kprobe_perf_type(void)
9130 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9132 return parse_uint_from_file(file, "%d\n");
9135 static int determine_uprobe_perf_type(void)
9137 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9139 return parse_uint_from_file(file, "%d\n");
9142 static int determine_kprobe_retprobe_bit(void)
9144 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9146 return parse_uint_from_file(file, "config:%d\n");
9149 static int determine_uprobe_retprobe_bit(void)
9151 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9153 return parse_uint_from_file(file, "config:%d\n");
9156 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9157 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9159 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9160 uint64_t offset, int pid, size_t ref_ctr_off)
9162 struct perf_event_attr attr = {};
9163 char errmsg[STRERR_BUFSIZE];
9166 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9169 type = uprobe ? determine_uprobe_perf_type()
9170 : determine_kprobe_perf_type();
9172 pr_warn("failed to determine %s perf type: %s\n",
9173 uprobe ? "uprobe" : "kprobe",
9174 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9178 int bit = uprobe ? determine_uprobe_retprobe_bit()
9179 : determine_kprobe_retprobe_bit();
9182 pr_warn("failed to determine %s retprobe bit: %s\n",
9183 uprobe ? "uprobe" : "kprobe",
9184 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9187 attr.config |= 1 << bit;
9189 attr.size = sizeof(attr);
9191 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9192 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9193 attr.config2 = offset; /* kprobe_addr or probe_offset */
9195 /* pid filter is meaningful only for uprobes */
9196 pfd = syscall(__NR_perf_event_open, &attr,
9197 pid < 0 ? -1 : pid /* pid */,
9198 pid == -1 ? 0 : -1 /* cpu */,
9199 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9202 pr_warn("%s perf_event_open() failed: %s\n",
9203 uprobe ? "uprobe" : "kprobe",
9204 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9211 bpf_program__attach_kprobe_opts(struct bpf_program *prog,
9212 const char *func_name,
9213 const struct bpf_kprobe_opts *opts)
9215 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9216 char errmsg[STRERR_BUFSIZE];
9217 struct bpf_link *link;
9218 unsigned long offset;
9222 if (!OPTS_VALID(opts, bpf_kprobe_opts))
9223 return libbpf_err_ptr(-EINVAL);
9225 retprobe = OPTS_GET(opts, retprobe, false);
9226 offset = OPTS_GET(opts, offset, 0);
9227 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9229 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
9230 offset, -1 /* pid */, 0 /* ref_ctr_off */);
9232 pr_warn("prog '%s': failed to create %s '%s' perf event: %s\n",
9233 prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9234 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9235 return libbpf_err_ptr(pfd);
9237 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9238 err = libbpf_get_error(link);
9241 pr_warn("prog '%s': failed to attach to %s '%s': %s\n",
9242 prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9243 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9244 return libbpf_err_ptr(err);
9249 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
9251 const char *func_name)
9253 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
9254 .retprobe = retprobe,
9257 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
9260 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
9261 struct bpf_program *prog)
9263 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
9264 unsigned long offset = 0;
9265 struct bpf_link *link;
9266 const char *func_name;
9270 func_name = prog->sec_name + sec->len;
9271 opts.retprobe = strcmp(sec->sec, "kretprobe/") == 0;
9273 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
9276 pr_warn("kprobe name is invalid: %s\n", func_name);
9277 return libbpf_err_ptr(err);
9279 if (opts.retprobe && offset != 0) {
9282 pr_warn("kretprobes do not support offset specification\n");
9283 return libbpf_err_ptr(err);
9286 opts.offset = offset;
9287 link = bpf_program__attach_kprobe_opts(prog, func, &opts);
9292 LIBBPF_API struct bpf_link *
9293 bpf_program__attach_uprobe_opts(struct bpf_program *prog, pid_t pid,
9294 const char *binary_path, size_t func_offset,
9295 const struct bpf_uprobe_opts *opts)
9297 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9298 char errmsg[STRERR_BUFSIZE];
9299 struct bpf_link *link;
9304 if (!OPTS_VALID(opts, bpf_uprobe_opts))
9305 return libbpf_err_ptr(-EINVAL);
9307 retprobe = OPTS_GET(opts, retprobe, false);
9308 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
9309 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9311 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
9312 func_offset, pid, ref_ctr_off);
9314 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
9315 prog->name, retprobe ? "uretprobe" : "uprobe",
9316 binary_path, func_offset,
9317 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9318 return libbpf_err_ptr(pfd);
9320 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9321 err = libbpf_get_error(link);
9324 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
9325 prog->name, retprobe ? "uretprobe" : "uprobe",
9326 binary_path, func_offset,
9327 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9328 return libbpf_err_ptr(err);
9333 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
9334 bool retprobe, pid_t pid,
9335 const char *binary_path,
9338 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
9340 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
9343 static int determine_tracepoint_id(const char *tp_category,
9344 const char *tp_name)
9346 char file[PATH_MAX];
9349 ret = snprintf(file, sizeof(file),
9350 "/sys/kernel/debug/tracing/events/%s/%s/id",
9351 tp_category, tp_name);
9354 if (ret >= sizeof(file)) {
9355 pr_debug("tracepoint %s/%s path is too long\n",
9356 tp_category, tp_name);
9359 return parse_uint_from_file(file, "%d\n");
9362 static int perf_event_open_tracepoint(const char *tp_category,
9363 const char *tp_name)
9365 struct perf_event_attr attr = {};
9366 char errmsg[STRERR_BUFSIZE];
9367 int tp_id, pfd, err;
9369 tp_id = determine_tracepoint_id(tp_category, tp_name);
9371 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
9372 tp_category, tp_name,
9373 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
9377 attr.type = PERF_TYPE_TRACEPOINT;
9378 attr.size = sizeof(attr);
9379 attr.config = tp_id;
9381 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
9382 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9385 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
9386 tp_category, tp_name,
9387 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9393 struct bpf_link *bpf_program__attach_tracepoint_opts(struct bpf_program *prog,
9394 const char *tp_category,
9395 const char *tp_name,
9396 const struct bpf_tracepoint_opts *opts)
9398 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9399 char errmsg[STRERR_BUFSIZE];
9400 struct bpf_link *link;
9403 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
9404 return libbpf_err_ptr(-EINVAL);
9406 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9408 pfd = perf_event_open_tracepoint(tp_category, tp_name);
9410 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
9411 prog->name, tp_category, tp_name,
9412 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9413 return libbpf_err_ptr(pfd);
9415 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9416 err = libbpf_get_error(link);
9419 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
9420 prog->name, tp_category, tp_name,
9421 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9422 return libbpf_err_ptr(err);
9427 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
9428 const char *tp_category,
9429 const char *tp_name)
9431 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
9434 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
9435 struct bpf_program *prog)
9437 char *sec_name, *tp_cat, *tp_name;
9438 struct bpf_link *link;
9440 sec_name = strdup(prog->sec_name);
9442 return libbpf_err_ptr(-ENOMEM);
9444 /* extract "tp/<category>/<name>" */
9445 tp_cat = sec_name + sec->len;
9446 tp_name = strchr(tp_cat, '/');
9449 return libbpf_err_ptr(-EINVAL);
9454 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
9459 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
9460 const char *tp_name)
9462 char errmsg[STRERR_BUFSIZE];
9463 struct bpf_link *link;
9466 prog_fd = bpf_program__fd(prog);
9468 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9469 return libbpf_err_ptr(-EINVAL);
9472 link = calloc(1, sizeof(*link));
9474 return libbpf_err_ptr(-ENOMEM);
9475 link->detach = &bpf_link__detach_fd;
9477 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
9481 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
9482 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9483 return libbpf_err_ptr(pfd);
9489 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
9490 struct bpf_program *prog)
9492 const char *tp_name = prog->sec_name + sec->len;
9494 return bpf_program__attach_raw_tracepoint(prog, tp_name);
9497 /* Common logic for all BPF program types that attach to a btf_id */
9498 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
9500 char errmsg[STRERR_BUFSIZE];
9501 struct bpf_link *link;
9504 prog_fd = bpf_program__fd(prog);
9506 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9507 return libbpf_err_ptr(-EINVAL);
9510 link = calloc(1, sizeof(*link));
9512 return libbpf_err_ptr(-ENOMEM);
9513 link->detach = &bpf_link__detach_fd;
9515 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
9519 pr_warn("prog '%s': failed to attach: %s\n",
9520 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9521 return libbpf_err_ptr(pfd);
9524 return (struct bpf_link *)link;
9527 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
9529 return bpf_program__attach_btf_id(prog);
9532 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
9534 return bpf_program__attach_btf_id(prog);
9537 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
9538 struct bpf_program *prog)
9540 return bpf_program__attach_trace(prog);
9543 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
9544 struct bpf_program *prog)
9546 return bpf_program__attach_lsm(prog);
9549 static struct bpf_link *
9550 bpf_program__attach_fd(struct bpf_program *prog, int target_fd, int btf_id,
9551 const char *target_name)
9553 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
9554 .target_btf_id = btf_id);
9555 enum bpf_attach_type attach_type;
9556 char errmsg[STRERR_BUFSIZE];
9557 struct bpf_link *link;
9558 int prog_fd, link_fd;
9560 prog_fd = bpf_program__fd(prog);
9562 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9563 return libbpf_err_ptr(-EINVAL);
9566 link = calloc(1, sizeof(*link));
9568 return libbpf_err_ptr(-ENOMEM);
9569 link->detach = &bpf_link__detach_fd;
9571 attach_type = bpf_program__get_expected_attach_type(prog);
9572 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
9576 pr_warn("prog '%s': failed to attach to %s: %s\n",
9577 prog->name, target_name,
9578 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9579 return libbpf_err_ptr(link_fd);
9586 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
9588 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
9592 bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
9594 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
9597 struct bpf_link *bpf_program__attach_xdp(struct bpf_program *prog, int ifindex)
9599 /* target_fd/target_ifindex use the same field in LINK_CREATE */
9600 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
9603 struct bpf_link *bpf_program__attach_freplace(struct bpf_program *prog,
9605 const char *attach_func_name)
9609 if (!!target_fd != !!attach_func_name) {
9610 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
9612 return libbpf_err_ptr(-EINVAL);
9615 if (prog->type != BPF_PROG_TYPE_EXT) {
9616 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
9618 return libbpf_err_ptr(-EINVAL);
9622 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
9624 return libbpf_err_ptr(btf_id);
9626 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
9628 /* no target, so use raw_tracepoint_open for compatibility
9631 return bpf_program__attach_trace(prog);
9636 bpf_program__attach_iter(struct bpf_program *prog,
9637 const struct bpf_iter_attach_opts *opts)
9639 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
9640 char errmsg[STRERR_BUFSIZE];
9641 struct bpf_link *link;
9642 int prog_fd, link_fd;
9643 __u32 target_fd = 0;
9645 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
9646 return libbpf_err_ptr(-EINVAL);
9648 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
9649 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
9651 prog_fd = bpf_program__fd(prog);
9653 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9654 return libbpf_err_ptr(-EINVAL);
9657 link = calloc(1, sizeof(*link));
9659 return libbpf_err_ptr(-ENOMEM);
9660 link->detach = &bpf_link__detach_fd;
9662 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
9667 pr_warn("prog '%s': failed to attach to iterator: %s\n",
9668 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9669 return libbpf_err_ptr(link_fd);
9675 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
9676 struct bpf_program *prog)
9678 return bpf_program__attach_iter(prog, NULL);
9681 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
9683 const struct bpf_sec_def *sec_def;
9685 sec_def = find_sec_def(prog->sec_name);
9686 if (!sec_def || !sec_def->attach_fn)
9687 return libbpf_err_ptr(-ESRCH);
9689 return sec_def->attach_fn(sec_def, prog);
9692 static int bpf_link__detach_struct_ops(struct bpf_link *link)
9696 if (bpf_map_delete_elem(link->fd, &zero))
9702 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
9704 struct bpf_struct_ops *st_ops;
9705 struct bpf_link *link;
9709 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
9710 return libbpf_err_ptr(-EINVAL);
9712 link = calloc(1, sizeof(*link));
9714 return libbpf_err_ptr(-EINVAL);
9716 st_ops = map->st_ops;
9717 for (i = 0; i < btf_vlen(st_ops->type); i++) {
9718 struct bpf_program *prog = st_ops->progs[i];
9725 prog_fd = bpf_program__fd(prog);
9726 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9727 *(unsigned long *)kern_data = prog_fd;
9730 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
9734 return libbpf_err_ptr(err);
9737 link->detach = bpf_link__detach_struct_ops;
9743 enum bpf_perf_event_ret
9744 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
9745 void **copy_mem, size_t *copy_size,
9746 bpf_perf_event_print_t fn, void *private_data)
9748 struct perf_event_mmap_page *header = mmap_mem;
9749 __u64 data_head = ring_buffer_read_head(header);
9750 __u64 data_tail = header->data_tail;
9751 void *base = ((__u8 *)header) + page_size;
9752 int ret = LIBBPF_PERF_EVENT_CONT;
9753 struct perf_event_header *ehdr;
9756 while (data_head != data_tail) {
9757 ehdr = base + (data_tail & (mmap_size - 1));
9758 ehdr_size = ehdr->size;
9760 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
9761 void *copy_start = ehdr;
9762 size_t len_first = base + mmap_size - copy_start;
9763 size_t len_secnd = ehdr_size - len_first;
9765 if (*copy_size < ehdr_size) {
9767 *copy_mem = malloc(ehdr_size);
9770 ret = LIBBPF_PERF_EVENT_ERROR;
9773 *copy_size = ehdr_size;
9776 memcpy(*copy_mem, copy_start, len_first);
9777 memcpy(*copy_mem + len_first, base, len_secnd);
9781 ret = fn(ehdr, private_data);
9782 data_tail += ehdr_size;
9783 if (ret != LIBBPF_PERF_EVENT_CONT)
9787 ring_buffer_write_tail(header, data_tail);
9788 return libbpf_err(ret);
9793 struct perf_buffer_params {
9794 struct perf_event_attr *attr;
9795 /* if event_cb is specified, it takes precendence */
9796 perf_buffer_event_fn event_cb;
9797 /* sample_cb and lost_cb are higher-level common-case callbacks */
9798 perf_buffer_sample_fn sample_cb;
9799 perf_buffer_lost_fn lost_cb;
9806 struct perf_cpu_buf {
9807 struct perf_buffer *pb;
9808 void *base; /* mmap()'ed memory */
9809 void *buf; /* for reconstructing segmented data */
9816 struct perf_buffer {
9817 perf_buffer_event_fn event_cb;
9818 perf_buffer_sample_fn sample_cb;
9819 perf_buffer_lost_fn lost_cb;
9820 void *ctx; /* passed into callbacks */
9824 struct perf_cpu_buf **cpu_bufs;
9825 struct epoll_event *events;
9826 int cpu_cnt; /* number of allocated CPU buffers */
9827 int epoll_fd; /* perf event FD */
9828 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
9831 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
9832 struct perf_cpu_buf *cpu_buf)
9836 if (cpu_buf->base &&
9837 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
9838 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
9839 if (cpu_buf->fd >= 0) {
9840 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
9847 void perf_buffer__free(struct perf_buffer *pb)
9851 if (IS_ERR_OR_NULL(pb))
9854 for (i = 0; i < pb->cpu_cnt; i++) {
9855 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
9860 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
9861 perf_buffer__free_cpu_buf(pb, cpu_buf);
9865 if (pb->epoll_fd >= 0)
9866 close(pb->epoll_fd);
9871 static struct perf_cpu_buf *
9872 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
9873 int cpu, int map_key)
9875 struct perf_cpu_buf *cpu_buf;
9876 char msg[STRERR_BUFSIZE];
9879 cpu_buf = calloc(1, sizeof(*cpu_buf));
9881 return ERR_PTR(-ENOMEM);
9885 cpu_buf->map_key = map_key;
9887 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
9888 -1, PERF_FLAG_FD_CLOEXEC);
9889 if (cpu_buf->fd < 0) {
9891 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
9892 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9896 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
9897 PROT_READ | PROT_WRITE, MAP_SHARED,
9899 if (cpu_buf->base == MAP_FAILED) {
9900 cpu_buf->base = NULL;
9902 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
9903 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9907 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9909 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
9910 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9917 perf_buffer__free_cpu_buf(pb, cpu_buf);
9918 return (struct perf_cpu_buf *)ERR_PTR(err);
9921 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
9922 struct perf_buffer_params *p);
9924 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
9925 const struct perf_buffer_opts *opts)
9927 struct perf_buffer_params p = {};
9928 struct perf_event_attr attr = { 0, };
9930 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
9931 attr.type = PERF_TYPE_SOFTWARE;
9932 attr.sample_type = PERF_SAMPLE_RAW;
9933 attr.sample_period = 1;
9934 attr.wakeup_events = 1;
9937 p.sample_cb = opts ? opts->sample_cb : NULL;
9938 p.lost_cb = opts ? opts->lost_cb : NULL;
9939 p.ctx = opts ? opts->ctx : NULL;
9941 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
9944 struct perf_buffer *
9945 perf_buffer__new_raw(int map_fd, size_t page_cnt,
9946 const struct perf_buffer_raw_opts *opts)
9948 struct perf_buffer_params p = {};
9950 p.attr = opts->attr;
9951 p.event_cb = opts->event_cb;
9953 p.cpu_cnt = opts->cpu_cnt;
9954 p.cpus = opts->cpus;
9955 p.map_keys = opts->map_keys;
9957 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
9960 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
9961 struct perf_buffer_params *p)
9963 const char *online_cpus_file = "/sys/devices/system/cpu/online";
9964 struct bpf_map_info map;
9965 char msg[STRERR_BUFSIZE];
9966 struct perf_buffer *pb;
9967 bool *online = NULL;
9971 if (page_cnt & (page_cnt - 1)) {
9972 pr_warn("page count should be power of two, but is %zu\n",
9974 return ERR_PTR(-EINVAL);
9977 /* best-effort sanity checks */
9978 memset(&map, 0, sizeof(map));
9979 map_info_len = sizeof(map);
9980 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
9983 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
9984 * -EBADFD, -EFAULT, or -E2BIG on real error
9986 if (err != -EINVAL) {
9987 pr_warn("failed to get map info for map FD %d: %s\n",
9988 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
9989 return ERR_PTR(err);
9991 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
9994 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
9995 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
9997 return ERR_PTR(-EINVAL);
10001 pb = calloc(1, sizeof(*pb));
10003 return ERR_PTR(-ENOMEM);
10005 pb->event_cb = p->event_cb;
10006 pb->sample_cb = p->sample_cb;
10007 pb->lost_cb = p->lost_cb;
10010 pb->page_size = getpagesize();
10011 pb->mmap_size = pb->page_size * page_cnt;
10012 pb->map_fd = map_fd;
10014 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
10015 if (pb->epoll_fd < 0) {
10017 pr_warn("failed to create epoll instance: %s\n",
10018 libbpf_strerror_r(err, msg, sizeof(msg)));
10022 if (p->cpu_cnt > 0) {
10023 pb->cpu_cnt = p->cpu_cnt;
10025 pb->cpu_cnt = libbpf_num_possible_cpus();
10026 if (pb->cpu_cnt < 0) {
10030 if (map.max_entries && map.max_entries < pb->cpu_cnt)
10031 pb->cpu_cnt = map.max_entries;
10034 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
10037 pr_warn("failed to allocate events: out of memory\n");
10040 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
10041 if (!pb->cpu_bufs) {
10043 pr_warn("failed to allocate buffers: out of memory\n");
10047 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
10049 pr_warn("failed to get online CPU mask: %d\n", err);
10053 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
10054 struct perf_cpu_buf *cpu_buf;
10057 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
10058 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
10060 /* in case user didn't explicitly requested particular CPUs to
10061 * be attached to, skip offline/not present CPUs
10063 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
10066 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
10067 if (IS_ERR(cpu_buf)) {
10068 err = PTR_ERR(cpu_buf);
10072 pb->cpu_bufs[j] = cpu_buf;
10074 err = bpf_map_update_elem(pb->map_fd, &map_key,
10078 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
10079 cpu, map_key, cpu_buf->fd,
10080 libbpf_strerror_r(err, msg, sizeof(msg)));
10084 pb->events[j].events = EPOLLIN;
10085 pb->events[j].data.ptr = cpu_buf;
10086 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
10087 &pb->events[j]) < 0) {
10089 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
10091 libbpf_strerror_r(err, msg, sizeof(msg)));
10104 perf_buffer__free(pb);
10105 return ERR_PTR(err);
10108 struct perf_sample_raw {
10109 struct perf_event_header header;
10114 struct perf_sample_lost {
10115 struct perf_event_header header;
10118 uint64_t sample_id;
10121 static enum bpf_perf_event_ret
10122 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
10124 struct perf_cpu_buf *cpu_buf = ctx;
10125 struct perf_buffer *pb = cpu_buf->pb;
10128 /* user wants full control over parsing perf event */
10130 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
10133 case PERF_RECORD_SAMPLE: {
10134 struct perf_sample_raw *s = data;
10137 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
10140 case PERF_RECORD_LOST: {
10141 struct perf_sample_lost *s = data;
10144 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
10148 pr_warn("unknown perf sample type %d\n", e->type);
10149 return LIBBPF_PERF_EVENT_ERROR;
10151 return LIBBPF_PERF_EVENT_CONT;
10154 static int perf_buffer__process_records(struct perf_buffer *pb,
10155 struct perf_cpu_buf *cpu_buf)
10157 enum bpf_perf_event_ret ret;
10159 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
10160 pb->page_size, &cpu_buf->buf,
10161 &cpu_buf->buf_size,
10162 perf_buffer__process_record, cpu_buf);
10163 if (ret != LIBBPF_PERF_EVENT_CONT)
10168 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
10170 return pb->epoll_fd;
10173 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
10177 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
10181 for (i = 0; i < cnt; i++) {
10182 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
10184 err = perf_buffer__process_records(pb, cpu_buf);
10186 pr_warn("error while processing records: %d\n", err);
10187 return libbpf_err(err);
10193 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
10196 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
10198 return pb->cpu_cnt;
10202 * Return perf_event FD of a ring buffer in *buf_idx* slot of
10203 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
10204 * select()/poll()/epoll() Linux syscalls.
10206 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
10208 struct perf_cpu_buf *cpu_buf;
10210 if (buf_idx >= pb->cpu_cnt)
10211 return libbpf_err(-EINVAL);
10213 cpu_buf = pb->cpu_bufs[buf_idx];
10215 return libbpf_err(-ENOENT);
10217 return cpu_buf->fd;
10221 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
10222 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
10223 * consume, do nothing and return success.
10228 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
10230 struct perf_cpu_buf *cpu_buf;
10232 if (buf_idx >= pb->cpu_cnt)
10233 return libbpf_err(-EINVAL);
10235 cpu_buf = pb->cpu_bufs[buf_idx];
10237 return libbpf_err(-ENOENT);
10239 return perf_buffer__process_records(pb, cpu_buf);
10242 int perf_buffer__consume(struct perf_buffer *pb)
10246 for (i = 0; i < pb->cpu_cnt; i++) {
10247 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10252 err = perf_buffer__process_records(pb, cpu_buf);
10254 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
10255 return libbpf_err(err);
10261 struct bpf_prog_info_array_desc {
10262 int array_offset; /* e.g. offset of jited_prog_insns */
10263 int count_offset; /* e.g. offset of jited_prog_len */
10264 int size_offset; /* > 0: offset of rec size,
10265 * < 0: fix size of -size_offset
10269 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
10270 [BPF_PROG_INFO_JITED_INSNS] = {
10271 offsetof(struct bpf_prog_info, jited_prog_insns),
10272 offsetof(struct bpf_prog_info, jited_prog_len),
10275 [BPF_PROG_INFO_XLATED_INSNS] = {
10276 offsetof(struct bpf_prog_info, xlated_prog_insns),
10277 offsetof(struct bpf_prog_info, xlated_prog_len),
10280 [BPF_PROG_INFO_MAP_IDS] = {
10281 offsetof(struct bpf_prog_info, map_ids),
10282 offsetof(struct bpf_prog_info, nr_map_ids),
10283 -(int)sizeof(__u32),
10285 [BPF_PROG_INFO_JITED_KSYMS] = {
10286 offsetof(struct bpf_prog_info, jited_ksyms),
10287 offsetof(struct bpf_prog_info, nr_jited_ksyms),
10288 -(int)sizeof(__u64),
10290 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
10291 offsetof(struct bpf_prog_info, jited_func_lens),
10292 offsetof(struct bpf_prog_info, nr_jited_func_lens),
10293 -(int)sizeof(__u32),
10295 [BPF_PROG_INFO_FUNC_INFO] = {
10296 offsetof(struct bpf_prog_info, func_info),
10297 offsetof(struct bpf_prog_info, nr_func_info),
10298 offsetof(struct bpf_prog_info, func_info_rec_size),
10300 [BPF_PROG_INFO_LINE_INFO] = {
10301 offsetof(struct bpf_prog_info, line_info),
10302 offsetof(struct bpf_prog_info, nr_line_info),
10303 offsetof(struct bpf_prog_info, line_info_rec_size),
10305 [BPF_PROG_INFO_JITED_LINE_INFO] = {
10306 offsetof(struct bpf_prog_info, jited_line_info),
10307 offsetof(struct bpf_prog_info, nr_jited_line_info),
10308 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
10310 [BPF_PROG_INFO_PROG_TAGS] = {
10311 offsetof(struct bpf_prog_info, prog_tags),
10312 offsetof(struct bpf_prog_info, nr_prog_tags),
10313 -(int)sizeof(__u8) * BPF_TAG_SIZE,
10318 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
10321 __u32 *array = (__u32 *)info;
10324 return array[offset / sizeof(__u32)];
10325 return -(int)offset;
10328 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
10331 __u64 *array = (__u64 *)info;
10334 return array[offset / sizeof(__u64)];
10335 return -(int)offset;
10338 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
10341 __u32 *array = (__u32 *)info;
10344 array[offset / sizeof(__u32)] = val;
10347 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
10350 __u64 *array = (__u64 *)info;
10353 array[offset / sizeof(__u64)] = val;
10356 struct bpf_prog_info_linear *
10357 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
10359 struct bpf_prog_info_linear *info_linear;
10360 struct bpf_prog_info info = {};
10361 __u32 info_len = sizeof(info);
10362 __u32 data_len = 0;
10366 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
10367 return libbpf_err_ptr(-EINVAL);
10369 /* step 1: get array dimensions */
10370 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
10372 pr_debug("can't get prog info: %s", strerror(errno));
10373 return libbpf_err_ptr(-EFAULT);
10376 /* step 2: calculate total size of all arrays */
10377 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10378 bool include_array = (arrays & (1UL << i)) > 0;
10379 struct bpf_prog_info_array_desc *desc;
10382 desc = bpf_prog_info_array_desc + i;
10384 /* kernel is too old to support this field */
10385 if (info_len < desc->array_offset + sizeof(__u32) ||
10386 info_len < desc->count_offset + sizeof(__u32) ||
10387 (desc->size_offset > 0 && info_len < desc->size_offset))
10388 include_array = false;
10390 if (!include_array) {
10391 arrays &= ~(1UL << i); /* clear the bit */
10395 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10396 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10398 data_len += count * size;
10401 /* step 3: allocate continuous memory */
10402 data_len = roundup(data_len, sizeof(__u64));
10403 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
10405 return libbpf_err_ptr(-ENOMEM);
10407 /* step 4: fill data to info_linear->info */
10408 info_linear->arrays = arrays;
10409 memset(&info_linear->info, 0, sizeof(info));
10410 ptr = info_linear->data;
10412 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10413 struct bpf_prog_info_array_desc *desc;
10416 if ((arrays & (1UL << i)) == 0)
10419 desc = bpf_prog_info_array_desc + i;
10420 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10421 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10422 bpf_prog_info_set_offset_u32(&info_linear->info,
10423 desc->count_offset, count);
10424 bpf_prog_info_set_offset_u32(&info_linear->info,
10425 desc->size_offset, size);
10426 bpf_prog_info_set_offset_u64(&info_linear->info,
10427 desc->array_offset,
10429 ptr += count * size;
10432 /* step 5: call syscall again to get required arrays */
10433 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
10435 pr_debug("can't get prog info: %s", strerror(errno));
10437 return libbpf_err_ptr(-EFAULT);
10440 /* step 6: verify the data */
10441 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10442 struct bpf_prog_info_array_desc *desc;
10445 if ((arrays & (1UL << i)) == 0)
10448 desc = bpf_prog_info_array_desc + i;
10449 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10450 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10451 desc->count_offset);
10453 pr_warn("%s: mismatch in element count\n", __func__);
10455 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10456 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10457 desc->size_offset);
10459 pr_warn("%s: mismatch in rec size\n", __func__);
10462 /* step 7: update info_len and data_len */
10463 info_linear->info_len = sizeof(struct bpf_prog_info);
10464 info_linear->data_len = data_len;
10466 return info_linear;
10469 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
10473 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10474 struct bpf_prog_info_array_desc *desc;
10477 if ((info_linear->arrays & (1UL << i)) == 0)
10480 desc = bpf_prog_info_array_desc + i;
10481 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
10482 desc->array_offset);
10483 offs = addr - ptr_to_u64(info_linear->data);
10484 bpf_prog_info_set_offset_u64(&info_linear->info,
10485 desc->array_offset, offs);
10489 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
10493 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10494 struct bpf_prog_info_array_desc *desc;
10497 if ((info_linear->arrays & (1UL << i)) == 0)
10500 desc = bpf_prog_info_array_desc + i;
10501 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
10502 desc->array_offset);
10503 addr = offs + ptr_to_u64(info_linear->data);
10504 bpf_prog_info_set_offset_u64(&info_linear->info,
10505 desc->array_offset, addr);
10509 int bpf_program__set_attach_target(struct bpf_program *prog,
10510 int attach_prog_fd,
10511 const char *attach_func_name)
10513 int btf_obj_fd = 0, btf_id = 0, err;
10515 if (!prog || attach_prog_fd < 0 || !attach_func_name)
10516 return libbpf_err(-EINVAL);
10518 if (prog->obj->loaded)
10519 return libbpf_err(-EINVAL);
10521 if (attach_prog_fd) {
10522 btf_id = libbpf_find_prog_btf_id(attach_func_name,
10525 return libbpf_err(btf_id);
10527 /* load btf_vmlinux, if not yet */
10528 err = bpf_object__load_vmlinux_btf(prog->obj, true);
10530 return libbpf_err(err);
10531 err = find_kernel_btf_id(prog->obj, attach_func_name,
10532 prog->expected_attach_type,
10533 &btf_obj_fd, &btf_id);
10535 return libbpf_err(err);
10538 prog->attach_btf_id = btf_id;
10539 prog->attach_btf_obj_fd = btf_obj_fd;
10540 prog->attach_prog_fd = attach_prog_fd;
10544 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
10546 int err = 0, n, len, start, end = -1;
10552 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
10554 if (*s == ',' || *s == '\n') {
10558 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
10559 if (n <= 0 || n > 2) {
10560 pr_warn("Failed to get CPU range %s: %d\n", s, n);
10563 } else if (n == 1) {
10566 if (start < 0 || start > end) {
10567 pr_warn("Invalid CPU range [%d,%d] in %s\n",
10572 tmp = realloc(*mask, end + 1);
10578 memset(tmp + *mask_sz, 0, start - *mask_sz);
10579 memset(tmp + start, 1, end - start + 1);
10580 *mask_sz = end + 1;
10584 pr_warn("Empty CPU range\n");
10594 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
10596 int fd, err = 0, len;
10599 fd = open(fcpu, O_RDONLY);
10602 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
10605 len = read(fd, buf, sizeof(buf));
10608 err = len ? -errno : -EINVAL;
10609 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
10612 if (len >= sizeof(buf)) {
10613 pr_warn("CPU mask is too big in file %s\n", fcpu);
10618 return parse_cpu_mask_str(buf, mask, mask_sz);
10621 int libbpf_num_possible_cpus(void)
10623 static const char *fcpu = "/sys/devices/system/cpu/possible";
10625 int err, n, i, tmp_cpus;
10628 tmp_cpus = READ_ONCE(cpus);
10632 err = parse_cpu_mask_file(fcpu, &mask, &n);
10634 return libbpf_err(err);
10637 for (i = 0; i < n; i++) {
10643 WRITE_ONCE(cpus, tmp_cpus);
10647 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
10648 const struct bpf_object_open_opts *opts)
10650 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
10651 .object_name = s->name,
10653 struct bpf_object *obj;
10656 /* Attempt to preserve opts->object_name, unless overriden by user
10657 * explicitly. Overwriting object name for skeletons is discouraged,
10658 * as it breaks global data maps, because they contain object name
10659 * prefix as their own map name prefix. When skeleton is generated,
10660 * bpftool is making an assumption that this name will stay the same.
10663 memcpy(&skel_opts, opts, sizeof(*opts));
10664 if (!opts->object_name)
10665 skel_opts.object_name = s->name;
10668 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
10669 err = libbpf_get_error(obj);
10671 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
10673 return libbpf_err(err);
10678 for (i = 0; i < s->map_cnt; i++) {
10679 struct bpf_map **map = s->maps[i].map;
10680 const char *name = s->maps[i].name;
10681 void **mmaped = s->maps[i].mmaped;
10683 *map = bpf_object__find_map_by_name(obj, name);
10685 pr_warn("failed to find skeleton map '%s'\n", name);
10686 return libbpf_err(-ESRCH);
10689 /* externs shouldn't be pre-setup from user code */
10690 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
10691 *mmaped = (*map)->mmaped;
10694 for (i = 0; i < s->prog_cnt; i++) {
10695 struct bpf_program **prog = s->progs[i].prog;
10696 const char *name = s->progs[i].name;
10698 *prog = bpf_object__find_program_by_name(obj, name);
10700 pr_warn("failed to find skeleton program '%s'\n", name);
10701 return libbpf_err(-ESRCH);
10708 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
10712 err = bpf_object__load(*s->obj);
10714 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
10715 return libbpf_err(err);
10718 for (i = 0; i < s->map_cnt; i++) {
10719 struct bpf_map *map = *s->maps[i].map;
10720 size_t mmap_sz = bpf_map_mmap_sz(map);
10721 int prot, map_fd = bpf_map__fd(map);
10722 void **mmaped = s->maps[i].mmaped;
10727 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
10732 if (map->def.map_flags & BPF_F_RDONLY_PROG)
10735 prot = PROT_READ | PROT_WRITE;
10737 /* Remap anonymous mmap()-ed "map initialization image" as
10738 * a BPF map-backed mmap()-ed memory, but preserving the same
10739 * memory address. This will cause kernel to change process'
10740 * page table to point to a different piece of kernel memory,
10741 * but from userspace point of view memory address (and its
10742 * contents, being identical at this point) will stay the
10743 * same. This mapping will be released by bpf_object__close()
10744 * as per normal clean up procedure, so we don't need to worry
10745 * about it from skeleton's clean up perspective.
10747 *mmaped = mmap(map->mmaped, mmap_sz, prot,
10748 MAP_SHARED | MAP_FIXED, map_fd, 0);
10749 if (*mmaped == MAP_FAILED) {
10752 pr_warn("failed to re-mmap() map '%s': %d\n",
10753 bpf_map__name(map), err);
10754 return libbpf_err(err);
10761 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
10765 for (i = 0; i < s->prog_cnt; i++) {
10766 struct bpf_program *prog = *s->progs[i].prog;
10767 struct bpf_link **link = s->progs[i].link;
10768 const struct bpf_sec_def *sec_def;
10773 sec_def = find_sec_def(prog->sec_name);
10774 if (!sec_def || !sec_def->attach_fn)
10777 *link = sec_def->attach_fn(sec_def, prog);
10778 err = libbpf_get_error(*link);
10780 pr_warn("failed to auto-attach program '%s': %d\n",
10781 bpf_program__name(prog), err);
10782 return libbpf_err(err);
10789 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
10793 for (i = 0; i < s->prog_cnt; i++) {
10794 struct bpf_link **link = s->progs[i].link;
10796 bpf_link__destroy(*link);
10801 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
10804 bpf_object__detach_skeleton(s);
10806 bpf_object__close(*s->obj);