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 */
199 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
211 enum reloc_type type;
219 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
220 struct bpf_program *prog);
225 enum bpf_prog_type prog_type;
226 enum bpf_attach_type expected_attach_type;
227 bool is_exp_attach_type_optional;
231 attach_fn_t attach_fn;
235 * bpf_prog should be a better name but it has been used in
239 const struct bpf_sec_def *sec_def;
242 /* this program's instruction offset (in number of instructions)
243 * within its containing ELF section
246 /* number of original instructions in ELF section belonging to this
247 * program, not taking into account subprogram instructions possible
248 * appended later during relocation
251 /* Offset (in number of instructions) of the start of instruction
252 * belonging to this BPF program within its containing main BPF
253 * program. For the entry-point (main) BPF program, this is always
254 * zero. For a sub-program, this gets reset before each of main BPF
255 * programs are processed and relocated and is used to determined
256 * whether sub-program was already appended to the main program, and
257 * if yes, at which instruction offset.
262 /* sec_name with / replaced by _; makes recursive pinning
263 * in bpf_object__pin_programs easier
267 /* instructions that belong to BPF program; insns[0] is located at
268 * sec_insn_off instruction within its ELF section in ELF file, so
269 * when mapping ELF file instruction index to the local instruction,
270 * one needs to subtract sec_insn_off; and vice versa.
272 struct bpf_insn *insns;
273 /* actual number of instruction in this BPF program's image; for
274 * entry-point BPF programs this includes the size of main program
275 * itself plus all the used sub-programs, appended at the end
279 struct reloc_desc *reloc_desc;
287 bpf_program_prep_t preprocessor;
289 struct bpf_object *obj;
291 bpf_program_clear_priv_t clear_priv;
294 bool mark_btf_static;
295 enum bpf_prog_type type;
296 enum bpf_attach_type expected_attach_type;
298 __u32 attach_btf_obj_fd;
300 __u32 attach_prog_fd;
302 __u32 func_info_rec_size;
306 __u32 line_info_rec_size;
311 struct bpf_struct_ops {
313 const struct btf_type *type;
314 struct bpf_program **progs;
315 __u32 *kern_func_off;
316 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
318 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
319 * btf_vmlinux's format.
320 * struct bpf_struct_ops_tcp_congestion_ops {
321 * [... some other kernel fields ...]
322 * struct tcp_congestion_ops data;
324 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
325 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
332 #define DATA_SEC ".data"
333 #define BSS_SEC ".bss"
334 #define RODATA_SEC ".rodata"
335 #define KCONFIG_SEC ".kconfig"
336 #define KSYMS_SEC ".ksyms"
337 #define STRUCT_OPS_SEC ".struct_ops"
339 enum libbpf_map_type {
347 static const char * const libbpf_type_to_btf_name[] = {
348 [LIBBPF_MAP_DATA] = DATA_SEC,
349 [LIBBPF_MAP_BSS] = BSS_SEC,
350 [LIBBPF_MAP_RODATA] = RODATA_SEC,
351 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
361 struct bpf_map_def def;
364 __u32 btf_key_type_id;
365 __u32 btf_value_type_id;
366 __u32 btf_vmlinux_value_type_id;
368 bpf_map_clear_priv_t clear_priv;
369 enum libbpf_map_type libbpf_type;
371 struct bpf_struct_ops *st_ops;
372 struct bpf_map *inner_map;
396 enum extern_type type;
412 unsigned long long addr;
414 /* target btf_id of the corresponding kernel var. */
415 int kernel_btf_obj_fd;
418 /* local btf_id of the ksym extern's type. */
424 static LIST_HEAD(bpf_objects_list);
434 char name[BPF_OBJ_NAME_LEN];
438 struct bpf_program *programs;
440 struct bpf_map *maps;
445 struct extern_desc *externs;
453 struct bpf_gen *gen_loader;
456 * Information when doing elf related work. Only valid if fd
469 Elf_Data *st_ops_data;
470 size_t shstrndx; /* section index for section name strings */
479 __u32 btf_maps_sec_btf_id;
488 * All loaded bpf_object is linked in a list, which is
489 * hidden to caller. bpf_objects__<func> handlers deal with
492 struct list_head list;
495 struct btf_ext *btf_ext;
497 /* Parse and load BTF vmlinux if any of the programs in the object need
500 struct btf *btf_vmlinux;
501 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
502 * override for vmlinux BTF.
504 char *btf_custom_path;
505 /* vmlinux BTF override for CO-RE relocations */
506 struct btf *btf_vmlinux_override;
507 /* Lazily initialized kernel module BTFs */
508 struct module_btf *btf_modules;
509 bool btf_modules_loaded;
510 size_t btf_module_cnt;
511 size_t btf_module_cap;
514 bpf_object_clear_priv_t clear_priv;
518 #define obj_elf_valid(o) ((o)->efile.elf)
520 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
521 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
522 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
523 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
524 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr);
525 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
526 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
528 void bpf_program__unload(struct bpf_program *prog)
536 * If the object is opened but the program was never loaded,
537 * it is possible that prog->instances.nr == -1.
539 if (prog->instances.nr > 0) {
540 for (i = 0; i < prog->instances.nr; i++)
541 zclose(prog->instances.fds[i]);
542 } else if (prog->instances.nr != -1) {
543 pr_warn("Internal error: instances.nr is %d\n",
547 prog->instances.nr = -1;
548 zfree(&prog->instances.fds);
550 zfree(&prog->func_info);
551 zfree(&prog->line_info);
554 static void bpf_program__exit(struct bpf_program *prog)
559 if (prog->clear_priv)
560 prog->clear_priv(prog, prog->priv);
563 prog->clear_priv = NULL;
565 bpf_program__unload(prog);
567 zfree(&prog->sec_name);
568 zfree(&prog->pin_name);
570 zfree(&prog->reloc_desc);
577 static char *__bpf_program__pin_name(struct bpf_program *prog)
581 name = p = strdup(prog->sec_name);
582 while ((p = strchr(p, '/')))
588 static bool insn_is_subprog_call(const struct bpf_insn *insn)
590 return BPF_CLASS(insn->code) == BPF_JMP &&
591 BPF_OP(insn->code) == BPF_CALL &&
592 BPF_SRC(insn->code) == BPF_K &&
593 insn->src_reg == BPF_PSEUDO_CALL &&
594 insn->dst_reg == 0 &&
598 static bool is_call_insn(const struct bpf_insn *insn)
600 return insn->code == (BPF_JMP | BPF_CALL);
603 static bool insn_is_pseudo_func(struct bpf_insn *insn)
605 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
609 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
610 const char *name, size_t sec_idx, const char *sec_name,
611 size_t sec_off, void *insn_data, size_t insn_data_sz)
613 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
614 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
615 sec_name, name, sec_off, insn_data_sz);
619 memset(prog, 0, sizeof(*prog));
622 prog->sec_idx = sec_idx;
623 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
624 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
625 /* insns_cnt can later be increased by appending used subprograms */
626 prog->insns_cnt = prog->sec_insn_cnt;
628 prog->type = BPF_PROG_TYPE_UNSPEC;
631 prog->instances.fds = NULL;
632 prog->instances.nr = -1;
634 prog->sec_name = strdup(sec_name);
638 prog->name = strdup(name);
642 prog->pin_name = __bpf_program__pin_name(prog);
646 prog->insns = malloc(insn_data_sz);
649 memcpy(prog->insns, insn_data, insn_data_sz);
653 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
654 bpf_program__exit(prog);
659 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
660 const char *sec_name, int sec_idx)
662 Elf_Data *symbols = obj->efile.symbols;
663 struct bpf_program *prog, *progs;
664 void *data = sec_data->d_buf;
665 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
666 int nr_progs, err, i;
670 progs = obj->programs;
671 nr_progs = obj->nr_programs;
672 nr_syms = symbols->d_size / sizeof(GElf_Sym);
675 for (i = 0; i < nr_syms; i++) {
676 if (!gelf_getsym(symbols, i, &sym))
678 if (sym.st_shndx != sec_idx)
680 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
683 prog_sz = sym.st_size;
684 sec_off = sym.st_value;
686 name = elf_sym_str(obj, sym.st_name);
688 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
690 return -LIBBPF_ERRNO__FORMAT;
693 if (sec_off + prog_sz > sec_sz) {
694 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
696 return -LIBBPF_ERRNO__FORMAT;
699 if (sec_idx != obj->efile.text_shndx && GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
700 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
704 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
705 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
707 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
710 * In this case the original obj->programs
711 * is still valid, so don't need special treat for
712 * bpf_close_object().
714 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
718 obj->programs = progs;
720 prog = &progs[nr_progs];
722 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
723 sec_off, data + sec_off, prog_sz);
727 /* if function is a global/weak symbol, but has restricted
728 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
729 * as static to enable more permissive BPF verification mode
730 * with more outside context available to BPF verifier
732 if (GELF_ST_BIND(sym.st_info) != STB_LOCAL
733 && (GELF_ST_VISIBILITY(sym.st_other) == STV_HIDDEN
734 || GELF_ST_VISIBILITY(sym.st_other) == STV_INTERNAL))
735 prog->mark_btf_static = true;
738 obj->nr_programs = nr_progs;
744 static __u32 get_kernel_version(void)
746 __u32 major, minor, patch;
750 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
752 return KERNEL_VERSION(major, minor, patch);
755 static const struct btf_member *
756 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
758 struct btf_member *m;
761 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
762 if (btf_member_bit_offset(t, i) == bit_offset)
769 static const struct btf_member *
770 find_member_by_name(const struct btf *btf, const struct btf_type *t,
773 struct btf_member *m;
776 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
777 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
784 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
785 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
786 const char *name, __u32 kind);
789 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
790 const struct btf_type **type, __u32 *type_id,
791 const struct btf_type **vtype, __u32 *vtype_id,
792 const struct btf_member **data_member)
794 const struct btf_type *kern_type, *kern_vtype;
795 const struct btf_member *kern_data_member;
796 __s32 kern_vtype_id, kern_type_id;
799 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
800 if (kern_type_id < 0) {
801 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
805 kern_type = btf__type_by_id(btf, kern_type_id);
807 /* Find the corresponding "map_value" type that will be used
808 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
809 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
812 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
813 tname, BTF_KIND_STRUCT);
814 if (kern_vtype_id < 0) {
815 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
816 STRUCT_OPS_VALUE_PREFIX, tname);
817 return kern_vtype_id;
819 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
821 /* Find "struct tcp_congestion_ops" from
822 * struct bpf_struct_ops_tcp_congestion_ops {
824 * struct tcp_congestion_ops data;
827 kern_data_member = btf_members(kern_vtype);
828 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
829 if (kern_data_member->type == kern_type_id)
832 if (i == btf_vlen(kern_vtype)) {
833 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
834 tname, STRUCT_OPS_VALUE_PREFIX, tname);
839 *type_id = kern_type_id;
841 *vtype_id = kern_vtype_id;
842 *data_member = kern_data_member;
847 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
849 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
852 /* Init the map's fields that depend on kern_btf */
853 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
854 const struct btf *btf,
855 const struct btf *kern_btf)
857 const struct btf_member *member, *kern_member, *kern_data_member;
858 const struct btf_type *type, *kern_type, *kern_vtype;
859 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
860 struct bpf_struct_ops *st_ops;
861 void *data, *kern_data;
865 st_ops = map->st_ops;
867 tname = st_ops->tname;
868 err = find_struct_ops_kern_types(kern_btf, tname,
869 &kern_type, &kern_type_id,
870 &kern_vtype, &kern_vtype_id,
875 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
876 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
878 map->def.value_size = kern_vtype->size;
879 map->btf_vmlinux_value_type_id = kern_vtype_id;
881 st_ops->kern_vdata = calloc(1, kern_vtype->size);
882 if (!st_ops->kern_vdata)
886 kern_data_off = kern_data_member->offset / 8;
887 kern_data = st_ops->kern_vdata + kern_data_off;
889 member = btf_members(type);
890 for (i = 0; i < btf_vlen(type); i++, member++) {
891 const struct btf_type *mtype, *kern_mtype;
892 __u32 mtype_id, kern_mtype_id;
893 void *mdata, *kern_mdata;
894 __s64 msize, kern_msize;
895 __u32 moff, kern_moff;
896 __u32 kern_member_idx;
899 mname = btf__name_by_offset(btf, member->name_off);
900 kern_member = find_member_by_name(kern_btf, kern_type, mname);
902 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
907 kern_member_idx = kern_member - btf_members(kern_type);
908 if (btf_member_bitfield_size(type, i) ||
909 btf_member_bitfield_size(kern_type, kern_member_idx)) {
910 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
915 moff = member->offset / 8;
916 kern_moff = kern_member->offset / 8;
919 kern_mdata = kern_data + kern_moff;
921 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
922 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
924 if (BTF_INFO_KIND(mtype->info) !=
925 BTF_INFO_KIND(kern_mtype->info)) {
926 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
927 map->name, mname, BTF_INFO_KIND(mtype->info),
928 BTF_INFO_KIND(kern_mtype->info));
932 if (btf_is_ptr(mtype)) {
933 struct bpf_program *prog;
935 prog = st_ops->progs[i];
939 kern_mtype = skip_mods_and_typedefs(kern_btf,
943 /* mtype->type must be a func_proto which was
944 * guaranteed in bpf_object__collect_st_ops_relos(),
945 * so only check kern_mtype for func_proto here.
947 if (!btf_is_func_proto(kern_mtype)) {
948 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
953 prog->attach_btf_id = kern_type_id;
954 prog->expected_attach_type = kern_member_idx;
956 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
958 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
959 map->name, mname, prog->name, moff,
965 msize = btf__resolve_size(btf, mtype_id);
966 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
967 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
968 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
969 map->name, mname, (ssize_t)msize,
970 (ssize_t)kern_msize);
974 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
975 map->name, mname, (unsigned int)msize,
977 memcpy(kern_mdata, mdata, msize);
983 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
989 for (i = 0; i < obj->nr_maps; i++) {
992 if (!bpf_map__is_struct_ops(map))
995 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1004 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1006 const struct btf_type *type, *datasec;
1007 const struct btf_var_secinfo *vsi;
1008 struct bpf_struct_ops *st_ops;
1009 const char *tname, *var_name;
1010 __s32 type_id, datasec_id;
1011 const struct btf *btf;
1012 struct bpf_map *map;
1015 if (obj->efile.st_ops_shndx == -1)
1019 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1021 if (datasec_id < 0) {
1022 pr_warn("struct_ops init: DATASEC %s not found\n",
1027 datasec = btf__type_by_id(btf, datasec_id);
1028 vsi = btf_var_secinfos(datasec);
1029 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1030 type = btf__type_by_id(obj->btf, vsi->type);
1031 var_name = btf__name_by_offset(obj->btf, type->name_off);
1033 type_id = btf__resolve_type(obj->btf, vsi->type);
1035 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1036 vsi->type, STRUCT_OPS_SEC);
1040 type = btf__type_by_id(obj->btf, type_id);
1041 tname = btf__name_by_offset(obj->btf, type->name_off);
1043 pr_warn("struct_ops init: anonymous type is not supported\n");
1046 if (!btf_is_struct(type)) {
1047 pr_warn("struct_ops init: %s is not a struct\n", tname);
1051 map = bpf_object__add_map(obj);
1053 return PTR_ERR(map);
1055 map->sec_idx = obj->efile.st_ops_shndx;
1056 map->sec_offset = vsi->offset;
1057 map->name = strdup(var_name);
1061 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1062 map->def.key_size = sizeof(int);
1063 map->def.value_size = type->size;
1064 map->def.max_entries = 1;
1066 map->st_ops = calloc(1, sizeof(*map->st_ops));
1069 st_ops = map->st_ops;
1070 st_ops->data = malloc(type->size);
1071 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1072 st_ops->kern_func_off = malloc(btf_vlen(type) *
1073 sizeof(*st_ops->kern_func_off));
1074 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1077 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1078 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1079 var_name, STRUCT_OPS_SEC);
1083 memcpy(st_ops->data,
1084 obj->efile.st_ops_data->d_buf + vsi->offset,
1086 st_ops->tname = tname;
1087 st_ops->type = type;
1088 st_ops->type_id = type_id;
1090 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1091 tname, type_id, var_name, vsi->offset);
1097 static struct bpf_object *bpf_object__new(const char *path,
1098 const void *obj_buf,
1100 const char *obj_name)
1102 struct bpf_object *obj;
1105 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1107 pr_warn("alloc memory failed for %s\n", path);
1108 return ERR_PTR(-ENOMEM);
1111 strcpy(obj->path, path);
1113 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1114 obj->name[sizeof(obj->name) - 1] = 0;
1116 /* Using basename() GNU version which doesn't modify arg. */
1117 strncpy(obj->name, basename((void *)path),
1118 sizeof(obj->name) - 1);
1119 end = strchr(obj->name, '.');
1126 * Caller of this function should also call
1127 * bpf_object__elf_finish() after data collection to return
1128 * obj_buf to user. If not, we should duplicate the buffer to
1129 * avoid user freeing them before elf finish.
1131 obj->efile.obj_buf = obj_buf;
1132 obj->efile.obj_buf_sz = obj_buf_sz;
1133 obj->efile.maps_shndx = -1;
1134 obj->efile.btf_maps_shndx = -1;
1135 obj->efile.data_shndx = -1;
1136 obj->efile.rodata_shndx = -1;
1137 obj->efile.bss_shndx = -1;
1138 obj->efile.st_ops_shndx = -1;
1139 obj->kconfig_map_idx = -1;
1140 obj->rodata_map_idx = -1;
1142 obj->kern_version = get_kernel_version();
1143 obj->loaded = false;
1145 INIT_LIST_HEAD(&obj->list);
1146 list_add(&obj->list, &bpf_objects_list);
1150 static void bpf_object__elf_finish(struct bpf_object *obj)
1152 if (!obj_elf_valid(obj))
1155 if (obj->efile.elf) {
1156 elf_end(obj->efile.elf);
1157 obj->efile.elf = NULL;
1159 obj->efile.symbols = NULL;
1160 obj->efile.data = NULL;
1161 obj->efile.rodata = NULL;
1162 obj->efile.bss = NULL;
1163 obj->efile.st_ops_data = NULL;
1165 zfree(&obj->efile.reloc_sects);
1166 obj->efile.nr_reloc_sects = 0;
1167 zclose(obj->efile.fd);
1168 obj->efile.obj_buf = NULL;
1169 obj->efile.obj_buf_sz = 0;
1172 static int bpf_object__elf_init(struct bpf_object *obj)
1177 if (obj_elf_valid(obj)) {
1178 pr_warn("elf: init internal error\n");
1179 return -LIBBPF_ERRNO__LIBELF;
1182 if (obj->efile.obj_buf_sz > 0) {
1184 * obj_buf should have been validated by
1185 * bpf_object__open_buffer().
1187 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1188 obj->efile.obj_buf_sz);
1190 obj->efile.fd = open(obj->path, O_RDONLY);
1191 if (obj->efile.fd < 0) {
1192 char errmsg[STRERR_BUFSIZE], *cp;
1195 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1196 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1200 obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1203 if (!obj->efile.elf) {
1204 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1205 err = -LIBBPF_ERRNO__LIBELF;
1209 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1210 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1211 err = -LIBBPF_ERRNO__FORMAT;
1214 ep = &obj->efile.ehdr;
1216 if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) {
1217 pr_warn("elf: failed to get section names section index for %s: %s\n",
1218 obj->path, elf_errmsg(-1));
1219 err = -LIBBPF_ERRNO__FORMAT;
1223 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1224 if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) {
1225 pr_warn("elf: failed to get section names strings from %s: %s\n",
1226 obj->path, elf_errmsg(-1));
1227 err = -LIBBPF_ERRNO__FORMAT;
1231 /* Old LLVM set e_machine to EM_NONE */
1232 if (ep->e_type != ET_REL ||
1233 (ep->e_machine && ep->e_machine != EM_BPF)) {
1234 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1235 err = -LIBBPF_ERRNO__FORMAT;
1241 bpf_object__elf_finish(obj);
1245 static int bpf_object__check_endianness(struct bpf_object *obj)
1247 #if __BYTE_ORDER == __LITTLE_ENDIAN
1248 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1250 #elif __BYTE_ORDER == __BIG_ENDIAN
1251 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1254 # error "Unrecognized __BYTE_ORDER__"
1256 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1257 return -LIBBPF_ERRNO__ENDIAN;
1261 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1263 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1264 pr_debug("license of %s is %s\n", obj->path, obj->license);
1269 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1273 if (size != sizeof(kver)) {
1274 pr_warn("invalid kver section in %s\n", obj->path);
1275 return -LIBBPF_ERRNO__FORMAT;
1277 memcpy(&kver, data, sizeof(kver));
1278 obj->kern_version = kver;
1279 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1283 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1285 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1286 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1291 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1299 } else if (!strcmp(name, DATA_SEC)) {
1300 if (obj->efile.data)
1301 *size = obj->efile.data->d_size;
1302 } else if (!strcmp(name, BSS_SEC)) {
1304 *size = obj->efile.bss->d_size;
1305 } else if (!strcmp(name, RODATA_SEC)) {
1306 if (obj->efile.rodata)
1307 *size = obj->efile.rodata->d_size;
1308 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1309 if (obj->efile.st_ops_data)
1310 *size = obj->efile.st_ops_data->d_size;
1312 Elf_Scn *scn = elf_sec_by_name(obj, name);
1313 Elf_Data *data = elf_sec_data(obj, scn);
1316 ret = 0; /* found it */
1317 *size = data->d_size;
1321 return *size ? 0 : ret;
1324 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1327 Elf_Data *symbols = obj->efile.symbols;
1334 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1337 if (!gelf_getsym(symbols, si, &sym))
1339 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1340 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1343 sname = elf_sym_str(obj, sym.st_name);
1345 pr_warn("failed to get sym name string for var %s\n",
1349 if (strcmp(name, sname) == 0) {
1350 *off = sym.st_value;
1358 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1360 struct bpf_map *new_maps;
1364 if (obj->nr_maps < obj->maps_cap)
1365 return &obj->maps[obj->nr_maps++];
1367 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1368 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1370 pr_warn("alloc maps for object failed\n");
1371 return ERR_PTR(-ENOMEM);
1374 obj->maps_cap = new_cap;
1375 obj->maps = new_maps;
1377 /* zero out new maps */
1378 memset(obj->maps + obj->nr_maps, 0,
1379 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1381 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1382 * when failure (zclose won't close negative fd)).
1384 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1385 obj->maps[i].fd = -1;
1386 obj->maps[i].inner_map_fd = -1;
1389 return &obj->maps[obj->nr_maps++];
1392 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1394 long page_sz = sysconf(_SC_PAGE_SIZE);
1397 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1398 map_sz = roundup(map_sz, page_sz);
1402 static char *internal_map_name(struct bpf_object *obj,
1403 enum libbpf_map_type type)
1405 char map_name[BPF_OBJ_NAME_LEN], *p;
1406 const char *sfx = libbpf_type_to_btf_name[type];
1407 int sfx_len = max((size_t)7, strlen(sfx));
1408 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1411 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1412 sfx_len, libbpf_type_to_btf_name[type]);
1414 /* sanitise map name to characters allowed by kernel */
1415 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1416 if (!isalnum(*p) && *p != '_' && *p != '.')
1419 return strdup(map_name);
1423 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1424 int sec_idx, void *data, size_t data_sz)
1426 struct bpf_map_def *def;
1427 struct bpf_map *map;
1430 map = bpf_object__add_map(obj);
1432 return PTR_ERR(map);
1434 map->libbpf_type = type;
1435 map->sec_idx = sec_idx;
1436 map->sec_offset = 0;
1437 map->name = internal_map_name(obj, type);
1439 pr_warn("failed to alloc map name\n");
1444 def->type = BPF_MAP_TYPE_ARRAY;
1445 def->key_size = sizeof(int);
1446 def->value_size = data_sz;
1447 def->max_entries = 1;
1448 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1449 ? BPF_F_RDONLY_PROG : 0;
1450 def->map_flags |= BPF_F_MMAPABLE;
1452 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1453 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1455 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1456 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1457 if (map->mmaped == MAP_FAILED) {
1460 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1467 memcpy(map->mmaped, data, data_sz);
1469 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1473 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1478 * Populate obj->maps with libbpf internal maps.
1480 if (obj->efile.data_shndx >= 0) {
1481 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1482 obj->efile.data_shndx,
1483 obj->efile.data->d_buf,
1484 obj->efile.data->d_size);
1488 if (obj->efile.rodata_shndx >= 0) {
1489 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1490 obj->efile.rodata_shndx,
1491 obj->efile.rodata->d_buf,
1492 obj->efile.rodata->d_size);
1496 obj->rodata_map_idx = obj->nr_maps - 1;
1498 if (obj->efile.bss_shndx >= 0) {
1499 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1500 obj->efile.bss_shndx,
1502 obj->efile.bss->d_size);
1510 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1515 for (i = 0; i < obj->nr_extern; i++) {
1516 if (strcmp(obj->externs[i].name, name) == 0)
1517 return &obj->externs[i];
1522 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1525 switch (ext->kcfg.type) {
1528 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1532 *(bool *)ext_val = value == 'y' ? true : false;
1536 *(enum libbpf_tristate *)ext_val = TRI_YES;
1537 else if (value == 'm')
1538 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1539 else /* value == 'n' */
1540 *(enum libbpf_tristate *)ext_val = TRI_NO;
1543 *(char *)ext_val = value;
1549 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1557 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1562 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1563 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1567 len = strlen(value);
1568 if (value[len - 1] != '"') {
1569 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1576 if (len >= ext->kcfg.sz) {
1577 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1578 ext->name, value, len, ext->kcfg.sz - 1);
1579 len = ext->kcfg.sz - 1;
1581 memcpy(ext_val, value + 1, len);
1582 ext_val[len] = '\0';
1587 static int parse_u64(const char *value, __u64 *res)
1593 *res = strtoull(value, &value_end, 0);
1596 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1600 pr_warn("failed to parse '%s' as integer completely\n", value);
1606 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1608 int bit_sz = ext->kcfg.sz * 8;
1610 if (ext->kcfg.sz == 8)
1613 /* Validate that value stored in u64 fits in integer of `ext->sz`
1614 * bytes size without any loss of information. If the target integer
1615 * is signed, we rely on the following limits of integer type of
1616 * Y bits and subsequent transformation:
1618 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1619 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1620 * 0 <= X + 2^(Y-1) < 2^Y
1622 * For unsigned target integer, check that all the (64 - Y) bits are
1625 if (ext->kcfg.is_signed)
1626 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1628 return (v >> bit_sz) == 0;
1631 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1634 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1635 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1636 ext->name, (unsigned long long)value);
1639 if (!is_kcfg_value_in_range(ext, value)) {
1640 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1641 ext->name, (unsigned long long)value, ext->kcfg.sz);
1644 switch (ext->kcfg.sz) {
1645 case 1: *(__u8 *)ext_val = value; break;
1646 case 2: *(__u16 *)ext_val = value; break;
1647 case 4: *(__u32 *)ext_val = value; break;
1648 case 8: *(__u64 *)ext_val = value; break;
1656 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1657 char *buf, void *data)
1659 struct extern_desc *ext;
1665 if (strncmp(buf, "CONFIG_", 7))
1668 sep = strchr(buf, '=');
1670 pr_warn("failed to parse '%s': no separator\n", buf);
1674 /* Trim ending '\n' */
1676 if (buf[len - 1] == '\n')
1677 buf[len - 1] = '\0';
1678 /* Split on '=' and ensure that a value is present. */
1682 pr_warn("failed to parse '%s': no value\n", buf);
1686 ext = find_extern_by_name(obj, buf);
1687 if (!ext || ext->is_set)
1690 ext_val = data + ext->kcfg.data_off;
1694 case 'y': case 'n': case 'm':
1695 err = set_kcfg_value_tri(ext, ext_val, *value);
1698 err = set_kcfg_value_str(ext, ext_val, value);
1701 /* assume integer */
1702 err = parse_u64(value, &num);
1704 pr_warn("extern (kcfg) %s=%s should be integer\n",
1708 err = set_kcfg_value_num(ext, ext_val, num);
1713 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1717 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1725 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1728 else if (len >= PATH_MAX)
1729 return -ENAMETOOLONG;
1731 /* gzopen also accepts uncompressed files. */
1732 file = gzopen(buf, "r");
1734 file = gzopen("/proc/config.gz", "r");
1737 pr_warn("failed to open system Kconfig\n");
1741 while (gzgets(file, buf, sizeof(buf))) {
1742 err = bpf_object__process_kconfig_line(obj, buf, data);
1744 pr_warn("error parsing system Kconfig line '%s': %d\n",
1755 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1756 const char *config, void *data)
1762 file = fmemopen((void *)config, strlen(config), "r");
1765 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1769 while (fgets(buf, sizeof(buf), file)) {
1770 err = bpf_object__process_kconfig_line(obj, buf, data);
1772 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1782 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1784 struct extern_desc *last_ext = NULL, *ext;
1788 for (i = 0; i < obj->nr_extern; i++) {
1789 ext = &obj->externs[i];
1790 if (ext->type == EXT_KCFG)
1797 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1798 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1799 obj->efile.symbols_shndx,
1804 obj->kconfig_map_idx = obj->nr_maps - 1;
1809 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1811 Elf_Data *symbols = obj->efile.symbols;
1812 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1813 Elf_Data *data = NULL;
1816 if (obj->efile.maps_shndx < 0)
1822 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1823 data = elf_sec_data(obj, scn);
1824 if (!scn || !data) {
1825 pr_warn("elf: failed to get legacy map definitions for %s\n",
1831 * Count number of maps. Each map has a name.
1832 * Array of maps is not supported: only the first element is
1835 * TODO: Detect array of map and report error.
1837 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1838 for (i = 0; i < nr_syms; i++) {
1841 if (!gelf_getsym(symbols, i, &sym))
1843 if (sym.st_shndx != obj->efile.maps_shndx)
1847 /* Assume equally sized map definitions */
1848 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1849 nr_maps, data->d_size, obj->path);
1851 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1852 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1856 map_def_sz = data->d_size / nr_maps;
1858 /* Fill obj->maps using data in "maps" section. */
1859 for (i = 0; i < nr_syms; i++) {
1861 const char *map_name;
1862 struct bpf_map_def *def;
1863 struct bpf_map *map;
1865 if (!gelf_getsym(symbols, i, &sym))
1867 if (sym.st_shndx != obj->efile.maps_shndx)
1870 map = bpf_object__add_map(obj);
1872 return PTR_ERR(map);
1874 map_name = elf_sym_str(obj, sym.st_name);
1876 pr_warn("failed to get map #%d name sym string for obj %s\n",
1878 return -LIBBPF_ERRNO__FORMAT;
1881 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION
1882 || GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
1883 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
1887 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1888 map->sec_idx = sym.st_shndx;
1889 map->sec_offset = sym.st_value;
1890 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1891 map_name, map->sec_idx, map->sec_offset);
1892 if (sym.st_value + map_def_sz > data->d_size) {
1893 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1894 obj->path, map_name);
1898 map->name = strdup(map_name);
1900 pr_warn("failed to alloc map name\n");
1903 pr_debug("map %d is \"%s\"\n", i, map->name);
1904 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1906 * If the definition of the map in the object file fits in
1907 * bpf_map_def, copy it. Any extra fields in our version
1908 * of bpf_map_def will default to zero as a result of the
1911 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1912 memcpy(&map->def, def, map_def_sz);
1915 * Here the map structure being read is bigger than what
1916 * we expect, truncate if the excess bits are all zero.
1917 * If they are not zero, reject this map as
1922 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1923 b < ((char *)def) + map_def_sz; b++) {
1925 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1926 obj->path, map_name);
1931 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1937 const struct btf_type *
1938 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1940 const struct btf_type *t = btf__type_by_id(btf, id);
1945 while (btf_is_mod(t) || btf_is_typedef(t)) {
1948 t = btf__type_by_id(btf, t->type);
1954 static const struct btf_type *
1955 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1957 const struct btf_type *t;
1959 t = skip_mods_and_typedefs(btf, id, NULL);
1963 t = skip_mods_and_typedefs(btf, t->type, res_id);
1965 return btf_is_func_proto(t) ? t : NULL;
1968 static const char *__btf_kind_str(__u16 kind)
1971 case BTF_KIND_UNKN: return "void";
1972 case BTF_KIND_INT: return "int";
1973 case BTF_KIND_PTR: return "ptr";
1974 case BTF_KIND_ARRAY: return "array";
1975 case BTF_KIND_STRUCT: return "struct";
1976 case BTF_KIND_UNION: return "union";
1977 case BTF_KIND_ENUM: return "enum";
1978 case BTF_KIND_FWD: return "fwd";
1979 case BTF_KIND_TYPEDEF: return "typedef";
1980 case BTF_KIND_VOLATILE: return "volatile";
1981 case BTF_KIND_CONST: return "const";
1982 case BTF_KIND_RESTRICT: return "restrict";
1983 case BTF_KIND_FUNC: return "func";
1984 case BTF_KIND_FUNC_PROTO: return "func_proto";
1985 case BTF_KIND_VAR: return "var";
1986 case BTF_KIND_DATASEC: return "datasec";
1987 case BTF_KIND_FLOAT: return "float";
1988 default: return "unknown";
1992 const char *btf_kind_str(const struct btf_type *t)
1994 return __btf_kind_str(btf_kind(t));
1998 * Fetch integer attribute of BTF map definition. Such attributes are
1999 * represented using a pointer to an array, in which dimensionality of array
2000 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2001 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2002 * type definition, while using only sizeof(void *) space in ELF data section.
2004 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2005 const struct btf_member *m, __u32 *res)
2007 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2008 const char *name = btf__name_by_offset(btf, m->name_off);
2009 const struct btf_array *arr_info;
2010 const struct btf_type *arr_t;
2012 if (!btf_is_ptr(t)) {
2013 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2014 map_name, name, btf_kind_str(t));
2018 arr_t = btf__type_by_id(btf, t->type);
2020 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2021 map_name, name, t->type);
2024 if (!btf_is_array(arr_t)) {
2025 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2026 map_name, name, btf_kind_str(arr_t));
2029 arr_info = btf_array(arr_t);
2030 *res = arr_info->nelems;
2034 static int build_map_pin_path(struct bpf_map *map, const char *path)
2040 path = "/sys/fs/bpf";
2042 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2045 else if (len >= PATH_MAX)
2046 return -ENAMETOOLONG;
2048 return bpf_map__set_pin_path(map, buf);
2051 int parse_btf_map_def(const char *map_name, struct btf *btf,
2052 const struct btf_type *def_t, bool strict,
2053 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2055 const struct btf_type *t;
2056 const struct btf_member *m;
2057 bool is_inner = inner_def == NULL;
2060 vlen = btf_vlen(def_t);
2061 m = btf_members(def_t);
2062 for (i = 0; i < vlen; i++, m++) {
2063 const char *name = btf__name_by_offset(btf, m->name_off);
2066 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2069 if (strcmp(name, "type") == 0) {
2070 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2072 map_def->parts |= MAP_DEF_MAP_TYPE;
2073 } else if (strcmp(name, "max_entries") == 0) {
2074 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2076 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2077 } else if (strcmp(name, "map_flags") == 0) {
2078 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2080 map_def->parts |= MAP_DEF_MAP_FLAGS;
2081 } else if (strcmp(name, "numa_node") == 0) {
2082 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2084 map_def->parts |= MAP_DEF_NUMA_NODE;
2085 } else if (strcmp(name, "key_size") == 0) {
2088 if (!get_map_field_int(map_name, btf, m, &sz))
2090 if (map_def->key_size && map_def->key_size != sz) {
2091 pr_warn("map '%s': conflicting key size %u != %u.\n",
2092 map_name, map_def->key_size, sz);
2095 map_def->key_size = sz;
2096 map_def->parts |= MAP_DEF_KEY_SIZE;
2097 } else if (strcmp(name, "key") == 0) {
2100 t = btf__type_by_id(btf, m->type);
2102 pr_warn("map '%s': key type [%d] not found.\n",
2106 if (!btf_is_ptr(t)) {
2107 pr_warn("map '%s': key spec is not PTR: %s.\n",
2108 map_name, btf_kind_str(t));
2111 sz = btf__resolve_size(btf, t->type);
2113 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2114 map_name, t->type, (ssize_t)sz);
2117 if (map_def->key_size && map_def->key_size != sz) {
2118 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2119 map_name, map_def->key_size, (ssize_t)sz);
2122 map_def->key_size = sz;
2123 map_def->key_type_id = t->type;
2124 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2125 } else if (strcmp(name, "value_size") == 0) {
2128 if (!get_map_field_int(map_name, btf, m, &sz))
2130 if (map_def->value_size && map_def->value_size != sz) {
2131 pr_warn("map '%s': conflicting value size %u != %u.\n",
2132 map_name, map_def->value_size, sz);
2135 map_def->value_size = sz;
2136 map_def->parts |= MAP_DEF_VALUE_SIZE;
2137 } else if (strcmp(name, "value") == 0) {
2140 t = btf__type_by_id(btf, m->type);
2142 pr_warn("map '%s': value type [%d] not found.\n",
2146 if (!btf_is_ptr(t)) {
2147 pr_warn("map '%s': value spec is not PTR: %s.\n",
2148 map_name, btf_kind_str(t));
2151 sz = btf__resolve_size(btf, t->type);
2153 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2154 map_name, t->type, (ssize_t)sz);
2157 if (map_def->value_size && map_def->value_size != sz) {
2158 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2159 map_name, map_def->value_size, (ssize_t)sz);
2162 map_def->value_size = sz;
2163 map_def->value_type_id = t->type;
2164 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2166 else if (strcmp(name, "values") == 0) {
2167 char inner_map_name[128];
2171 pr_warn("map '%s': multi-level inner maps not supported.\n",
2175 if (i != vlen - 1) {
2176 pr_warn("map '%s': '%s' member should be last.\n",
2180 if (!bpf_map_type__is_map_in_map(map_def->map_type)) {
2181 pr_warn("map '%s': should be map-in-map.\n",
2185 if (map_def->value_size && map_def->value_size != 4) {
2186 pr_warn("map '%s': conflicting value size %u != 4.\n",
2187 map_name, map_def->value_size);
2190 map_def->value_size = 4;
2191 t = btf__type_by_id(btf, m->type);
2193 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2197 if (!btf_is_array(t) || btf_array(t)->nelems) {
2198 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2202 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2203 if (!btf_is_ptr(t)) {
2204 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2205 map_name, btf_kind_str(t));
2208 t = skip_mods_and_typedefs(btf, t->type, NULL);
2209 if (!btf_is_struct(t)) {
2210 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2211 map_name, btf_kind_str(t));
2215 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2216 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2220 map_def->parts |= MAP_DEF_INNER_MAP;
2221 } else if (strcmp(name, "pinning") == 0) {
2225 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2228 if (!get_map_field_int(map_name, btf, m, &val))
2230 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2231 pr_warn("map '%s': invalid pinning value %u.\n",
2235 map_def->pinning = val;
2236 map_def->parts |= MAP_DEF_PINNING;
2239 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2242 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2246 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2247 pr_warn("map '%s': map type isn't specified.\n", map_name);
2254 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2256 map->def.type = def->map_type;
2257 map->def.key_size = def->key_size;
2258 map->def.value_size = def->value_size;
2259 map->def.max_entries = def->max_entries;
2260 map->def.map_flags = def->map_flags;
2262 map->numa_node = def->numa_node;
2263 map->btf_key_type_id = def->key_type_id;
2264 map->btf_value_type_id = def->value_type_id;
2266 if (def->parts & MAP_DEF_MAP_TYPE)
2267 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2269 if (def->parts & MAP_DEF_KEY_TYPE)
2270 pr_debug("map '%s': found key [%u], sz = %u.\n",
2271 map->name, def->key_type_id, def->key_size);
2272 else if (def->parts & MAP_DEF_KEY_SIZE)
2273 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2275 if (def->parts & MAP_DEF_VALUE_TYPE)
2276 pr_debug("map '%s': found value [%u], sz = %u.\n",
2277 map->name, def->value_type_id, def->value_size);
2278 else if (def->parts & MAP_DEF_VALUE_SIZE)
2279 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2281 if (def->parts & MAP_DEF_MAX_ENTRIES)
2282 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2283 if (def->parts & MAP_DEF_MAP_FLAGS)
2284 pr_debug("map '%s': found map_flags = %u.\n", map->name, def->map_flags);
2285 if (def->parts & MAP_DEF_PINNING)
2286 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2287 if (def->parts & MAP_DEF_NUMA_NODE)
2288 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2290 if (def->parts & MAP_DEF_INNER_MAP)
2291 pr_debug("map '%s': found inner map definition.\n", map->name);
2294 static const char *btf_var_linkage_str(__u32 linkage)
2297 case BTF_VAR_STATIC: return "static";
2298 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2299 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2300 default: return "unknown";
2304 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2305 const struct btf_type *sec,
2306 int var_idx, int sec_idx,
2307 const Elf_Data *data, bool strict,
2308 const char *pin_root_path)
2310 struct btf_map_def map_def = {}, inner_def = {};
2311 const struct btf_type *var, *def;
2312 const struct btf_var_secinfo *vi;
2313 const struct btf_var *var_extra;
2314 const char *map_name;
2315 struct bpf_map *map;
2318 vi = btf_var_secinfos(sec) + var_idx;
2319 var = btf__type_by_id(obj->btf, vi->type);
2320 var_extra = btf_var(var);
2321 map_name = btf__name_by_offset(obj->btf, var->name_off);
2323 if (map_name == NULL || map_name[0] == '\0') {
2324 pr_warn("map #%d: empty name.\n", var_idx);
2327 if ((__u64)vi->offset + vi->size > data->d_size) {
2328 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2331 if (!btf_is_var(var)) {
2332 pr_warn("map '%s': unexpected var kind %s.\n",
2333 map_name, btf_kind_str(var));
2336 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2337 pr_warn("map '%s': unsupported map linkage %s.\n",
2338 map_name, btf_var_linkage_str(var_extra->linkage));
2342 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2343 if (!btf_is_struct(def)) {
2344 pr_warn("map '%s': unexpected def kind %s.\n",
2345 map_name, btf_kind_str(var));
2348 if (def->size > vi->size) {
2349 pr_warn("map '%s': invalid def size.\n", map_name);
2353 map = bpf_object__add_map(obj);
2355 return PTR_ERR(map);
2356 map->name = strdup(map_name);
2358 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2361 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2362 map->def.type = BPF_MAP_TYPE_UNSPEC;
2363 map->sec_idx = sec_idx;
2364 map->sec_offset = vi->offset;
2365 map->btf_var_idx = var_idx;
2366 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2367 map_name, map->sec_idx, map->sec_offset);
2369 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2373 fill_map_from_def(map, &map_def);
2375 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2376 err = build_map_pin_path(map, pin_root_path);
2378 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2383 if (map_def.parts & MAP_DEF_INNER_MAP) {
2384 map->inner_map = calloc(1, sizeof(*map->inner_map));
2385 if (!map->inner_map)
2387 map->inner_map->fd = -1;
2388 map->inner_map->sec_idx = sec_idx;
2389 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2390 if (!map->inner_map->name)
2392 sprintf(map->inner_map->name, "%s.inner", map_name);
2394 fill_map_from_def(map->inner_map, &inner_def);
2400 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2401 const char *pin_root_path)
2403 const struct btf_type *sec = NULL;
2404 int nr_types, i, vlen, err;
2405 const struct btf_type *t;
2410 if (obj->efile.btf_maps_shndx < 0)
2413 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2414 data = elf_sec_data(obj, scn);
2415 if (!scn || !data) {
2416 pr_warn("elf: failed to get %s map definitions for %s\n",
2417 MAPS_ELF_SEC, obj->path);
2421 nr_types = btf__get_nr_types(obj->btf);
2422 for (i = 1; i <= nr_types; i++) {
2423 t = btf__type_by_id(obj->btf, i);
2424 if (!btf_is_datasec(t))
2426 name = btf__name_by_offset(obj->btf, t->name_off);
2427 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2429 obj->efile.btf_maps_sec_btf_id = i;
2435 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2439 vlen = btf_vlen(sec);
2440 for (i = 0; i < vlen; i++) {
2441 err = bpf_object__init_user_btf_map(obj, sec, i,
2442 obj->efile.btf_maps_shndx,
2452 static int bpf_object__init_maps(struct bpf_object *obj,
2453 const struct bpf_object_open_opts *opts)
2455 const char *pin_root_path;
2459 strict = !OPTS_GET(opts, relaxed_maps, false);
2460 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2462 err = bpf_object__init_user_maps(obj, strict);
2463 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2464 err = err ?: bpf_object__init_global_data_maps(obj);
2465 err = err ?: bpf_object__init_kconfig_map(obj);
2466 err = err ?: bpf_object__init_struct_ops_maps(obj);
2471 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2475 if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh))
2478 return sh.sh_flags & SHF_EXECINSTR;
2481 static bool btf_needs_sanitization(struct bpf_object *obj)
2483 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2484 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2485 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2486 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2488 return !has_func || !has_datasec || !has_func_global || !has_float;
2491 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2493 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2494 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2495 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2496 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2500 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2501 t = (struct btf_type *)btf__type_by_id(btf, i);
2503 if (!has_datasec && btf_is_var(t)) {
2504 /* replace VAR with INT */
2505 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2507 * using size = 1 is the safest choice, 4 will be too
2508 * big and cause kernel BTF validation failure if
2509 * original variable took less than 4 bytes
2512 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2513 } else if (!has_datasec && btf_is_datasec(t)) {
2514 /* replace DATASEC with STRUCT */
2515 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2516 struct btf_member *m = btf_members(t);
2517 struct btf_type *vt;
2520 name = (char *)btf__name_by_offset(btf, t->name_off);
2528 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2529 for (j = 0; j < vlen; j++, v++, m++) {
2530 /* order of field assignments is important */
2531 m->offset = v->offset * 8;
2533 /* preserve variable name as member name */
2534 vt = (void *)btf__type_by_id(btf, v->type);
2535 m->name_off = vt->name_off;
2537 } else if (!has_func && btf_is_func_proto(t)) {
2538 /* replace FUNC_PROTO with ENUM */
2540 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2541 t->size = sizeof(__u32); /* kernel enforced */
2542 } else if (!has_func && btf_is_func(t)) {
2543 /* replace FUNC with TYPEDEF */
2544 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2545 } else if (!has_func_global && btf_is_func(t)) {
2546 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2547 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2548 } else if (!has_float && btf_is_float(t)) {
2549 /* replace FLOAT with an equally-sized empty STRUCT;
2550 * since C compilers do not accept e.g. "float" as a
2551 * valid struct name, make it anonymous
2554 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2559 static bool libbpf_needs_btf(const struct bpf_object *obj)
2561 return obj->efile.btf_maps_shndx >= 0 ||
2562 obj->efile.st_ops_shndx >= 0 ||
2566 static bool kernel_needs_btf(const struct bpf_object *obj)
2568 return obj->efile.st_ops_shndx >= 0;
2571 static int bpf_object__init_btf(struct bpf_object *obj,
2573 Elf_Data *btf_ext_data)
2578 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2579 err = libbpf_get_error(obj->btf);
2582 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2585 /* enforce 8-byte pointers for BPF-targeted BTFs */
2586 btf__set_pointer_size(obj->btf, 8);
2590 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2591 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2594 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2595 err = libbpf_get_error(obj->btf_ext);
2597 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2598 BTF_EXT_ELF_SEC, err);
2599 obj->btf_ext = NULL;
2604 if (err && libbpf_needs_btf(obj)) {
2605 pr_warn("BTF is required, but is missing or corrupted.\n");
2611 static int bpf_object__finalize_btf(struct bpf_object *obj)
2618 err = btf__finalize_data(obj, obj->btf);
2620 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2627 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2629 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2630 prog->type == BPF_PROG_TYPE_LSM)
2633 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2634 * also need vmlinux BTF
2636 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2642 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2644 struct bpf_program *prog;
2647 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2650 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2653 /* Support for typed ksyms needs kernel BTF */
2654 for (i = 0; i < obj->nr_extern; i++) {
2655 const struct extern_desc *ext;
2657 ext = &obj->externs[i];
2658 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2662 bpf_object__for_each_program(prog, obj) {
2665 if (prog_needs_vmlinux_btf(prog))
2672 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2676 /* btf_vmlinux could be loaded earlier */
2677 if (obj->btf_vmlinux || obj->gen_loader)
2680 if (!force && !obj_needs_vmlinux_btf(obj))
2683 obj->btf_vmlinux = libbpf_find_kernel_btf();
2684 err = libbpf_get_error(obj->btf_vmlinux);
2686 pr_warn("Error loading vmlinux BTF: %d\n", err);
2687 obj->btf_vmlinux = NULL;
2693 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2695 struct btf *kern_btf = obj->btf;
2696 bool btf_mandatory, sanitize;
2702 if (!kernel_supports(obj, FEAT_BTF)) {
2703 if (kernel_needs_btf(obj)) {
2707 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2711 /* Even though some subprogs are global/weak, user might prefer more
2712 * permissive BPF verification process that BPF verifier performs for
2713 * static functions, taking into account more context from the caller
2714 * functions. In such case, they need to mark such subprogs with
2715 * __attribute__((visibility("hidden"))) and libbpf will adjust
2716 * corresponding FUNC BTF type to be marked as static and trigger more
2717 * involved BPF verification process.
2719 for (i = 0; i < obj->nr_programs; i++) {
2720 struct bpf_program *prog = &obj->programs[i];
2725 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2728 n = btf__get_nr_types(obj->btf);
2729 for (j = 1; j <= n; j++) {
2730 t = btf_type_by_id(obj->btf, j);
2731 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2734 name = btf__str_by_offset(obj->btf, t->name_off);
2735 if (strcmp(name, prog->name) != 0)
2738 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2743 sanitize = btf_needs_sanitization(obj);
2745 const void *raw_data;
2748 /* clone BTF to sanitize a copy and leave the original intact */
2749 raw_data = btf__get_raw_data(obj->btf, &sz);
2750 kern_btf = btf__new(raw_data, sz);
2751 err = libbpf_get_error(kern_btf);
2755 /* enforce 8-byte pointers for BPF-targeted BTFs */
2756 btf__set_pointer_size(obj->btf, 8);
2757 bpf_object__sanitize_btf(obj, kern_btf);
2760 if (obj->gen_loader) {
2762 const void *raw_data = btf__get_raw_data(kern_btf, &raw_size);
2766 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
2767 /* Pretend to have valid FD to pass various fd >= 0 checks.
2768 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
2770 btf__set_fd(kern_btf, 0);
2772 err = btf__load_into_kernel(kern_btf);
2776 /* move fd to libbpf's BTF */
2777 btf__set_fd(obj->btf, btf__fd(kern_btf));
2778 btf__set_fd(kern_btf, -1);
2780 btf__free(kern_btf);
2784 btf_mandatory = kernel_needs_btf(obj);
2785 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2786 btf_mandatory ? "BTF is mandatory, can't proceed."
2787 : "BTF is optional, ignoring.");
2794 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
2798 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
2800 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2801 off, obj->path, elf_errmsg(-1));
2808 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
2812 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
2814 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2815 off, obj->path, elf_errmsg(-1));
2822 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
2826 scn = elf_getscn(obj->efile.elf, idx);
2828 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
2829 idx, obj->path, elf_errmsg(-1));
2835 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
2837 Elf_Scn *scn = NULL;
2838 Elf *elf = obj->efile.elf;
2839 const char *sec_name;
2841 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2842 sec_name = elf_sec_name(obj, scn);
2846 if (strcmp(sec_name, name) != 0)
2854 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr)
2859 if (gelf_getshdr(scn, hdr) != hdr) {
2860 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
2861 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2868 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
2876 if (elf_sec_hdr(obj, scn, &sh))
2879 name = elf_sec_str(obj, sh.sh_name);
2881 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
2882 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2889 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
2896 data = elf_getdata(scn, 0);
2898 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
2899 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
2900 obj->path, elf_errmsg(-1));
2907 static bool is_sec_name_dwarf(const char *name)
2909 /* approximation, but the actual list is too long */
2910 return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
2913 static bool ignore_elf_section(GElf_Shdr *hdr, const char *name)
2915 /* no special handling of .strtab */
2916 if (hdr->sh_type == SHT_STRTAB)
2919 /* ignore .llvm_addrsig section as well */
2920 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
2923 /* no subprograms will lead to an empty .text section, ignore it */
2924 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
2925 strcmp(name, ".text") == 0)
2928 /* DWARF sections */
2929 if (is_sec_name_dwarf(name))
2932 if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
2933 name += sizeof(".rel") - 1;
2934 /* DWARF section relocations */
2935 if (is_sec_name_dwarf(name))
2938 /* .BTF and .BTF.ext don't need relocations */
2939 if (strcmp(name, BTF_ELF_SEC) == 0 ||
2940 strcmp(name, BTF_EXT_ELF_SEC) == 0)
2947 static int cmp_progs(const void *_a, const void *_b)
2949 const struct bpf_program *a = _a;
2950 const struct bpf_program *b = _b;
2952 if (a->sec_idx != b->sec_idx)
2953 return a->sec_idx < b->sec_idx ? -1 : 1;
2955 /* sec_insn_off can't be the same within the section */
2956 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
2959 static int bpf_object__elf_collect(struct bpf_object *obj)
2961 Elf *elf = obj->efile.elf;
2962 Elf_Data *btf_ext_data = NULL;
2963 Elf_Data *btf_data = NULL;
2964 int idx = 0, err = 0;
2970 /* a bunch of ELF parsing functionality depends on processing symbols,
2971 * so do the first pass and find the symbol table
2974 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2975 if (elf_sec_hdr(obj, scn, &sh))
2976 return -LIBBPF_ERRNO__FORMAT;
2978 if (sh.sh_type == SHT_SYMTAB) {
2979 if (obj->efile.symbols) {
2980 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
2981 return -LIBBPF_ERRNO__FORMAT;
2984 data = elf_sec_data(obj, scn);
2986 return -LIBBPF_ERRNO__FORMAT;
2988 obj->efile.symbols = data;
2989 obj->efile.symbols_shndx = elf_ndxscn(scn);
2990 obj->efile.strtabidx = sh.sh_link;
2995 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2998 if (elf_sec_hdr(obj, scn, &sh))
2999 return -LIBBPF_ERRNO__FORMAT;
3001 name = elf_sec_str(obj, sh.sh_name);
3003 return -LIBBPF_ERRNO__FORMAT;
3005 if (ignore_elf_section(&sh, name))
3008 data = elf_sec_data(obj, scn);
3010 return -LIBBPF_ERRNO__FORMAT;
3012 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3013 idx, name, (unsigned long)data->d_size,
3014 (int)sh.sh_link, (unsigned long)sh.sh_flags,
3017 if (strcmp(name, "license") == 0) {
3018 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3021 } else if (strcmp(name, "version") == 0) {
3022 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3025 } else if (strcmp(name, "maps") == 0) {
3026 obj->efile.maps_shndx = idx;
3027 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3028 obj->efile.btf_maps_shndx = idx;
3029 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3031 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3032 btf_ext_data = data;
3033 } else if (sh.sh_type == SHT_SYMTAB) {
3034 /* already processed during the first pass above */
3035 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
3036 if (sh.sh_flags & SHF_EXECINSTR) {
3037 if (strcmp(name, ".text") == 0)
3038 obj->efile.text_shndx = idx;
3039 err = bpf_object__add_programs(obj, data, name, idx);
3042 } else if (strcmp(name, DATA_SEC) == 0) {
3043 obj->efile.data = data;
3044 obj->efile.data_shndx = idx;
3045 } else if (strcmp(name, RODATA_SEC) == 0) {
3046 obj->efile.rodata = data;
3047 obj->efile.rodata_shndx = idx;
3048 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3049 obj->efile.st_ops_data = data;
3050 obj->efile.st_ops_shndx = idx;
3052 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3055 } else if (sh.sh_type == SHT_REL) {
3056 int nr_sects = obj->efile.nr_reloc_sects;
3057 void *sects = obj->efile.reloc_sects;
3058 int sec = sh.sh_info; /* points to other section */
3060 /* Only do relo for section with exec instructions */
3061 if (!section_have_execinstr(obj, sec) &&
3062 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3063 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3064 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3066 elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>");
3070 sects = libbpf_reallocarray(sects, nr_sects + 1,
3071 sizeof(*obj->efile.reloc_sects));
3075 obj->efile.reloc_sects = sects;
3076 obj->efile.nr_reloc_sects++;
3078 obj->efile.reloc_sects[nr_sects].shdr = sh;
3079 obj->efile.reloc_sects[nr_sects].data = data;
3080 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3081 obj->efile.bss = data;
3082 obj->efile.bss_shndx = idx;
3084 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3085 (size_t)sh.sh_size);
3089 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3090 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3091 return -LIBBPF_ERRNO__FORMAT;
3094 /* sort BPF programs by section name and in-section instruction offset
3095 * for faster search */
3096 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3098 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3101 static bool sym_is_extern(const GElf_Sym *sym)
3103 int bind = GELF_ST_BIND(sym->st_info);
3104 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3105 return sym->st_shndx == SHN_UNDEF &&
3106 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3107 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
3110 static bool sym_is_subprog(const GElf_Sym *sym, int text_shndx)
3112 int bind = GELF_ST_BIND(sym->st_info);
3113 int type = GELF_ST_TYPE(sym->st_info);
3115 /* in .text section */
3116 if (sym->st_shndx != text_shndx)
3119 /* local function */
3120 if (bind == STB_LOCAL && type == STT_SECTION)
3123 /* global function */
3124 return bind == STB_GLOBAL && type == STT_FUNC;
3127 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3129 const struct btf_type *t;
3136 n = btf__get_nr_types(btf);
3137 for (i = 1; i <= n; i++) {
3138 t = btf__type_by_id(btf, i);
3140 if (!btf_is_var(t) && !btf_is_func(t))
3143 tname = btf__name_by_offset(btf, t->name_off);
3144 if (strcmp(tname, ext_name))
3147 if (btf_is_var(t) &&
3148 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3151 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3160 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3161 const struct btf_var_secinfo *vs;
3162 const struct btf_type *t;
3168 n = btf__get_nr_types(btf);
3169 for (i = 1; i <= n; i++) {
3170 t = btf__type_by_id(btf, i);
3172 if (!btf_is_datasec(t))
3175 vs = btf_var_secinfos(t);
3176 for (j = 0; j < btf_vlen(t); j++, vs++) {
3177 if (vs->type == ext_btf_id)
3185 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3188 const struct btf_type *t;
3191 t = skip_mods_and_typedefs(btf, id, NULL);
3192 name = btf__name_by_offset(btf, t->name_off);
3196 switch (btf_kind(t)) {
3197 case BTF_KIND_INT: {
3198 int enc = btf_int_encoding(t);
3200 if (enc & BTF_INT_BOOL)
3201 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3203 *is_signed = enc & BTF_INT_SIGNED;
3206 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3207 return KCFG_UNKNOWN;
3212 return KCFG_UNKNOWN;
3213 if (strcmp(name, "libbpf_tristate"))
3214 return KCFG_UNKNOWN;
3215 return KCFG_TRISTATE;
3216 case BTF_KIND_ARRAY:
3217 if (btf_array(t)->nelems == 0)
3218 return KCFG_UNKNOWN;
3219 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3220 return KCFG_UNKNOWN;
3221 return KCFG_CHAR_ARR;
3223 return KCFG_UNKNOWN;
3227 static int cmp_externs(const void *_a, const void *_b)
3229 const struct extern_desc *a = _a;
3230 const struct extern_desc *b = _b;
3232 if (a->type != b->type)
3233 return a->type < b->type ? -1 : 1;
3235 if (a->type == EXT_KCFG) {
3236 /* descending order by alignment requirements */
3237 if (a->kcfg.align != b->kcfg.align)
3238 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3239 /* ascending order by size, within same alignment class */
3240 if (a->kcfg.sz != b->kcfg.sz)
3241 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3244 /* resolve ties by name */
3245 return strcmp(a->name, b->name);
3248 static int find_int_btf_id(const struct btf *btf)
3250 const struct btf_type *t;
3253 n = btf__get_nr_types(btf);
3254 for (i = 1; i <= n; i++) {
3255 t = btf__type_by_id(btf, i);
3257 if (btf_is_int(t) && btf_int_bits(t) == 32)
3264 static int add_dummy_ksym_var(struct btf *btf)
3266 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3267 const struct btf_var_secinfo *vs;
3268 const struct btf_type *sec;
3273 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3278 sec = btf__type_by_id(btf, sec_btf_id);
3279 vs = btf_var_secinfos(sec);
3280 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3281 const struct btf_type *vt;
3283 vt = btf__type_by_id(btf, vs->type);
3284 if (btf_is_func(vt))
3288 /* No func in ksyms sec. No need to add dummy var. */
3289 if (i == btf_vlen(sec))
3292 int_btf_id = find_int_btf_id(btf);
3293 dummy_var_btf_id = btf__add_var(btf,
3295 BTF_VAR_GLOBAL_ALLOCATED,
3297 if (dummy_var_btf_id < 0)
3298 pr_warn("cannot create a dummy_ksym var\n");
3300 return dummy_var_btf_id;
3303 static int bpf_object__collect_externs(struct bpf_object *obj)
3305 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3306 const struct btf_type *t;
3307 struct extern_desc *ext;
3308 int i, n, off, dummy_var_btf_id;
3309 const char *ext_name, *sec_name;
3313 if (!obj->efile.symbols)
3316 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3317 if (elf_sec_hdr(obj, scn, &sh))
3318 return -LIBBPF_ERRNO__FORMAT;
3320 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3321 if (dummy_var_btf_id < 0)
3322 return dummy_var_btf_id;
3324 n = sh.sh_size / sh.sh_entsize;
3325 pr_debug("looking for externs among %d symbols...\n", n);
3327 for (i = 0; i < n; i++) {
3330 if (!gelf_getsym(obj->efile.symbols, i, &sym))
3331 return -LIBBPF_ERRNO__FORMAT;
3332 if (!sym_is_extern(&sym))
3334 ext_name = elf_sym_str(obj, sym.st_name);
3335 if (!ext_name || !ext_name[0])
3339 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3343 ext = &ext[obj->nr_extern];
3344 memset(ext, 0, sizeof(*ext));
3347 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3348 if (ext->btf_id <= 0) {
3349 pr_warn("failed to find BTF for extern '%s': %d\n",
3350 ext_name, ext->btf_id);
3353 t = btf__type_by_id(obj->btf, ext->btf_id);
3354 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3356 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
3358 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3359 if (ext->sec_btf_id <= 0) {
3360 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3361 ext_name, ext->btf_id, ext->sec_btf_id);
3362 return ext->sec_btf_id;
3364 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3365 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3367 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3368 if (btf_is_func(t)) {
3369 pr_warn("extern function %s is unsupported under %s section\n",
3370 ext->name, KCONFIG_SEC);
3374 ext->type = EXT_KCFG;
3375 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3376 if (ext->kcfg.sz <= 0) {
3377 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3378 ext_name, ext->kcfg.sz);
3379 return ext->kcfg.sz;
3381 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3382 if (ext->kcfg.align <= 0) {
3383 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3384 ext_name, ext->kcfg.align);
3387 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3388 &ext->kcfg.is_signed);
3389 if (ext->kcfg.type == KCFG_UNKNOWN) {
3390 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3393 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3394 if (btf_is_func(t) && ext->is_weak) {
3395 pr_warn("extern weak function %s is unsupported\n",
3400 ext->type = EXT_KSYM;
3401 skip_mods_and_typedefs(obj->btf, t->type,
3402 &ext->ksym.type_id);
3404 pr_warn("unrecognized extern section '%s'\n", sec_name);
3408 pr_debug("collected %d externs total\n", obj->nr_extern);
3410 if (!obj->nr_extern)
3413 /* sort externs by type, for kcfg ones also by (align, size, name) */
3414 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3416 /* for .ksyms section, we need to turn all externs into allocated
3417 * variables in BTF to pass kernel verification; we do this by
3418 * pretending that each extern is a 8-byte variable
3421 /* find existing 4-byte integer type in BTF to use for fake
3422 * extern variables in DATASEC
3424 int int_btf_id = find_int_btf_id(obj->btf);
3425 /* For extern function, a dummy_var added earlier
3426 * will be used to replace the vs->type and
3427 * its name string will be used to refill
3428 * the missing param's name.
3430 const struct btf_type *dummy_var;
3432 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3433 for (i = 0; i < obj->nr_extern; i++) {
3434 ext = &obj->externs[i];
3435 if (ext->type != EXT_KSYM)
3437 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3438 i, ext->sym_idx, ext->name);
3443 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3444 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3445 struct btf_type *vt;
3447 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3448 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3449 ext = find_extern_by_name(obj, ext_name);
3451 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3452 btf_kind_str(vt), ext_name);
3455 if (btf_is_func(vt)) {
3456 const struct btf_type *func_proto;
3457 struct btf_param *param;
3460 func_proto = btf__type_by_id(obj->btf,
3462 param = btf_params(func_proto);
3463 /* Reuse the dummy_var string if the
3464 * func proto does not have param name.
3466 for (j = 0; j < btf_vlen(func_proto); j++)
3467 if (param[j].type && !param[j].name_off)
3469 dummy_var->name_off;
3470 vs->type = dummy_var_btf_id;
3471 vt->info &= ~0xffff;
3472 vt->info |= BTF_FUNC_GLOBAL;
3474 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3475 vt->type = int_btf_id;
3478 vs->size = sizeof(int);
3485 /* for kcfg externs calculate their offsets within a .kconfig map */
3487 for (i = 0; i < obj->nr_extern; i++) {
3488 ext = &obj->externs[i];
3489 if (ext->type != EXT_KCFG)
3492 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3493 off = ext->kcfg.data_off + ext->kcfg.sz;
3494 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3495 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3499 for (i = 0; i < n; i++) {
3500 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3502 t = btf__type_by_id(obj->btf, vs->type);
3503 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3504 ext = find_extern_by_name(obj, ext_name);
3506 pr_warn("failed to find extern definition for BTF var '%s'\n",
3510 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3511 vs->offset = ext->kcfg.data_off;
3517 struct bpf_program *
3518 bpf_object__find_program_by_title(const struct bpf_object *obj,
3521 struct bpf_program *pos;
3523 bpf_object__for_each_program(pos, obj) {
3524 if (pos->sec_name && !strcmp(pos->sec_name, title))
3527 return errno = ENOENT, NULL;
3530 static bool prog_is_subprog(const struct bpf_object *obj,
3531 const struct bpf_program *prog)
3533 /* For legacy reasons, libbpf supports an entry-point BPF programs
3534 * without SEC() attribute, i.e., those in the .text section. But if
3535 * there are 2 or more such programs in the .text section, they all
3536 * must be subprograms called from entry-point BPF programs in
3537 * designated SEC()'tions, otherwise there is no way to distinguish
3538 * which of those programs should be loaded vs which are a subprogram.
3539 * Similarly, if there is a function/program in .text and at least one
3540 * other BPF program with custom SEC() attribute, then we just assume
3541 * .text programs are subprograms (even if they are not called from
3542 * other programs), because libbpf never explicitly supported mixing
3543 * SEC()-designated BPF programs and .text entry-point BPF programs.
3545 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3548 struct bpf_program *
3549 bpf_object__find_program_by_name(const struct bpf_object *obj,
3552 struct bpf_program *prog;
3554 bpf_object__for_each_program(prog, obj) {
3555 if (prog_is_subprog(obj, prog))
3557 if (!strcmp(prog->name, name))
3560 return errno = ENOENT, NULL;
3563 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3566 return shndx == obj->efile.data_shndx ||
3567 shndx == obj->efile.bss_shndx ||
3568 shndx == obj->efile.rodata_shndx;
3571 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3574 return shndx == obj->efile.maps_shndx ||
3575 shndx == obj->efile.btf_maps_shndx;
3578 static enum libbpf_map_type
3579 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3581 if (shndx == obj->efile.data_shndx)
3582 return LIBBPF_MAP_DATA;
3583 else if (shndx == obj->efile.bss_shndx)
3584 return LIBBPF_MAP_BSS;
3585 else if (shndx == obj->efile.rodata_shndx)
3586 return LIBBPF_MAP_RODATA;
3587 else if (shndx == obj->efile.symbols_shndx)
3588 return LIBBPF_MAP_KCONFIG;
3590 return LIBBPF_MAP_UNSPEC;
3593 static int bpf_program__record_reloc(struct bpf_program *prog,
3594 struct reloc_desc *reloc_desc,
3595 __u32 insn_idx, const char *sym_name,
3596 const GElf_Sym *sym, const GElf_Rel *rel)
3598 struct bpf_insn *insn = &prog->insns[insn_idx];
3599 size_t map_idx, nr_maps = prog->obj->nr_maps;
3600 struct bpf_object *obj = prog->obj;
3601 __u32 shdr_idx = sym->st_shndx;
3602 enum libbpf_map_type type;
3603 const char *sym_sec_name;
3604 struct bpf_map *map;
3606 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3607 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3608 prog->name, sym_name, insn_idx, insn->code);
3609 return -LIBBPF_ERRNO__RELOC;
3612 if (sym_is_extern(sym)) {
3613 int sym_idx = GELF_R_SYM(rel->r_info);
3614 int i, n = obj->nr_extern;
3615 struct extern_desc *ext;
3617 for (i = 0; i < n; i++) {
3618 ext = &obj->externs[i];
3619 if (ext->sym_idx == sym_idx)
3623 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3624 prog->name, sym_name, sym_idx);
3625 return -LIBBPF_ERRNO__RELOC;
3627 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3628 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3629 if (insn->code == (BPF_JMP | BPF_CALL))
3630 reloc_desc->type = RELO_EXTERN_FUNC;
3632 reloc_desc->type = RELO_EXTERN_VAR;
3633 reloc_desc->insn_idx = insn_idx;
3634 reloc_desc->sym_off = i; /* sym_off stores extern index */
3638 /* sub-program call relocation */
3639 if (is_call_insn(insn)) {
3640 if (insn->src_reg != BPF_PSEUDO_CALL) {
3641 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3642 return -LIBBPF_ERRNO__RELOC;
3644 /* text_shndx can be 0, if no default "main" program exists */
3645 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3646 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3647 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3648 prog->name, sym_name, sym_sec_name);
3649 return -LIBBPF_ERRNO__RELOC;
3651 if (sym->st_value % BPF_INSN_SZ) {
3652 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3653 prog->name, sym_name, (size_t)sym->st_value);
3654 return -LIBBPF_ERRNO__RELOC;
3656 reloc_desc->type = RELO_CALL;
3657 reloc_desc->insn_idx = insn_idx;
3658 reloc_desc->sym_off = sym->st_value;
3662 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3663 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3664 prog->name, sym_name, shdr_idx);
3665 return -LIBBPF_ERRNO__RELOC;
3668 /* loading subprog addresses */
3669 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3670 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3671 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3673 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3674 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3675 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3676 return -LIBBPF_ERRNO__RELOC;
3679 reloc_desc->type = RELO_SUBPROG_ADDR;
3680 reloc_desc->insn_idx = insn_idx;
3681 reloc_desc->sym_off = sym->st_value;
3685 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3686 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3688 /* generic map reference relocation */
3689 if (type == LIBBPF_MAP_UNSPEC) {
3690 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3691 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3692 prog->name, sym_name, sym_sec_name);
3693 return -LIBBPF_ERRNO__RELOC;
3695 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3696 map = &obj->maps[map_idx];
3697 if (map->libbpf_type != type ||
3698 map->sec_idx != sym->st_shndx ||
3699 map->sec_offset != sym->st_value)
3701 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
3702 prog->name, map_idx, map->name, map->sec_idx,
3703 map->sec_offset, insn_idx);
3706 if (map_idx >= nr_maps) {
3707 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
3708 prog->name, sym_sec_name, (size_t)sym->st_value);
3709 return -LIBBPF_ERRNO__RELOC;
3711 reloc_desc->type = RELO_LD64;
3712 reloc_desc->insn_idx = insn_idx;
3713 reloc_desc->map_idx = map_idx;
3714 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3718 /* global data map relocation */
3719 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3720 pr_warn("prog '%s': bad data relo against section '%s'\n",
3721 prog->name, sym_sec_name);
3722 return -LIBBPF_ERRNO__RELOC;
3724 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3725 map = &obj->maps[map_idx];
3726 if (map->libbpf_type != type)
3728 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3729 prog->name, map_idx, map->name, map->sec_idx,
3730 map->sec_offset, insn_idx);
3733 if (map_idx >= nr_maps) {
3734 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
3735 prog->name, sym_sec_name);
3736 return -LIBBPF_ERRNO__RELOC;
3739 reloc_desc->type = RELO_DATA;
3740 reloc_desc->insn_idx = insn_idx;
3741 reloc_desc->map_idx = map_idx;
3742 reloc_desc->sym_off = sym->st_value;
3746 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
3748 return insn_idx >= prog->sec_insn_off &&
3749 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
3752 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
3753 size_t sec_idx, size_t insn_idx)
3755 int l = 0, r = obj->nr_programs - 1, m;
3756 struct bpf_program *prog;
3759 m = l + (r - l + 1) / 2;
3760 prog = &obj->programs[m];
3762 if (prog->sec_idx < sec_idx ||
3763 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
3768 /* matching program could be at index l, but it still might be the
3769 * wrong one, so we need to double check conditions for the last time
3771 prog = &obj->programs[l];
3772 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
3778 bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data)
3780 Elf_Data *symbols = obj->efile.symbols;
3781 const char *relo_sec_name, *sec_name;
3782 size_t sec_idx = shdr->sh_info;
3783 struct bpf_program *prog;
3784 struct reloc_desc *relos;
3786 const char *sym_name;
3793 scn = elf_sec_by_idx(obj, sec_idx);
3794 scn_data = elf_sec_data(obj, scn);
3796 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
3797 sec_name = elf_sec_name(obj, scn);
3798 if (!relo_sec_name || !sec_name)
3801 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
3802 relo_sec_name, sec_idx, sec_name);
3803 nrels = shdr->sh_size / shdr->sh_entsize;
3805 for (i = 0; i < nrels; i++) {
3806 if (!gelf_getrel(data, i, &rel)) {
3807 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
3808 return -LIBBPF_ERRNO__FORMAT;
3810 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3811 pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n",
3812 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3813 return -LIBBPF_ERRNO__FORMAT;
3816 if (rel.r_offset % BPF_INSN_SZ || rel.r_offset >= scn_data->d_size) {
3817 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
3818 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3819 return -LIBBPF_ERRNO__FORMAT;
3822 insn_idx = rel.r_offset / BPF_INSN_SZ;
3823 /* relocations against static functions are recorded as
3824 * relocations against the section that contains a function;
3825 * in such case, symbol will be STT_SECTION and sym.st_name
3826 * will point to empty string (0), so fetch section name
3829 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0)
3830 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx));
3832 sym_name = elf_sym_str(obj, sym.st_name);
3833 sym_name = sym_name ?: "<?";
3835 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
3836 relo_sec_name, i, insn_idx, sym_name);
3838 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
3840 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
3841 relo_sec_name, i, sec_name, insn_idx);
3845 relos = libbpf_reallocarray(prog->reloc_desc,
3846 prog->nr_reloc + 1, sizeof(*relos));
3849 prog->reloc_desc = relos;
3851 /* adjust insn_idx to local BPF program frame of reference */
3852 insn_idx -= prog->sec_insn_off;
3853 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
3854 insn_idx, sym_name, &sym, &rel);
3863 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3865 struct bpf_map_def *def = &map->def;
3866 __u32 key_type_id = 0, value_type_id = 0;
3869 /* if it's BTF-defined map, we don't need to search for type IDs.
3870 * For struct_ops map, it does not need btf_key_type_id and
3871 * btf_value_type_id.
3873 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3874 bpf_map__is_struct_ops(map))
3877 if (!bpf_map__is_internal(map)) {
3878 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3879 def->value_size, &key_type_id,
3883 * LLVM annotates global data differently in BTF, that is,
3884 * only as '.data', '.bss' or '.rodata'.
3886 ret = btf__find_by_name(obj->btf,
3887 libbpf_type_to_btf_name[map->libbpf_type]);
3892 map->btf_key_type_id = key_type_id;
3893 map->btf_value_type_id = bpf_map__is_internal(map) ?
3894 ret : value_type_id;
3898 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
3900 char file[PATH_MAX], buff[4096];
3905 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
3906 memset(info, 0, sizeof(*info));
3908 fp = fopen(file, "r");
3911 pr_warn("failed to open %s: %d. No procfs support?\n", file,
3916 while (fgets(buff, sizeof(buff), fp)) {
3917 if (sscanf(buff, "map_type:\t%u", &val) == 1)
3919 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
3920 info->key_size = val;
3921 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
3922 info->value_size = val;
3923 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
3924 info->max_entries = val;
3925 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
3926 info->map_flags = val;
3934 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3936 struct bpf_map_info info = {};
3937 __u32 len = sizeof(info);
3941 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3942 if (err && errno == EINVAL)
3943 err = bpf_get_map_info_from_fdinfo(fd, &info);
3945 return libbpf_err(err);
3947 new_name = strdup(info.name);
3949 return libbpf_err(-errno);
3951 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3954 goto err_free_new_name;
3957 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3960 goto err_close_new_fd;
3963 err = zclose(map->fd);
3966 goto err_close_new_fd;
3971 map->name = new_name;
3972 map->def.type = info.type;
3973 map->def.key_size = info.key_size;
3974 map->def.value_size = info.value_size;
3975 map->def.max_entries = info.max_entries;
3976 map->def.map_flags = info.map_flags;
3977 map->btf_key_type_id = info.btf_key_type_id;
3978 map->btf_value_type_id = info.btf_value_type_id;
3987 return libbpf_err(err);
3990 __u32 bpf_map__max_entries(const struct bpf_map *map)
3992 return map->def.max_entries;
3995 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
3997 if (!bpf_map_type__is_map_in_map(map->def.type))
3998 return errno = EINVAL, NULL;
4000 return map->inner_map;
4003 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4006 return libbpf_err(-EBUSY);
4007 map->def.max_entries = max_entries;
4011 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4013 if (!map || !max_entries)
4014 return libbpf_err(-EINVAL);
4016 return bpf_map__set_max_entries(map, max_entries);
4020 bpf_object__probe_loading(struct bpf_object *obj)
4022 struct bpf_load_program_attr attr;
4023 char *cp, errmsg[STRERR_BUFSIZE];
4024 struct bpf_insn insns[] = {
4025 BPF_MOV64_IMM(BPF_REG_0, 0),
4030 if (obj->gen_loader)
4033 /* make sure basic loading works */
4035 memset(&attr, 0, sizeof(attr));
4036 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4038 attr.insns_cnt = ARRAY_SIZE(insns);
4039 attr.license = "GPL";
4041 ret = bpf_load_program_xattr(&attr, NULL, 0);
4043 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4044 ret = bpf_load_program_xattr(&attr, NULL, 0);
4048 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4049 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4050 "program. Make sure your kernel supports BPF "
4051 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4052 "set to big enough value.\n", __func__, cp, ret);
4060 static int probe_fd(int fd)
4067 static int probe_kern_prog_name(void)
4069 struct bpf_load_program_attr attr;
4070 struct bpf_insn insns[] = {
4071 BPF_MOV64_IMM(BPF_REG_0, 0),
4076 /* make sure loading with name works */
4078 memset(&attr, 0, sizeof(attr));
4079 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4081 attr.insns_cnt = ARRAY_SIZE(insns);
4082 attr.license = "GPL";
4084 ret = bpf_load_program_xattr(&attr, NULL, 0);
4085 return probe_fd(ret);
4088 static int probe_kern_global_data(void)
4090 struct bpf_load_program_attr prg_attr;
4091 struct bpf_create_map_attr map_attr;
4092 char *cp, errmsg[STRERR_BUFSIZE];
4093 struct bpf_insn insns[] = {
4094 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4095 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4096 BPF_MOV64_IMM(BPF_REG_0, 0),
4101 memset(&map_attr, 0, sizeof(map_attr));
4102 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4103 map_attr.key_size = sizeof(int);
4104 map_attr.value_size = 32;
4105 map_attr.max_entries = 1;
4107 map = bpf_create_map_xattr(&map_attr);
4110 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4111 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4112 __func__, cp, -ret);
4118 memset(&prg_attr, 0, sizeof(prg_attr));
4119 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4120 prg_attr.insns = insns;
4121 prg_attr.insns_cnt = ARRAY_SIZE(insns);
4122 prg_attr.license = "GPL";
4124 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
4126 return probe_fd(ret);
4129 static int probe_kern_btf(void)
4131 static const char strs[] = "\0int";
4134 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4137 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4138 strs, sizeof(strs)));
4141 static int probe_kern_btf_func(void)
4143 static const char strs[] = "\0int\0x\0a";
4144 /* void x(int a) {} */
4147 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4148 /* FUNC_PROTO */ /* [2] */
4149 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4150 BTF_PARAM_ENC(7, 1),
4151 /* FUNC x */ /* [3] */
4152 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4155 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4156 strs, sizeof(strs)));
4159 static int probe_kern_btf_func_global(void)
4161 static const char strs[] = "\0int\0x\0a";
4162 /* static void x(int a) {} */
4165 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4166 /* FUNC_PROTO */ /* [2] */
4167 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4168 BTF_PARAM_ENC(7, 1),
4169 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4170 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4173 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4174 strs, sizeof(strs)));
4177 static int probe_kern_btf_datasec(void)
4179 static const char strs[] = "\0x\0.data";
4183 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4184 /* VAR x */ /* [2] */
4185 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4187 /* DATASEC val */ /* [3] */
4188 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4189 BTF_VAR_SECINFO_ENC(2, 0, 4),
4192 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4193 strs, sizeof(strs)));
4196 static int probe_kern_btf_float(void)
4198 static const char strs[] = "\0float";
4201 BTF_TYPE_FLOAT_ENC(1, 4),
4204 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4205 strs, sizeof(strs)));
4208 static int probe_kern_array_mmap(void)
4210 struct bpf_create_map_attr attr = {
4211 .map_type = BPF_MAP_TYPE_ARRAY,
4212 .map_flags = BPF_F_MMAPABLE,
4213 .key_size = sizeof(int),
4214 .value_size = sizeof(int),
4218 return probe_fd(bpf_create_map_xattr(&attr));
4221 static int probe_kern_exp_attach_type(void)
4223 struct bpf_load_program_attr attr;
4224 struct bpf_insn insns[] = {
4225 BPF_MOV64_IMM(BPF_REG_0, 0),
4229 memset(&attr, 0, sizeof(attr));
4230 /* use any valid combination of program type and (optional)
4231 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4232 * to see if kernel supports expected_attach_type field for
4233 * BPF_PROG_LOAD command
4235 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
4236 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
4238 attr.insns_cnt = ARRAY_SIZE(insns);
4239 attr.license = "GPL";
4241 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4244 static int probe_kern_probe_read_kernel(void)
4246 struct bpf_load_program_attr attr;
4247 struct bpf_insn insns[] = {
4248 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4249 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4250 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4251 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4252 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4256 memset(&attr, 0, sizeof(attr));
4257 attr.prog_type = BPF_PROG_TYPE_KPROBE;
4259 attr.insns_cnt = ARRAY_SIZE(insns);
4260 attr.license = "GPL";
4262 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4265 static int probe_prog_bind_map(void)
4267 struct bpf_load_program_attr prg_attr;
4268 struct bpf_create_map_attr map_attr;
4269 char *cp, errmsg[STRERR_BUFSIZE];
4270 struct bpf_insn insns[] = {
4271 BPF_MOV64_IMM(BPF_REG_0, 0),
4276 memset(&map_attr, 0, sizeof(map_attr));
4277 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4278 map_attr.key_size = sizeof(int);
4279 map_attr.value_size = 32;
4280 map_attr.max_entries = 1;
4282 map = bpf_create_map_xattr(&map_attr);
4285 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4286 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4287 __func__, cp, -ret);
4291 memset(&prg_attr, 0, sizeof(prg_attr));
4292 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4293 prg_attr.insns = insns;
4294 prg_attr.insns_cnt = ARRAY_SIZE(insns);
4295 prg_attr.license = "GPL";
4297 prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
4303 ret = bpf_prog_bind_map(prog, map, NULL);
4311 static int probe_module_btf(void)
4313 static const char strs[] = "\0int";
4316 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4318 struct bpf_btf_info info;
4319 __u32 len = sizeof(info);
4323 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4325 return 0; /* BTF not supported at all */
4327 memset(&info, 0, sizeof(info));
4328 info.name = ptr_to_u64(name);
4329 info.name_len = sizeof(name);
4331 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4332 * kernel's module BTF support coincides with support for
4333 * name/name_len fields in struct bpf_btf_info.
4335 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4340 enum kern_feature_result {
4346 typedef int (*feature_probe_fn)(void);
4348 static struct kern_feature_desc {
4350 feature_probe_fn probe;
4351 enum kern_feature_result res;
4352 } feature_probes[__FEAT_CNT] = {
4353 [FEAT_PROG_NAME] = {
4354 "BPF program name", probe_kern_prog_name,
4356 [FEAT_GLOBAL_DATA] = {
4357 "global variables", probe_kern_global_data,
4360 "minimal BTF", probe_kern_btf,
4363 "BTF functions", probe_kern_btf_func,
4365 [FEAT_BTF_GLOBAL_FUNC] = {
4366 "BTF global function", probe_kern_btf_func_global,
4368 [FEAT_BTF_DATASEC] = {
4369 "BTF data section and variable", probe_kern_btf_datasec,
4371 [FEAT_ARRAY_MMAP] = {
4372 "ARRAY map mmap()", probe_kern_array_mmap,
4374 [FEAT_EXP_ATTACH_TYPE] = {
4375 "BPF_PROG_LOAD expected_attach_type attribute",
4376 probe_kern_exp_attach_type,
4378 [FEAT_PROBE_READ_KERN] = {
4379 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4381 [FEAT_PROG_BIND_MAP] = {
4382 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4384 [FEAT_MODULE_BTF] = {
4385 "module BTF support", probe_module_btf,
4387 [FEAT_BTF_FLOAT] = {
4388 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4392 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4394 struct kern_feature_desc *feat = &feature_probes[feat_id];
4397 if (obj->gen_loader)
4398 /* To generate loader program assume the latest kernel
4399 * to avoid doing extra prog_load, map_create syscalls.
4403 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4404 ret = feat->probe();
4406 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4407 } else if (ret == 0) {
4408 WRITE_ONCE(feat->res, FEAT_MISSING);
4410 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4411 WRITE_ONCE(feat->res, FEAT_MISSING);
4415 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4418 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4420 struct bpf_map_info map_info = {};
4421 char msg[STRERR_BUFSIZE];
4425 map_info_len = sizeof(map_info);
4427 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4428 if (err && errno == EINVAL)
4429 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4431 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4432 libbpf_strerror_r(errno, msg, sizeof(msg)));
4436 return (map_info.type == map->def.type &&
4437 map_info.key_size == map->def.key_size &&
4438 map_info.value_size == map->def.value_size &&
4439 map_info.max_entries == map->def.max_entries &&
4440 map_info.map_flags == map->def.map_flags);
4444 bpf_object__reuse_map(struct bpf_map *map)
4446 char *cp, errmsg[STRERR_BUFSIZE];
4449 pin_fd = bpf_obj_get(map->pin_path);
4452 if (err == -ENOENT) {
4453 pr_debug("found no pinned map to reuse at '%s'\n",
4458 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4459 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4464 if (!map_is_reuse_compat(map, pin_fd)) {
4465 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4471 err = bpf_map__reuse_fd(map, pin_fd);
4477 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4483 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4485 enum libbpf_map_type map_type = map->libbpf_type;
4486 char *cp, errmsg[STRERR_BUFSIZE];
4489 if (obj->gen_loader) {
4490 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4491 map->mmaped, map->def.value_size);
4492 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4493 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4496 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4499 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4500 pr_warn("Error setting initial map(%s) contents: %s\n",
4505 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4506 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4507 err = bpf_map_freeze(map->fd);
4510 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4511 pr_warn("Error freezing map(%s) as read-only: %s\n",
4519 static void bpf_map__destroy(struct bpf_map *map);
4521 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4523 struct bpf_create_map_attr create_attr;
4524 struct bpf_map_def *def = &map->def;
4527 memset(&create_attr, 0, sizeof(create_attr));
4529 if (kernel_supports(obj, FEAT_PROG_NAME))
4530 create_attr.name = map->name;
4531 create_attr.map_ifindex = map->map_ifindex;
4532 create_attr.map_type = def->type;
4533 create_attr.map_flags = def->map_flags;
4534 create_attr.key_size = def->key_size;
4535 create_attr.value_size = def->value_size;
4536 create_attr.numa_node = map->numa_node;
4538 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4541 nr_cpus = libbpf_num_possible_cpus();
4543 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4544 map->name, nr_cpus);
4547 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4548 create_attr.max_entries = nr_cpus;
4550 create_attr.max_entries = def->max_entries;
4553 if (bpf_map__is_struct_ops(map))
4554 create_attr.btf_vmlinux_value_type_id =
4555 map->btf_vmlinux_value_type_id;
4557 create_attr.btf_fd = 0;
4558 create_attr.btf_key_type_id = 0;
4559 create_attr.btf_value_type_id = 0;
4560 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4561 create_attr.btf_fd = btf__fd(obj->btf);
4562 create_attr.btf_key_type_id = map->btf_key_type_id;
4563 create_attr.btf_value_type_id = map->btf_value_type_id;
4566 if (bpf_map_type__is_map_in_map(def->type)) {
4567 if (map->inner_map) {
4568 err = bpf_object__create_map(obj, map->inner_map, true);
4570 pr_warn("map '%s': failed to create inner map: %d\n",
4574 map->inner_map_fd = bpf_map__fd(map->inner_map);
4576 if (map->inner_map_fd >= 0)
4577 create_attr.inner_map_fd = map->inner_map_fd;
4580 if (obj->gen_loader) {
4581 bpf_gen__map_create(obj->gen_loader, &create_attr, is_inner ? -1 : map - obj->maps);
4582 /* Pretend to have valid FD to pass various fd >= 0 checks.
4583 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4587 map->fd = bpf_create_map_xattr(&create_attr);
4589 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4590 create_attr.btf_value_type_id)) {
4591 char *cp, errmsg[STRERR_BUFSIZE];
4594 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4595 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4596 map->name, cp, err);
4597 create_attr.btf_fd = 0;
4598 create_attr.btf_key_type_id = 0;
4599 create_attr.btf_value_type_id = 0;
4600 map->btf_key_type_id = 0;
4601 map->btf_value_type_id = 0;
4602 map->fd = bpf_create_map_xattr(&create_attr);
4605 err = map->fd < 0 ? -errno : 0;
4607 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4608 if (obj->gen_loader)
4609 map->inner_map->fd = -1;
4610 bpf_map__destroy(map->inner_map);
4611 zfree(&map->inner_map);
4617 static int init_map_slots(struct bpf_object *obj, struct bpf_map *map)
4619 const struct bpf_map *targ_map;
4623 for (i = 0; i < map->init_slots_sz; i++) {
4624 if (!map->init_slots[i])
4627 targ_map = map->init_slots[i];
4628 fd = bpf_map__fd(targ_map);
4629 if (obj->gen_loader) {
4630 pr_warn("// TODO map_update_elem: idx %td key %d value==map_idx %td\n",
4631 map - obj->maps, i, targ_map - obj->maps);
4634 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4638 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4639 map->name, i, targ_map->name,
4643 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4644 map->name, i, targ_map->name, fd);
4647 zfree(&map->init_slots);
4648 map->init_slots_sz = 0;
4654 bpf_object__create_maps(struct bpf_object *obj)
4656 struct bpf_map *map;
4657 char *cp, errmsg[STRERR_BUFSIZE];
4662 for (i = 0; i < obj->nr_maps; i++) {
4663 map = &obj->maps[i];
4667 if (map->pin_path) {
4668 err = bpf_object__reuse_map(map);
4670 pr_warn("map '%s': error reusing pinned map\n",
4674 if (retried && map->fd < 0) {
4675 pr_warn("map '%s': cannot find pinned map\n",
4683 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
4684 map->name, map->fd);
4686 err = bpf_object__create_map(obj, map, false);
4690 pr_debug("map '%s': created successfully, fd=%d\n",
4691 map->name, map->fd);
4693 if (bpf_map__is_internal(map)) {
4694 err = bpf_object__populate_internal_map(obj, map);
4701 if (map->init_slots_sz) {
4702 err = init_map_slots(obj, map);
4710 if (map->pin_path && !map->pinned) {
4711 err = bpf_map__pin(map, NULL);
4714 if (!retried && err == -EEXIST) {
4718 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
4719 map->name, map->pin_path, err);
4728 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4729 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
4731 for (j = 0; j < i; j++)
4732 zclose(obj->maps[j].fd);
4736 static bool bpf_core_is_flavor_sep(const char *s)
4738 /* check X___Y name pattern, where X and Y are not underscores */
4739 return s[0] != '_' && /* X */
4740 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4741 s[4] != '_'; /* Y */
4744 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4745 * before last triple underscore. Struct name part after last triple
4746 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4748 size_t bpf_core_essential_name_len(const char *name)
4750 size_t n = strlen(name);
4753 for (i = n - 5; i >= 0; i--) {
4754 if (bpf_core_is_flavor_sep(name + i))
4760 static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
4766 static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
4767 size_t local_essent_len,
4768 const struct btf *targ_btf,
4769 const char *targ_btf_name,
4771 struct bpf_core_cand_list *cands)
4773 struct bpf_core_cand *new_cands, *cand;
4774 const struct btf_type *t;
4775 const char *targ_name;
4776 size_t targ_essent_len;
4779 n = btf__get_nr_types(targ_btf);
4780 for (i = targ_start_id; i <= n; i++) {
4781 t = btf__type_by_id(targ_btf, i);
4782 if (btf_kind(t) != btf_kind(local_cand->t))
4785 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4786 if (str_is_empty(targ_name))
4789 targ_essent_len = bpf_core_essential_name_len(targ_name);
4790 if (targ_essent_len != local_essent_len)
4793 if (strncmp(local_cand->name, targ_name, local_essent_len) != 0)
4796 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
4797 local_cand->id, btf_kind_str(local_cand->t),
4798 local_cand->name, i, btf_kind_str(t), targ_name,
4800 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
4801 sizeof(*cands->cands));
4805 cand = &new_cands[cands->len];
4806 cand->btf = targ_btf;
4808 cand->name = targ_name;
4811 cands->cands = new_cands;
4817 static int load_module_btfs(struct bpf_object *obj)
4819 struct bpf_btf_info info;
4820 struct module_btf *mod_btf;
4826 if (obj->btf_modules_loaded)
4829 if (obj->gen_loader)
4832 /* don't do this again, even if we find no module BTFs */
4833 obj->btf_modules_loaded = true;
4835 /* kernel too old to support module BTFs */
4836 if (!kernel_supports(obj, FEAT_MODULE_BTF))
4840 err = bpf_btf_get_next_id(id, &id);
4841 if (err && errno == ENOENT)
4845 pr_warn("failed to iterate BTF objects: %d\n", err);
4849 fd = bpf_btf_get_fd_by_id(id);
4851 if (errno == ENOENT)
4852 continue; /* expected race: BTF was unloaded */
4854 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
4859 memset(&info, 0, sizeof(info));
4860 info.name = ptr_to_u64(name);
4861 info.name_len = sizeof(name);
4863 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4866 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
4870 /* ignore non-module BTFs */
4871 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
4876 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
4877 err = libbpf_get_error(btf);
4879 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
4884 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
4885 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4889 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
4894 mod_btf->name = strdup(name);
4895 if (!mod_btf->name) {
4909 static struct bpf_core_cand_list *
4910 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
4912 struct bpf_core_cand local_cand = {};
4913 struct bpf_core_cand_list *cands;
4914 const struct btf *main_btf;
4915 size_t local_essent_len;
4918 local_cand.btf = local_btf;
4919 local_cand.t = btf__type_by_id(local_btf, local_type_id);
4921 return ERR_PTR(-EINVAL);
4923 local_cand.name = btf__name_by_offset(local_btf, local_cand.t->name_off);
4924 if (str_is_empty(local_cand.name))
4925 return ERR_PTR(-EINVAL);
4926 local_essent_len = bpf_core_essential_name_len(local_cand.name);
4928 cands = calloc(1, sizeof(*cands));
4930 return ERR_PTR(-ENOMEM);
4932 /* Attempt to find target candidates in vmlinux BTF first */
4933 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
4934 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
4938 /* if vmlinux BTF has any candidate, don't got for module BTFs */
4942 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
4943 if (obj->btf_vmlinux_override)
4946 /* now look through module BTFs, trying to still find candidates */
4947 err = load_module_btfs(obj);
4951 for (i = 0; i < obj->btf_module_cnt; i++) {
4952 err = bpf_core_add_cands(&local_cand, local_essent_len,
4953 obj->btf_modules[i].btf,
4954 obj->btf_modules[i].name,
4955 btf__get_nr_types(obj->btf_vmlinux) + 1,
4963 bpf_core_free_cands(cands);
4964 return ERR_PTR(err);
4967 /* Check local and target types for compatibility. This check is used for
4968 * type-based CO-RE relocations and follow slightly different rules than
4969 * field-based relocations. This function assumes that root types were already
4970 * checked for name match. Beyond that initial root-level name check, names
4971 * are completely ignored. Compatibility rules are as follows:
4972 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
4973 * kind should match for local and target types (i.e., STRUCT is not
4974 * compatible with UNION);
4975 * - for ENUMs, the size is ignored;
4976 * - for INT, size and signedness are ignored;
4977 * - for ARRAY, dimensionality is ignored, element types are checked for
4978 * compatibility recursively;
4979 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
4980 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
4981 * - FUNC_PROTOs are compatible if they have compatible signature: same
4982 * number of input args and compatible return and argument types.
4983 * These rules are not set in stone and probably will be adjusted as we get
4984 * more experience with using BPF CO-RE relocations.
4986 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
4987 const struct btf *targ_btf, __u32 targ_id)
4989 const struct btf_type *local_type, *targ_type;
4990 int depth = 32; /* max recursion depth */
4992 /* caller made sure that names match (ignoring flavor suffix) */
4993 local_type = btf__type_by_id(local_btf, local_id);
4994 targ_type = btf__type_by_id(targ_btf, targ_id);
4995 if (btf_kind(local_type) != btf_kind(targ_type))
5003 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5004 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5005 if (!local_type || !targ_type)
5008 if (btf_kind(local_type) != btf_kind(targ_type))
5011 switch (btf_kind(local_type)) {
5013 case BTF_KIND_STRUCT:
5014 case BTF_KIND_UNION:
5019 /* just reject deprecated bitfield-like integers; all other
5020 * integers are by default compatible between each other
5022 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5024 local_id = local_type->type;
5025 targ_id = targ_type->type;
5027 case BTF_KIND_ARRAY:
5028 local_id = btf_array(local_type)->type;
5029 targ_id = btf_array(targ_type)->type;
5031 case BTF_KIND_FUNC_PROTO: {
5032 struct btf_param *local_p = btf_params(local_type);
5033 struct btf_param *targ_p = btf_params(targ_type);
5034 __u16 local_vlen = btf_vlen(local_type);
5035 __u16 targ_vlen = btf_vlen(targ_type);
5038 if (local_vlen != targ_vlen)
5041 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5042 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5043 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5044 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5049 /* tail recurse for return type check */
5050 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5051 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5055 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5056 btf_kind_str(local_type), local_id, targ_id);
5061 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5066 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5071 static void *u32_as_hash_key(__u32 x)
5073 return (void *)(uintptr_t)x;
5076 static int bpf_core_apply_relo(struct bpf_program *prog,
5077 const struct bpf_core_relo *relo,
5079 const struct btf *local_btf,
5080 struct hashmap *cand_cache)
5082 const void *type_key = u32_as_hash_key(relo->type_id);
5083 struct bpf_core_cand_list *cands = NULL;
5084 const char *prog_name = prog->name;
5085 const struct btf_type *local_type;
5086 const char *local_name;
5087 __u32 local_id = relo->type_id;
5088 struct bpf_insn *insn;
5091 if (relo->insn_off % BPF_INSN_SZ)
5093 insn_idx = relo->insn_off / BPF_INSN_SZ;
5094 /* adjust insn_idx from section frame of reference to the local
5095 * program's frame of reference; (sub-)program code is not yet
5096 * relocated, so it's enough to just subtract in-section offset
5098 insn_idx = insn_idx - prog->sec_insn_off;
5099 if (insn_idx > prog->insns_cnt)
5101 insn = &prog->insns[insn_idx];
5103 local_type = btf__type_by_id(local_btf, local_id);
5107 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5111 if (prog->obj->gen_loader) {
5112 pr_warn("// TODO core_relo: prog %td insn[%d] %s kind %d\n",
5113 prog - prog->obj->programs, relo->insn_off / 8,
5114 local_name, relo->kind);
5118 if (relo->kind != BPF_TYPE_ID_LOCAL &&
5119 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5120 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5121 if (IS_ERR(cands)) {
5122 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5123 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5124 local_name, PTR_ERR(cands));
5125 return PTR_ERR(cands);
5127 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5129 bpf_core_free_cands(cands);
5134 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo, relo_idx, local_btf, cands);
5138 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5140 const struct btf_ext_info_sec *sec;
5141 const struct bpf_core_relo *rec;
5142 const struct btf_ext_info *seg;
5143 struct hashmap_entry *entry;
5144 struct hashmap *cand_cache = NULL;
5145 struct bpf_program *prog;
5146 const char *sec_name;
5147 int i, err = 0, insn_idx, sec_idx;
5149 if (obj->btf_ext->core_relo_info.len == 0)
5152 if (targ_btf_path) {
5153 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5154 err = libbpf_get_error(obj->btf_vmlinux_override);
5156 pr_warn("failed to parse target BTF: %d\n", err);
5161 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5162 if (IS_ERR(cand_cache)) {
5163 err = PTR_ERR(cand_cache);
5167 seg = &obj->btf_ext->core_relo_info;
5168 for_each_btf_ext_sec(seg, sec) {
5169 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5170 if (str_is_empty(sec_name)) {
5174 /* bpf_object's ELF is gone by now so it's not easy to find
5175 * section index by section name, but we can find *any*
5176 * bpf_program within desired section name and use it's
5177 * prog->sec_idx to do a proper search by section index and
5178 * instruction offset
5181 for (i = 0; i < obj->nr_programs; i++) {
5182 prog = &obj->programs[i];
5183 if (strcmp(prog->sec_name, sec_name) == 0)
5187 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5190 sec_idx = prog->sec_idx;
5192 pr_debug("sec '%s': found %d CO-RE relocations\n",
5193 sec_name, sec->num_info);
5195 for_each_btf_ext_rec(seg, sec, i, rec) {
5196 insn_idx = rec->insn_off / BPF_INSN_SZ;
5197 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5199 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5200 sec_name, insn_idx, i);
5204 /* no need to apply CO-RE relocation if the program is
5205 * not going to be loaded
5210 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
5212 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5213 prog->name, i, err);
5220 /* obj->btf_vmlinux and module BTFs are freed after object load */
5221 btf__free(obj->btf_vmlinux_override);
5222 obj->btf_vmlinux_override = NULL;
5224 if (!IS_ERR_OR_NULL(cand_cache)) {
5225 hashmap__for_each_entry(cand_cache, entry, i) {
5226 bpf_core_free_cands(entry->value);
5228 hashmap__free(cand_cache);
5233 /* Relocate data references within program code:
5235 * - global variable references;
5236 * - extern references.
5239 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5243 for (i = 0; i < prog->nr_reloc; i++) {
5244 struct reloc_desc *relo = &prog->reloc_desc[i];
5245 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5246 struct extern_desc *ext;
5248 switch (relo->type) {
5250 if (obj->gen_loader) {
5251 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5252 insn[0].imm = relo->map_idx;
5254 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5255 insn[0].imm = obj->maps[relo->map_idx].fd;
5259 insn[1].imm = insn[0].imm + relo->sym_off;
5260 if (obj->gen_loader) {
5261 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5262 insn[0].imm = relo->map_idx;
5264 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5265 insn[0].imm = obj->maps[relo->map_idx].fd;
5268 case RELO_EXTERN_VAR:
5269 ext = &obj->externs[relo->sym_off];
5270 if (ext->type == EXT_KCFG) {
5271 if (obj->gen_loader) {
5272 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5273 insn[0].imm = obj->kconfig_map_idx;
5275 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5276 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5278 insn[1].imm = ext->kcfg.data_off;
5279 } else /* EXT_KSYM */ {
5280 if (ext->ksym.type_id) { /* typed ksyms */
5281 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5282 insn[0].imm = ext->ksym.kernel_btf_id;
5283 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5284 } else { /* typeless ksyms */
5285 insn[0].imm = (__u32)ext->ksym.addr;
5286 insn[1].imm = ext->ksym.addr >> 32;
5290 case RELO_EXTERN_FUNC:
5291 ext = &obj->externs[relo->sym_off];
5292 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5293 insn[0].imm = ext->ksym.kernel_btf_id;
5295 case RELO_SUBPROG_ADDR:
5296 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5297 pr_warn("prog '%s': relo #%d: bad insn\n",
5301 /* handled already */
5304 /* handled already */
5307 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5308 prog->name, i, relo->type);
5316 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5317 const struct bpf_program *prog,
5318 const struct btf_ext_info *ext_info,
5319 void **prog_info, __u32 *prog_rec_cnt,
5322 void *copy_start = NULL, *copy_end = NULL;
5323 void *rec, *rec_end, *new_prog_info;
5324 const struct btf_ext_info_sec *sec;
5325 size_t old_sz, new_sz;
5326 const char *sec_name;
5329 for_each_btf_ext_sec(ext_info, sec) {
5330 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5333 if (strcmp(sec_name, prog->sec_name) != 0)
5336 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5337 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5339 if (insn_off < prog->sec_insn_off)
5341 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5346 copy_end = rec + ext_info->rec_size;
5352 /* append func/line info of a given (sub-)program to the main
5353 * program func/line info
5355 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5356 new_sz = old_sz + (copy_end - copy_start);
5357 new_prog_info = realloc(*prog_info, new_sz);
5360 *prog_info = new_prog_info;
5361 *prog_rec_cnt = new_sz / ext_info->rec_size;
5362 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5364 /* Kernel instruction offsets are in units of 8-byte
5365 * instructions, while .BTF.ext instruction offsets generated
5366 * by Clang are in units of bytes. So convert Clang offsets
5367 * into kernel offsets and adjust offset according to program
5368 * relocated position.
5370 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5371 rec = new_prog_info + old_sz;
5372 rec_end = new_prog_info + new_sz;
5373 for (; rec < rec_end; rec += ext_info->rec_size) {
5374 __u32 *insn_off = rec;
5376 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5378 *prog_rec_sz = ext_info->rec_size;
5386 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5387 struct bpf_program *main_prog,
5388 const struct bpf_program *prog)
5392 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5393 * supprot func/line info
5395 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5398 /* only attempt func info relocation if main program's func_info
5399 * relocation was successful
5401 if (main_prog != prog && !main_prog->func_info)
5404 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5405 &main_prog->func_info,
5406 &main_prog->func_info_cnt,
5407 &main_prog->func_info_rec_size);
5409 if (err != -ENOENT) {
5410 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5414 if (main_prog->func_info) {
5416 * Some info has already been found but has problem
5417 * in the last btf_ext reloc. Must have to error out.
5419 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5422 /* Have problem loading the very first info. Ignore the rest. */
5423 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5428 /* don't relocate line info if main program's relocation failed */
5429 if (main_prog != prog && !main_prog->line_info)
5432 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5433 &main_prog->line_info,
5434 &main_prog->line_info_cnt,
5435 &main_prog->line_info_rec_size);
5437 if (err != -ENOENT) {
5438 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5442 if (main_prog->line_info) {
5444 * Some info has already been found but has problem
5445 * in the last btf_ext reloc. Must have to error out.
5447 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5450 /* Have problem loading the very first info. Ignore the rest. */
5451 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5457 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5459 size_t insn_idx = *(const size_t *)key;
5460 const struct reloc_desc *relo = elem;
5462 if (insn_idx == relo->insn_idx)
5464 return insn_idx < relo->insn_idx ? -1 : 1;
5467 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5469 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5470 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5473 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5475 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5476 struct reloc_desc *relos;
5479 if (main_prog == subprog)
5481 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5484 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5485 sizeof(*relos) * subprog->nr_reloc);
5487 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5488 relos[i].insn_idx += subprog->sub_insn_off;
5489 /* After insn_idx adjustment the 'relos' array is still sorted
5490 * by insn_idx and doesn't break bsearch.
5492 main_prog->reloc_desc = relos;
5493 main_prog->nr_reloc = new_cnt;
5498 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5499 struct bpf_program *prog)
5501 size_t sub_insn_idx, insn_idx, new_cnt;
5502 struct bpf_program *subprog;
5503 struct bpf_insn *insns, *insn;
5504 struct reloc_desc *relo;
5507 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5511 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5512 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5513 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
5516 relo = find_prog_insn_relo(prog, insn_idx);
5517 if (relo && relo->type == RELO_EXTERN_FUNC)
5518 /* kfunc relocations will be handled later
5519 * in bpf_object__relocate_data()
5522 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
5523 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
5524 prog->name, insn_idx, relo->type);
5525 return -LIBBPF_ERRNO__RELOC;
5528 /* sub-program instruction index is a combination of
5529 * an offset of a symbol pointed to by relocation and
5530 * call instruction's imm field; for global functions,
5531 * call always has imm = -1, but for static functions
5532 * relocation is against STT_SECTION and insn->imm
5533 * points to a start of a static function
5535 * for subprog addr relocation, the relo->sym_off + insn->imm is
5536 * the byte offset in the corresponding section.
5538 if (relo->type == RELO_CALL)
5539 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
5541 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
5542 } else if (insn_is_pseudo_func(insn)) {
5544 * RELO_SUBPROG_ADDR relo is always emitted even if both
5545 * functions are in the same section, so it shouldn't reach here.
5547 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
5548 prog->name, insn_idx);
5549 return -LIBBPF_ERRNO__RELOC;
5551 /* if subprogram call is to a static function within
5552 * the same ELF section, there won't be any relocation
5553 * emitted, but it also means there is no additional
5554 * offset necessary, insns->imm is relative to
5555 * instruction's original position within the section
5557 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
5560 /* we enforce that sub-programs should be in .text section */
5561 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
5563 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
5565 return -LIBBPF_ERRNO__RELOC;
5568 /* if it's the first call instruction calling into this
5569 * subprogram (meaning this subprog hasn't been processed
5570 * yet) within the context of current main program:
5571 * - append it at the end of main program's instructions blog;
5572 * - process is recursively, while current program is put on hold;
5573 * - if that subprogram calls some other not yet processes
5574 * subprogram, same thing will happen recursively until
5575 * there are no more unprocesses subprograms left to append
5578 if (subprog->sub_insn_off == 0) {
5579 subprog->sub_insn_off = main_prog->insns_cnt;
5581 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
5582 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
5584 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
5587 main_prog->insns = insns;
5588 main_prog->insns_cnt = new_cnt;
5590 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
5591 subprog->insns_cnt * sizeof(*insns));
5593 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
5594 main_prog->name, subprog->insns_cnt, subprog->name);
5596 /* The subprog insns are now appended. Append its relos too. */
5597 err = append_subprog_relos(main_prog, subprog);
5600 err = bpf_object__reloc_code(obj, main_prog, subprog);
5605 /* main_prog->insns memory could have been re-allocated, so
5606 * calculate pointer again
5608 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5609 /* calculate correct instruction position within current main
5610 * prog; each main prog can have a different set of
5611 * subprograms appended (potentially in different order as
5612 * well), so position of any subprog can be different for
5613 * different main programs */
5614 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
5616 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
5617 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
5624 * Relocate sub-program calls.
5626 * Algorithm operates as follows. Each entry-point BPF program (referred to as
5627 * main prog) is processed separately. For each subprog (non-entry functions,
5628 * that can be called from either entry progs or other subprogs) gets their
5629 * sub_insn_off reset to zero. This serves as indicator that this subprogram
5630 * hasn't been yet appended and relocated within current main prog. Once its
5631 * relocated, sub_insn_off will point at the position within current main prog
5632 * where given subprog was appended. This will further be used to relocate all
5633 * the call instructions jumping into this subprog.
5635 * We start with main program and process all call instructions. If the call
5636 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
5637 * is zero), subprog instructions are appended at the end of main program's
5638 * instruction array. Then main program is "put on hold" while we recursively
5639 * process newly appended subprogram. If that subprogram calls into another
5640 * subprogram that hasn't been appended, new subprogram is appended again to
5641 * the *main* prog's instructions (subprog's instructions are always left
5642 * untouched, as they need to be in unmodified state for subsequent main progs
5643 * and subprog instructions are always sent only as part of a main prog) and
5644 * the process continues recursively. Once all the subprogs called from a main
5645 * prog or any of its subprogs are appended (and relocated), all their
5646 * positions within finalized instructions array are known, so it's easy to
5647 * rewrite call instructions with correct relative offsets, corresponding to
5648 * desired target subprog.
5650 * Its important to realize that some subprogs might not be called from some
5651 * main prog and any of its called/used subprogs. Those will keep their
5652 * subprog->sub_insn_off as zero at all times and won't be appended to current
5653 * main prog and won't be relocated within the context of current main prog.
5654 * They might still be used from other main progs later.
5656 * Visually this process can be shown as below. Suppose we have two main
5657 * programs mainA and mainB and BPF object contains three subprogs: subA,
5658 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
5659 * subC both call subB:
5661 * +--------+ +-------+
5663 * +--+---+ +--+-+-+ +---+--+
5664 * | subA | | subB | | subC |
5665 * +--+---+ +------+ +---+--+
5668 * +---+-------+ +------+----+
5669 * | mainA | | mainB |
5670 * +-----------+ +-----------+
5672 * We'll start relocating mainA, will find subA, append it and start
5673 * processing sub A recursively:
5675 * +-----------+------+
5677 * +-----------+------+
5679 * At this point we notice that subB is used from subA, so we append it and
5680 * relocate (there are no further subcalls from subB):
5682 * +-----------+------+------+
5683 * | mainA | subA | subB |
5684 * +-----------+------+------+
5686 * At this point, we relocate subA calls, then go one level up and finish with
5687 * relocatin mainA calls. mainA is done.
5689 * For mainB process is similar but results in different order. We start with
5690 * mainB and skip subA and subB, as mainB never calls them (at least
5691 * directly), but we see subC is needed, so we append and start processing it:
5693 * +-----------+------+
5695 * +-----------+------+
5696 * Now we see subC needs subB, so we go back to it, append and relocate it:
5698 * +-----------+------+------+
5699 * | mainB | subC | subB |
5700 * +-----------+------+------+
5702 * At this point we unwind recursion, relocate calls in subC, then in mainB.
5705 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
5707 struct bpf_program *subprog;
5710 /* mark all subprogs as not relocated (yet) within the context of
5711 * current main program
5713 for (i = 0; i < obj->nr_programs; i++) {
5714 subprog = &obj->programs[i];
5715 if (!prog_is_subprog(obj, subprog))
5718 subprog->sub_insn_off = 0;
5721 err = bpf_object__reloc_code(obj, prog, prog);
5730 bpf_object__free_relocs(struct bpf_object *obj)
5732 struct bpf_program *prog;
5735 /* free up relocation descriptors */
5736 for (i = 0; i < obj->nr_programs; i++) {
5737 prog = &obj->programs[i];
5738 zfree(&prog->reloc_desc);
5744 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
5746 struct bpf_program *prog;
5751 err = bpf_object__relocate_core(obj, targ_btf_path);
5753 pr_warn("failed to perform CO-RE relocations: %d\n",
5759 /* Before relocating calls pre-process relocations and mark
5760 * few ld_imm64 instructions that points to subprogs.
5761 * Otherwise bpf_object__reloc_code() later would have to consider
5762 * all ld_imm64 insns as relocation candidates. That would
5763 * reduce relocation speed, since amount of find_prog_insn_relo()
5764 * would increase and most of them will fail to find a relo.
5766 for (i = 0; i < obj->nr_programs; i++) {
5767 prog = &obj->programs[i];
5768 for (j = 0; j < prog->nr_reloc; j++) {
5769 struct reloc_desc *relo = &prog->reloc_desc[j];
5770 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5772 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
5773 if (relo->type == RELO_SUBPROG_ADDR)
5774 insn[0].src_reg = BPF_PSEUDO_FUNC;
5778 /* relocate subprogram calls and append used subprograms to main
5779 * programs; each copy of subprogram code needs to be relocated
5780 * differently for each main program, because its code location might
5782 * Append subprog relos to main programs to allow data relos to be
5783 * processed after text is completely relocated.
5785 for (i = 0; i < obj->nr_programs; i++) {
5786 prog = &obj->programs[i];
5787 /* sub-program's sub-calls are relocated within the context of
5788 * its main program only
5790 if (prog_is_subprog(obj, prog))
5793 err = bpf_object__relocate_calls(obj, prog);
5795 pr_warn("prog '%s': failed to relocate calls: %d\n",
5800 /* Process data relos for main programs */
5801 for (i = 0; i < obj->nr_programs; i++) {
5802 prog = &obj->programs[i];
5803 if (prog_is_subprog(obj, prog))
5805 err = bpf_object__relocate_data(obj, prog);
5807 pr_warn("prog '%s': failed to relocate data references: %d\n",
5812 if (!obj->gen_loader)
5813 bpf_object__free_relocs(obj);
5817 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5818 GElf_Shdr *shdr, Elf_Data *data);
5820 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5821 GElf_Shdr *shdr, Elf_Data *data)
5823 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
5824 int i, j, nrels, new_sz;
5825 const struct btf_var_secinfo *vi = NULL;
5826 const struct btf_type *sec, *var, *def;
5827 struct bpf_map *map = NULL, *targ_map;
5828 const struct btf_member *member;
5829 const char *name, *mname;
5836 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5838 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5842 symbols = obj->efile.symbols;
5843 nrels = shdr->sh_size / shdr->sh_entsize;
5844 for (i = 0; i < nrels; i++) {
5845 if (!gelf_getrel(data, i, &rel)) {
5846 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5847 return -LIBBPF_ERRNO__FORMAT;
5849 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5850 pr_warn(".maps relo #%d: symbol %zx not found\n",
5851 i, (size_t)GELF_R_SYM(rel.r_info));
5852 return -LIBBPF_ERRNO__FORMAT;
5854 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
5855 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5856 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5858 return -LIBBPF_ERRNO__RELOC;
5861 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5862 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5863 (size_t)rel.r_offset, sym.st_name, name);
5865 for (j = 0; j < obj->nr_maps; j++) {
5866 map = &obj->maps[j];
5867 if (map->sec_idx != obj->efile.btf_maps_shndx)
5870 vi = btf_var_secinfos(sec) + map->btf_var_idx;
5871 if (vi->offset <= rel.r_offset &&
5872 rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
5875 if (j == obj->nr_maps) {
5876 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5877 i, name, (size_t)rel.r_offset);
5881 if (!bpf_map_type__is_map_in_map(map->def.type))
5883 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5884 map->def.key_size != sizeof(int)) {
5885 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5886 i, map->name, sizeof(int));
5890 targ_map = bpf_object__find_map_by_name(obj, name);
5894 var = btf__type_by_id(obj->btf, vi->type);
5895 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5896 if (btf_vlen(def) == 0)
5898 member = btf_members(def) + btf_vlen(def) - 1;
5899 mname = btf__name_by_offset(obj->btf, member->name_off);
5900 if (strcmp(mname, "values"))
5903 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5904 if (rel.r_offset - vi->offset < moff)
5907 moff = rel.r_offset - vi->offset - moff;
5908 /* here we use BPF pointer size, which is always 64 bit, as we
5909 * are parsing ELF that was built for BPF target
5911 if (moff % bpf_ptr_sz)
5914 if (moff >= map->init_slots_sz) {
5916 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
5919 map->init_slots = tmp;
5920 memset(map->init_slots + map->init_slots_sz, 0,
5921 (new_sz - map->init_slots_sz) * host_ptr_sz);
5922 map->init_slots_sz = new_sz;
5924 map->init_slots[moff] = targ_map;
5926 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5927 i, map->name, moff, name);
5933 static int cmp_relocs(const void *_a, const void *_b)
5935 const struct reloc_desc *a = _a;
5936 const struct reloc_desc *b = _b;
5938 if (a->insn_idx != b->insn_idx)
5939 return a->insn_idx < b->insn_idx ? -1 : 1;
5941 /* no two relocations should have the same insn_idx, but ... */
5942 if (a->type != b->type)
5943 return a->type < b->type ? -1 : 1;
5948 static int bpf_object__collect_relos(struct bpf_object *obj)
5952 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5953 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5954 Elf_Data *data = obj->efile.reloc_sects[i].data;
5955 int idx = shdr->sh_info;
5957 if (shdr->sh_type != SHT_REL) {
5958 pr_warn("internal error at %d\n", __LINE__);
5959 return -LIBBPF_ERRNO__INTERNAL;
5962 if (idx == obj->efile.st_ops_shndx)
5963 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
5964 else if (idx == obj->efile.btf_maps_shndx)
5965 err = bpf_object__collect_map_relos(obj, shdr, data);
5967 err = bpf_object__collect_prog_relos(obj, shdr, data);
5972 for (i = 0; i < obj->nr_programs; i++) {
5973 struct bpf_program *p = &obj->programs[i];
5978 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
5983 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
5985 if (BPF_CLASS(insn->code) == BPF_JMP &&
5986 BPF_OP(insn->code) == BPF_CALL &&
5987 BPF_SRC(insn->code) == BPF_K &&
5988 insn->src_reg == 0 &&
5989 insn->dst_reg == 0) {
5990 *func_id = insn->imm;
5996 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
5998 struct bpf_insn *insn = prog->insns;
5999 enum bpf_func_id func_id;
6002 if (obj->gen_loader)
6005 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6006 if (!insn_is_helper_call(insn, &func_id))
6009 /* on kernels that don't yet support
6010 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6011 * to bpf_probe_read() which works well for old kernels
6014 case BPF_FUNC_probe_read_kernel:
6015 case BPF_FUNC_probe_read_user:
6016 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6017 insn->imm = BPF_FUNC_probe_read;
6019 case BPF_FUNC_probe_read_kernel_str:
6020 case BPF_FUNC_probe_read_user_str:
6021 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6022 insn->imm = BPF_FUNC_probe_read_str;
6032 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
6033 char *license, __u32 kern_version, int *pfd)
6035 struct bpf_prog_load_params load_attr = {};
6036 char *cp, errmsg[STRERR_BUFSIZE];
6037 size_t log_buf_size = 0;
6038 char *log_buf = NULL;
6041 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6043 * The program type must be set. Most likely we couldn't find a proper
6044 * section definition at load time, and thus we didn't infer the type.
6046 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6047 prog->name, prog->sec_name);
6051 if (!insns || !insns_cnt)
6054 load_attr.prog_type = prog->type;
6055 /* old kernels might not support specifying expected_attach_type */
6056 if (!kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE) && prog->sec_def &&
6057 prog->sec_def->is_exp_attach_type_optional)
6058 load_attr.expected_attach_type = 0;
6060 load_attr.expected_attach_type = prog->expected_attach_type;
6061 if (kernel_supports(prog->obj, FEAT_PROG_NAME))
6062 load_attr.name = prog->name;
6063 load_attr.insns = insns;
6064 load_attr.insn_cnt = insns_cnt;
6065 load_attr.license = license;
6066 load_attr.attach_btf_id = prog->attach_btf_id;
6067 if (prog->attach_prog_fd)
6068 load_attr.attach_prog_fd = prog->attach_prog_fd;
6070 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6071 load_attr.attach_btf_id = prog->attach_btf_id;
6072 load_attr.kern_version = kern_version;
6073 load_attr.prog_ifindex = prog->prog_ifindex;
6075 /* specify func_info/line_info only if kernel supports them */
6076 btf_fd = bpf_object__btf_fd(prog->obj);
6077 if (btf_fd >= 0 && kernel_supports(prog->obj, FEAT_BTF_FUNC)) {
6078 load_attr.prog_btf_fd = btf_fd;
6079 load_attr.func_info = prog->func_info;
6080 load_attr.func_info_rec_size = prog->func_info_rec_size;
6081 load_attr.func_info_cnt = prog->func_info_cnt;
6082 load_attr.line_info = prog->line_info;
6083 load_attr.line_info_rec_size = prog->line_info_rec_size;
6084 load_attr.line_info_cnt = prog->line_info_cnt;
6086 load_attr.log_level = prog->log_level;
6087 load_attr.prog_flags = prog->prog_flags;
6089 if (prog->obj->gen_loader) {
6090 bpf_gen__prog_load(prog->obj->gen_loader, &load_attr,
6091 prog - prog->obj->programs);
6097 log_buf = malloc(log_buf_size);
6104 load_attr.log_buf = log_buf;
6105 load_attr.log_buf_sz = log_buf_size;
6106 ret = libbpf__bpf_prog_load(&load_attr);
6109 if (log_buf && load_attr.log_level)
6110 pr_debug("verifier log:\n%s", log_buf);
6112 if (prog->obj->rodata_map_idx >= 0 &&
6113 kernel_supports(prog->obj, FEAT_PROG_BIND_MAP)) {
6114 struct bpf_map *rodata_map =
6115 &prog->obj->maps[prog->obj->rodata_map_idx];
6117 if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) {
6118 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6119 pr_warn("prog '%s': failed to bind .rodata map: %s\n",
6121 /* Don't fail hard if can't bind rodata. */
6130 if (!log_buf || errno == ENOSPC) {
6131 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
6137 ret = errno ? -errno : -LIBBPF_ERRNO__LOAD;
6138 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6139 pr_warn("load bpf program failed: %s\n", cp);
6142 if (log_buf && log_buf[0] != '\0') {
6143 ret = -LIBBPF_ERRNO__VERIFY;
6144 pr_warn("-- BEGIN DUMP LOG ---\n");
6145 pr_warn("\n%s\n", log_buf);
6146 pr_warn("-- END LOG --\n");
6147 } else if (load_attr.insn_cnt >= BPF_MAXINSNS) {
6148 pr_warn("Program too large (%zu insns), at most %d insns\n",
6149 load_attr.insn_cnt, BPF_MAXINSNS);
6150 ret = -LIBBPF_ERRNO__PROG2BIG;
6151 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
6152 /* Wrong program type? */
6155 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
6156 load_attr.expected_attach_type = 0;
6157 load_attr.log_buf = NULL;
6158 load_attr.log_buf_sz = 0;
6159 fd = libbpf__bpf_prog_load(&load_attr);
6162 ret = -LIBBPF_ERRNO__PROGTYPE;
6172 static int bpf_program__record_externs(struct bpf_program *prog)
6174 struct bpf_object *obj = prog->obj;
6177 for (i = 0; i < prog->nr_reloc; i++) {
6178 struct reloc_desc *relo = &prog->reloc_desc[i];
6179 struct extern_desc *ext = &obj->externs[relo->sym_off];
6181 switch (relo->type) {
6182 case RELO_EXTERN_VAR:
6183 if (ext->type != EXT_KSYM)
6185 if (!ext->ksym.type_id) {
6186 pr_warn("typeless ksym %s is not supported yet\n",
6190 bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_VAR,
6193 case RELO_EXTERN_FUNC:
6194 bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_FUNC,
6204 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id);
6206 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
6210 if (prog->obj->loaded) {
6211 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6212 return libbpf_err(-EINVAL);
6215 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6216 prog->type == BPF_PROG_TYPE_LSM ||
6217 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6218 int btf_obj_fd = 0, btf_type_id = 0;
6220 err = libbpf_find_attach_btf_id(prog, &btf_obj_fd, &btf_type_id);
6222 return libbpf_err(err);
6224 prog->attach_btf_obj_fd = btf_obj_fd;
6225 prog->attach_btf_id = btf_type_id;
6228 if (prog->instances.nr < 0 || !prog->instances.fds) {
6229 if (prog->preprocessor) {
6230 pr_warn("Internal error: can't load program '%s'\n",
6232 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
6235 prog->instances.fds = malloc(sizeof(int));
6236 if (!prog->instances.fds) {
6237 pr_warn("Not enough memory for BPF fds\n");
6238 return libbpf_err(-ENOMEM);
6240 prog->instances.nr = 1;
6241 prog->instances.fds[0] = -1;
6244 if (!prog->preprocessor) {
6245 if (prog->instances.nr != 1) {
6246 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6247 prog->name, prog->instances.nr);
6249 if (prog->obj->gen_loader)
6250 bpf_program__record_externs(prog);
6251 err = load_program(prog, prog->insns, prog->insns_cnt,
6252 license, kern_ver, &fd);
6254 prog->instances.fds[0] = fd;
6258 for (i = 0; i < prog->instances.nr; i++) {
6259 struct bpf_prog_prep_result result;
6260 bpf_program_prep_t preprocessor = prog->preprocessor;
6262 memset(&result, 0, sizeof(result));
6263 err = preprocessor(prog, i, prog->insns,
6264 prog->insns_cnt, &result);
6266 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6271 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6272 pr_debug("Skip loading the %dth instance of program '%s'\n",
6274 prog->instances.fds[i] = -1;
6280 err = load_program(prog, result.new_insn_ptr,
6281 result.new_insn_cnt, license, kern_ver, &fd);
6283 pr_warn("Loading the %dth instance of program '%s' failed\n",
6290 prog->instances.fds[i] = fd;
6294 pr_warn("failed to load program '%s'\n", prog->name);
6295 zfree(&prog->insns);
6296 prog->insns_cnt = 0;
6297 return libbpf_err(err);
6301 bpf_object__load_progs(struct bpf_object *obj, int log_level)
6303 struct bpf_program *prog;
6307 for (i = 0; i < obj->nr_programs; i++) {
6308 prog = &obj->programs[i];
6309 err = bpf_object__sanitize_prog(obj, prog);
6314 for (i = 0; i < obj->nr_programs; i++) {
6315 prog = &obj->programs[i];
6316 if (prog_is_subprog(obj, prog))
6319 pr_debug("prog '%s': skipped loading\n", prog->name);
6322 prog->log_level |= log_level;
6323 err = bpf_program__load(prog, obj->license, obj->kern_version);
6327 if (obj->gen_loader)
6328 bpf_object__free_relocs(obj);
6332 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6334 static struct bpf_object *
6335 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6336 const struct bpf_object_open_opts *opts)
6338 const char *obj_name, *kconfig, *btf_tmp_path;
6339 struct bpf_program *prog;
6340 struct bpf_object *obj;
6344 if (elf_version(EV_CURRENT) == EV_NONE) {
6345 pr_warn("failed to init libelf for %s\n",
6346 path ? : "(mem buf)");
6347 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6350 if (!OPTS_VALID(opts, bpf_object_open_opts))
6351 return ERR_PTR(-EINVAL);
6353 obj_name = OPTS_GET(opts, object_name, NULL);
6356 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6357 (unsigned long)obj_buf,
6358 (unsigned long)obj_buf_sz);
6359 obj_name = tmp_name;
6362 pr_debug("loading object '%s' from buffer\n", obj_name);
6365 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6369 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
6371 if (strlen(btf_tmp_path) >= PATH_MAX) {
6372 err = -ENAMETOOLONG;
6375 obj->btf_custom_path = strdup(btf_tmp_path);
6376 if (!obj->btf_custom_path) {
6382 kconfig = OPTS_GET(opts, kconfig, NULL);
6384 obj->kconfig = strdup(kconfig);
6385 if (!obj->kconfig) {
6391 err = bpf_object__elf_init(obj);
6392 err = err ? : bpf_object__check_endianness(obj);
6393 err = err ? : bpf_object__elf_collect(obj);
6394 err = err ? : bpf_object__collect_externs(obj);
6395 err = err ? : bpf_object__finalize_btf(obj);
6396 err = err ? : bpf_object__init_maps(obj, opts);
6397 err = err ? : bpf_object__collect_relos(obj);
6400 bpf_object__elf_finish(obj);
6402 bpf_object__for_each_program(prog, obj) {
6403 prog->sec_def = find_sec_def(prog->sec_name);
6404 if (!prog->sec_def) {
6405 /* couldn't guess, but user might manually specify */
6406 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6407 prog->name, prog->sec_name);
6411 if (prog->sec_def->is_sleepable)
6412 prog->prog_flags |= BPF_F_SLEEPABLE;
6413 bpf_program__set_type(prog, prog->sec_def->prog_type);
6414 bpf_program__set_expected_attach_type(prog,
6415 prog->sec_def->expected_attach_type);
6417 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6418 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6419 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6424 bpf_object__close(obj);
6425 return ERR_PTR(err);
6428 static struct bpf_object *
6429 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
6431 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6432 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
6435 /* param validation */
6439 pr_debug("loading %s\n", attr->file);
6440 return __bpf_object__open(attr->file, NULL, 0, &opts);
6443 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
6445 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
6448 struct bpf_object *bpf_object__open(const char *path)
6450 struct bpf_object_open_attr attr = {
6452 .prog_type = BPF_PROG_TYPE_UNSPEC,
6455 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6459 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
6462 return libbpf_err_ptr(-EINVAL);
6464 pr_debug("loading %s\n", path);
6466 return libbpf_ptr(__bpf_object__open(path, NULL, 0, opts));
6470 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
6471 const struct bpf_object_open_opts *opts)
6473 if (!obj_buf || obj_buf_sz == 0)
6474 return libbpf_err_ptr(-EINVAL);
6476 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, opts));
6480 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
6483 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6484 .object_name = name,
6485 /* wrong default, but backwards-compatible */
6486 .relaxed_maps = true,
6489 /* returning NULL is wrong, but backwards-compatible */
6490 if (!obj_buf || obj_buf_sz == 0)
6491 return errno = EINVAL, NULL;
6493 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, &opts));
6496 int bpf_object__unload(struct bpf_object *obj)
6501 return libbpf_err(-EINVAL);
6503 for (i = 0; i < obj->nr_maps; i++) {
6504 zclose(obj->maps[i].fd);
6505 if (obj->maps[i].st_ops)
6506 zfree(&obj->maps[i].st_ops->kern_vdata);
6509 for (i = 0; i < obj->nr_programs; i++)
6510 bpf_program__unload(&obj->programs[i]);
6515 static int bpf_object__sanitize_maps(struct bpf_object *obj)
6519 bpf_object__for_each_map(m, obj) {
6520 if (!bpf_map__is_internal(m))
6522 if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) {
6523 pr_warn("kernel doesn't support global data\n");
6526 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
6527 m->def.map_flags ^= BPF_F_MMAPABLE;
6533 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
6535 char sym_type, sym_name[500];
6536 unsigned long long sym_addr;
6537 const struct btf_type *t;
6538 struct extern_desc *ext;
6542 f = fopen("/proc/kallsyms", "r");
6545 pr_warn("failed to open /proc/kallsyms: %d\n", err);
6550 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
6551 &sym_addr, &sym_type, sym_name);
6552 if (ret == EOF && feof(f))
6555 pr_warn("failed to read kallsyms entry: %d\n", ret);
6560 ext = find_extern_by_name(obj, sym_name);
6561 if (!ext || ext->type != EXT_KSYM)
6564 t = btf__type_by_id(obj->btf, ext->btf_id);
6568 if (ext->is_set && ext->ksym.addr != sym_addr) {
6569 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
6570 sym_name, ext->ksym.addr, sym_addr);
6576 ext->ksym.addr = sym_addr;
6577 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
6586 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
6587 __u16 kind, struct btf **res_btf,
6590 int i, id, btf_fd, err;
6593 btf = obj->btf_vmlinux;
6595 id = btf__find_by_name_kind(btf, ksym_name, kind);
6597 if (id == -ENOENT) {
6598 err = load_module_btfs(obj);
6602 for (i = 0; i < obj->btf_module_cnt; i++) {
6603 btf = obj->btf_modules[i].btf;
6604 /* we assume module BTF FD is always >0 */
6605 btf_fd = obj->btf_modules[i].fd;
6606 id = btf__find_by_name_kind(btf, ksym_name, kind);
6612 pr_warn("extern (%s ksym) '%s': failed to find BTF ID in kernel BTF(s).\n",
6613 __btf_kind_str(kind), ksym_name);
6618 *res_btf_fd = btf_fd;
6622 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
6623 struct extern_desc *ext)
6625 const struct btf_type *targ_var, *targ_type;
6626 __u32 targ_type_id, local_type_id;
6627 const char *targ_var_name;
6628 int id, btf_fd = 0, err;
6629 struct btf *btf = NULL;
6631 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &btf_fd);
6635 /* find local type_id */
6636 local_type_id = ext->ksym.type_id;
6638 /* find target type_id */
6639 targ_var = btf__type_by_id(btf, id);
6640 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
6641 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
6643 err = bpf_core_types_are_compat(obj->btf, local_type_id,
6646 const struct btf_type *local_type;
6647 const char *targ_name, *local_name;
6649 local_type = btf__type_by_id(obj->btf, local_type_id);
6650 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
6651 targ_name = btf__name_by_offset(btf, targ_type->name_off);
6653 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
6654 ext->name, local_type_id,
6655 btf_kind_str(local_type), local_name, targ_type_id,
6656 btf_kind_str(targ_type), targ_name);
6661 ext->ksym.kernel_btf_obj_fd = btf_fd;
6662 ext->ksym.kernel_btf_id = id;
6663 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
6664 ext->name, id, btf_kind_str(targ_var), targ_var_name);
6669 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
6670 struct extern_desc *ext)
6672 int local_func_proto_id, kfunc_proto_id, kfunc_id;
6673 const struct btf_type *kern_func;
6674 struct btf *kern_btf = NULL;
6675 int ret, kern_btf_fd = 0;
6677 local_func_proto_id = ext->ksym.type_id;
6679 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC,
6680 &kern_btf, &kern_btf_fd);
6682 pr_warn("extern (func ksym) '%s': not found in kernel BTF\n",
6687 if (kern_btf != obj->btf_vmlinux) {
6688 pr_warn("extern (func ksym) '%s': function in kernel module is not supported\n",
6693 kern_func = btf__type_by_id(kern_btf, kfunc_id);
6694 kfunc_proto_id = kern_func->type;
6696 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
6697 kern_btf, kfunc_proto_id);
6699 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
6700 ext->name, local_func_proto_id, kfunc_proto_id);
6705 ext->ksym.kernel_btf_obj_fd = kern_btf_fd;
6706 ext->ksym.kernel_btf_id = kfunc_id;
6707 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
6708 ext->name, kfunc_id);
6713 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
6715 const struct btf_type *t;
6716 struct extern_desc *ext;
6719 for (i = 0; i < obj->nr_extern; i++) {
6720 ext = &obj->externs[i];
6721 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
6724 if (obj->gen_loader) {
6726 ext->ksym.kernel_btf_obj_fd = 0;
6727 ext->ksym.kernel_btf_id = 0;
6730 t = btf__type_by_id(obj->btf, ext->btf_id);
6732 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
6734 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
6741 static int bpf_object__resolve_externs(struct bpf_object *obj,
6742 const char *extra_kconfig)
6744 bool need_config = false, need_kallsyms = false;
6745 bool need_vmlinux_btf = false;
6746 struct extern_desc *ext;
6747 void *kcfg_data = NULL;
6750 if (obj->nr_extern == 0)
6753 if (obj->kconfig_map_idx >= 0)
6754 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
6756 for (i = 0; i < obj->nr_extern; i++) {
6757 ext = &obj->externs[i];
6759 if (ext->type == EXT_KCFG &&
6760 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
6761 void *ext_val = kcfg_data + ext->kcfg.data_off;
6762 __u32 kver = get_kernel_version();
6765 pr_warn("failed to get kernel version\n");
6768 err = set_kcfg_value_num(ext, ext_val, kver);
6771 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
6772 } else if (ext->type == EXT_KCFG &&
6773 strncmp(ext->name, "CONFIG_", 7) == 0) {
6775 } else if (ext->type == EXT_KSYM) {
6776 if (ext->ksym.type_id)
6777 need_vmlinux_btf = true;
6779 need_kallsyms = true;
6781 pr_warn("unrecognized extern '%s'\n", ext->name);
6785 if (need_config && extra_kconfig) {
6786 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
6789 need_config = false;
6790 for (i = 0; i < obj->nr_extern; i++) {
6791 ext = &obj->externs[i];
6792 if (ext->type == EXT_KCFG && !ext->is_set) {
6799 err = bpf_object__read_kconfig_file(obj, kcfg_data);
6803 if (need_kallsyms) {
6804 err = bpf_object__read_kallsyms_file(obj);
6808 if (need_vmlinux_btf) {
6809 err = bpf_object__resolve_ksyms_btf_id(obj);
6813 for (i = 0; i < obj->nr_extern; i++) {
6814 ext = &obj->externs[i];
6816 if (!ext->is_set && !ext->is_weak) {
6817 pr_warn("extern %s (strong) not resolved\n", ext->name);
6819 } else if (!ext->is_set) {
6820 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
6828 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
6830 struct bpf_object *obj;
6834 return libbpf_err(-EINVAL);
6837 return libbpf_err(-EINVAL);
6840 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
6841 return libbpf_err(-EINVAL);
6844 if (obj->gen_loader)
6845 bpf_gen__init(obj->gen_loader, attr->log_level);
6847 err = bpf_object__probe_loading(obj);
6848 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
6849 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
6850 err = err ? : bpf_object__sanitize_and_load_btf(obj);
6851 err = err ? : bpf_object__sanitize_maps(obj);
6852 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
6853 err = err ? : bpf_object__create_maps(obj);
6854 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : attr->target_btf_path);
6855 err = err ? : bpf_object__load_progs(obj, attr->log_level);
6857 if (obj->gen_loader) {
6859 btf__set_fd(obj->btf, -1);
6860 for (i = 0; i < obj->nr_maps; i++)
6861 obj->maps[i].fd = -1;
6863 err = bpf_gen__finish(obj->gen_loader);
6866 /* clean up module BTFs */
6867 for (i = 0; i < obj->btf_module_cnt; i++) {
6868 close(obj->btf_modules[i].fd);
6869 btf__free(obj->btf_modules[i].btf);
6870 free(obj->btf_modules[i].name);
6872 free(obj->btf_modules);
6874 /* clean up vmlinux BTF */
6875 btf__free(obj->btf_vmlinux);
6876 obj->btf_vmlinux = NULL;
6878 obj->loaded = true; /* doesn't matter if successfully or not */
6885 /* unpin any maps that were auto-pinned during load */
6886 for (i = 0; i < obj->nr_maps; i++)
6887 if (obj->maps[i].pinned && !obj->maps[i].reused)
6888 bpf_map__unpin(&obj->maps[i], NULL);
6890 bpf_object__unload(obj);
6891 pr_warn("failed to load object '%s'\n", obj->path);
6892 return libbpf_err(err);
6895 int bpf_object__load(struct bpf_object *obj)
6897 struct bpf_object_load_attr attr = {
6901 return bpf_object__load_xattr(&attr);
6904 static int make_parent_dir(const char *path)
6906 char *cp, errmsg[STRERR_BUFSIZE];
6910 dname = strdup(path);
6914 dir = dirname(dname);
6915 if (mkdir(dir, 0700) && errno != EEXIST)
6920 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
6921 pr_warn("failed to mkdir %s: %s\n", path, cp);
6926 static int check_path(const char *path)
6928 char *cp, errmsg[STRERR_BUFSIZE];
6929 struct statfs st_fs;
6936 dname = strdup(path);
6940 dir = dirname(dname);
6941 if (statfs(dir, &st_fs)) {
6942 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6943 pr_warn("failed to statfs %s: %s\n", dir, cp);
6948 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
6949 pr_warn("specified path %s is not on BPF FS\n", path);
6956 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
6959 char *cp, errmsg[STRERR_BUFSIZE];
6962 err = make_parent_dir(path);
6964 return libbpf_err(err);
6966 err = check_path(path);
6968 return libbpf_err(err);
6971 pr_warn("invalid program pointer\n");
6972 return libbpf_err(-EINVAL);
6975 if (instance < 0 || instance >= prog->instances.nr) {
6976 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
6977 instance, prog->name, prog->instances.nr);
6978 return libbpf_err(-EINVAL);
6981 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
6983 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
6984 pr_warn("failed to pin program: %s\n", cp);
6985 return libbpf_err(err);
6987 pr_debug("pinned program '%s'\n", path);
6992 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
6997 err = check_path(path);
6999 return libbpf_err(err);
7002 pr_warn("invalid program pointer\n");
7003 return libbpf_err(-EINVAL);
7006 if (instance < 0 || instance >= prog->instances.nr) {
7007 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7008 instance, prog->name, prog->instances.nr);
7009 return libbpf_err(-EINVAL);
7014 return libbpf_err(-errno);
7016 pr_debug("unpinned program '%s'\n", path);
7021 int bpf_program__pin(struct bpf_program *prog, const char *path)
7025 err = make_parent_dir(path);
7027 return libbpf_err(err);
7029 err = check_path(path);
7031 return libbpf_err(err);
7034 pr_warn("invalid program pointer\n");
7035 return libbpf_err(-EINVAL);
7038 if (prog->instances.nr <= 0) {
7039 pr_warn("no instances of prog %s to pin\n", prog->name);
7040 return libbpf_err(-EINVAL);
7043 if (prog->instances.nr == 1) {
7044 /* don't create subdirs when pinning single instance */
7045 return bpf_program__pin_instance(prog, path, 0);
7048 for (i = 0; i < prog->instances.nr; i++) {
7052 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7056 } else if (len >= PATH_MAX) {
7057 err = -ENAMETOOLONG;
7061 err = bpf_program__pin_instance(prog, buf, i);
7069 for (i = i - 1; i >= 0; i--) {
7073 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7076 else if (len >= PATH_MAX)
7079 bpf_program__unpin_instance(prog, buf, i);
7084 return libbpf_err(err);
7087 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7091 err = check_path(path);
7093 return libbpf_err(err);
7096 pr_warn("invalid program pointer\n");
7097 return libbpf_err(-EINVAL);
7100 if (prog->instances.nr <= 0) {
7101 pr_warn("no instances of prog %s to pin\n", prog->name);
7102 return libbpf_err(-EINVAL);
7105 if (prog->instances.nr == 1) {
7106 /* don't create subdirs when pinning single instance */
7107 return bpf_program__unpin_instance(prog, path, 0);
7110 for (i = 0; i < prog->instances.nr; i++) {
7114 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7116 return libbpf_err(-EINVAL);
7117 else if (len >= PATH_MAX)
7118 return libbpf_err(-ENAMETOOLONG);
7120 err = bpf_program__unpin_instance(prog, buf, i);
7127 return libbpf_err(-errno);
7132 int bpf_map__pin(struct bpf_map *map, const char *path)
7134 char *cp, errmsg[STRERR_BUFSIZE];
7138 pr_warn("invalid map pointer\n");
7139 return libbpf_err(-EINVAL);
7142 if (map->pin_path) {
7143 if (path && strcmp(path, map->pin_path)) {
7144 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7145 bpf_map__name(map), map->pin_path, path);
7146 return libbpf_err(-EINVAL);
7147 } else if (map->pinned) {
7148 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7149 bpf_map__name(map), map->pin_path);
7154 pr_warn("missing a path to pin map '%s' at\n",
7155 bpf_map__name(map));
7156 return libbpf_err(-EINVAL);
7157 } else if (map->pinned) {
7158 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7159 return libbpf_err(-EEXIST);
7162 map->pin_path = strdup(path);
7163 if (!map->pin_path) {
7169 err = make_parent_dir(map->pin_path);
7171 return libbpf_err(err);
7173 err = check_path(map->pin_path);
7175 return libbpf_err(err);
7177 if (bpf_obj_pin(map->fd, map->pin_path)) {
7183 pr_debug("pinned map '%s'\n", map->pin_path);
7188 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7189 pr_warn("failed to pin map: %s\n", cp);
7190 return libbpf_err(err);
7193 int bpf_map__unpin(struct bpf_map *map, const char *path)
7198 pr_warn("invalid map pointer\n");
7199 return libbpf_err(-EINVAL);
7202 if (map->pin_path) {
7203 if (path && strcmp(path, map->pin_path)) {
7204 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7205 bpf_map__name(map), map->pin_path, path);
7206 return libbpf_err(-EINVAL);
7208 path = map->pin_path;
7210 pr_warn("no path to unpin map '%s' from\n",
7211 bpf_map__name(map));
7212 return libbpf_err(-EINVAL);
7215 err = check_path(path);
7217 return libbpf_err(err);
7221 return libbpf_err(-errno);
7223 map->pinned = false;
7224 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7229 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7236 return libbpf_err(-errno);
7239 free(map->pin_path);
7240 map->pin_path = new;
7244 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7246 return map->pin_path;
7249 const char *bpf_map__pin_path(const struct bpf_map *map)
7251 return map->pin_path;
7254 bool bpf_map__is_pinned(const struct bpf_map *map)
7259 static void sanitize_pin_path(char *s)
7261 /* bpffs disallows periods in path names */
7269 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7271 struct bpf_map *map;
7275 return libbpf_err(-ENOENT);
7278 pr_warn("object not yet loaded; load it first\n");
7279 return libbpf_err(-ENOENT);
7282 bpf_object__for_each_map(map, obj) {
7283 char *pin_path = NULL;
7289 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7290 bpf_map__name(map));
7293 goto err_unpin_maps;
7294 } else if (len >= PATH_MAX) {
7295 err = -ENAMETOOLONG;
7296 goto err_unpin_maps;
7298 sanitize_pin_path(buf);
7300 } else if (!map->pin_path) {
7304 err = bpf_map__pin(map, pin_path);
7306 goto err_unpin_maps;
7312 while ((map = bpf_map__prev(map, obj))) {
7316 bpf_map__unpin(map, NULL);
7319 return libbpf_err(err);
7322 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7324 struct bpf_map *map;
7328 return libbpf_err(-ENOENT);
7330 bpf_object__for_each_map(map, obj) {
7331 char *pin_path = NULL;
7337 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7338 bpf_map__name(map));
7340 return libbpf_err(-EINVAL);
7341 else if (len >= PATH_MAX)
7342 return libbpf_err(-ENAMETOOLONG);
7343 sanitize_pin_path(buf);
7345 } else if (!map->pin_path) {
7349 err = bpf_map__unpin(map, pin_path);
7351 return libbpf_err(err);
7357 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
7359 struct bpf_program *prog;
7363 return libbpf_err(-ENOENT);
7366 pr_warn("object not yet loaded; load it first\n");
7367 return libbpf_err(-ENOENT);
7370 bpf_object__for_each_program(prog, obj) {
7374 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7378 goto err_unpin_programs;
7379 } else if (len >= PATH_MAX) {
7380 err = -ENAMETOOLONG;
7381 goto err_unpin_programs;
7384 err = bpf_program__pin(prog, buf);
7386 goto err_unpin_programs;
7392 while ((prog = bpf_program__prev(prog, obj))) {
7396 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7400 else if (len >= PATH_MAX)
7403 bpf_program__unpin(prog, buf);
7406 return libbpf_err(err);
7409 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
7411 struct bpf_program *prog;
7415 return libbpf_err(-ENOENT);
7417 bpf_object__for_each_program(prog, obj) {
7421 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7424 return libbpf_err(-EINVAL);
7425 else if (len >= PATH_MAX)
7426 return libbpf_err(-ENAMETOOLONG);
7428 err = bpf_program__unpin(prog, buf);
7430 return libbpf_err(err);
7436 int bpf_object__pin(struct bpf_object *obj, const char *path)
7440 err = bpf_object__pin_maps(obj, path);
7442 return libbpf_err(err);
7444 err = bpf_object__pin_programs(obj, path);
7446 bpf_object__unpin_maps(obj, path);
7447 return libbpf_err(err);
7453 static void bpf_map__destroy(struct bpf_map *map)
7455 if (map->clear_priv)
7456 map->clear_priv(map, map->priv);
7458 map->clear_priv = NULL;
7460 if (map->inner_map) {
7461 bpf_map__destroy(map->inner_map);
7462 zfree(&map->inner_map);
7465 zfree(&map->init_slots);
7466 map->init_slots_sz = 0;
7469 munmap(map->mmaped, bpf_map_mmap_sz(map));
7474 zfree(&map->st_ops->data);
7475 zfree(&map->st_ops->progs);
7476 zfree(&map->st_ops->kern_func_off);
7477 zfree(&map->st_ops);
7481 zfree(&map->pin_path);
7487 void bpf_object__close(struct bpf_object *obj)
7491 if (IS_ERR_OR_NULL(obj))
7494 if (obj->clear_priv)
7495 obj->clear_priv(obj, obj->priv);
7497 bpf_gen__free(obj->gen_loader);
7498 bpf_object__elf_finish(obj);
7499 bpf_object__unload(obj);
7500 btf__free(obj->btf);
7501 btf_ext__free(obj->btf_ext);
7503 for (i = 0; i < obj->nr_maps; i++)
7504 bpf_map__destroy(&obj->maps[i]);
7506 zfree(&obj->btf_custom_path);
7507 zfree(&obj->kconfig);
7508 zfree(&obj->externs);
7514 if (obj->programs && obj->nr_programs) {
7515 for (i = 0; i < obj->nr_programs; i++)
7516 bpf_program__exit(&obj->programs[i]);
7518 zfree(&obj->programs);
7520 list_del(&obj->list);
7525 bpf_object__next(struct bpf_object *prev)
7527 struct bpf_object *next;
7530 next = list_first_entry(&bpf_objects_list,
7534 next = list_next_entry(prev, list);
7536 /* Empty list is noticed here so don't need checking on entry. */
7537 if (&next->list == &bpf_objects_list)
7543 const char *bpf_object__name(const struct bpf_object *obj)
7545 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
7548 unsigned int bpf_object__kversion(const struct bpf_object *obj)
7550 return obj ? obj->kern_version : 0;
7553 struct btf *bpf_object__btf(const struct bpf_object *obj)
7555 return obj ? obj->btf : NULL;
7558 int bpf_object__btf_fd(const struct bpf_object *obj)
7560 return obj->btf ? btf__fd(obj->btf) : -1;
7563 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
7566 return libbpf_err(-EINVAL);
7568 obj->kern_version = kern_version;
7573 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
7574 bpf_object_clear_priv_t clear_priv)
7576 if (obj->priv && obj->clear_priv)
7577 obj->clear_priv(obj, obj->priv);
7580 obj->clear_priv = clear_priv;
7584 void *bpf_object__priv(const struct bpf_object *obj)
7586 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
7589 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
7591 struct bpf_gen *gen;
7595 if (!OPTS_VALID(opts, gen_loader_opts))
7597 gen = calloc(sizeof(*gen), 1);
7601 obj->gen_loader = gen;
7605 static struct bpf_program *
7606 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
7609 size_t nr_programs = obj->nr_programs;
7616 /* Iter from the beginning */
7617 return forward ? &obj->programs[0] :
7618 &obj->programs[nr_programs - 1];
7620 if (p->obj != obj) {
7621 pr_warn("error: program handler doesn't match object\n");
7622 return errno = EINVAL, NULL;
7625 idx = (p - obj->programs) + (forward ? 1 : -1);
7626 if (idx >= obj->nr_programs || idx < 0)
7628 return &obj->programs[idx];
7631 struct bpf_program *
7632 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
7634 struct bpf_program *prog = prev;
7637 prog = __bpf_program__iter(prog, obj, true);
7638 } while (prog && prog_is_subprog(obj, prog));
7643 struct bpf_program *
7644 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
7646 struct bpf_program *prog = next;
7649 prog = __bpf_program__iter(prog, obj, false);
7650 } while (prog && prog_is_subprog(obj, prog));
7655 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
7656 bpf_program_clear_priv_t clear_priv)
7658 if (prog->priv && prog->clear_priv)
7659 prog->clear_priv(prog, prog->priv);
7662 prog->clear_priv = clear_priv;
7666 void *bpf_program__priv(const struct bpf_program *prog)
7668 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
7671 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
7673 prog->prog_ifindex = ifindex;
7676 const char *bpf_program__name(const struct bpf_program *prog)
7681 const char *bpf_program__section_name(const struct bpf_program *prog)
7683 return prog->sec_name;
7686 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
7690 title = prog->sec_name;
7692 title = strdup(title);
7694 pr_warn("failed to strdup program title\n");
7695 return libbpf_err_ptr(-ENOMEM);
7702 bool bpf_program__autoload(const struct bpf_program *prog)
7707 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
7709 if (prog->obj->loaded)
7710 return libbpf_err(-EINVAL);
7712 prog->load = autoload;
7716 int bpf_program__fd(const struct bpf_program *prog)
7718 return bpf_program__nth_fd(prog, 0);
7721 size_t bpf_program__size(const struct bpf_program *prog)
7723 return prog->insns_cnt * BPF_INSN_SZ;
7726 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
7727 bpf_program_prep_t prep)
7731 if (nr_instances <= 0 || !prep)
7732 return libbpf_err(-EINVAL);
7734 if (prog->instances.nr > 0 || prog->instances.fds) {
7735 pr_warn("Can't set pre-processor after loading\n");
7736 return libbpf_err(-EINVAL);
7739 instances_fds = malloc(sizeof(int) * nr_instances);
7740 if (!instances_fds) {
7741 pr_warn("alloc memory failed for fds\n");
7742 return libbpf_err(-ENOMEM);
7745 /* fill all fd with -1 */
7746 memset(instances_fds, -1, sizeof(int) * nr_instances);
7748 prog->instances.nr = nr_instances;
7749 prog->instances.fds = instances_fds;
7750 prog->preprocessor = prep;
7754 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
7759 return libbpf_err(-EINVAL);
7761 if (n >= prog->instances.nr || n < 0) {
7762 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
7763 n, prog->name, prog->instances.nr);
7764 return libbpf_err(-EINVAL);
7767 fd = prog->instances.fds[n];
7769 pr_warn("%dth instance of program '%s' is invalid\n",
7771 return libbpf_err(-ENOENT);
7777 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
7782 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
7787 static bool bpf_program__is_type(const struct bpf_program *prog,
7788 enum bpf_prog_type type)
7790 return prog ? (prog->type == type) : false;
7793 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
7794 int bpf_program__set_##NAME(struct bpf_program *prog) \
7797 return libbpf_err(-EINVAL); \
7798 bpf_program__set_type(prog, TYPE); \
7802 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
7804 return bpf_program__is_type(prog, TYPE); \
7807 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
7808 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
7809 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7810 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
7811 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
7812 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
7813 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7814 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
7815 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
7816 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
7817 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
7818 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
7819 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
7821 enum bpf_attach_type
7822 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
7824 return prog->expected_attach_type;
7827 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
7828 enum bpf_attach_type type)
7830 prog->expected_attach_type = type;
7833 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
7834 attachable, attach_btf) \
7837 .len = sizeof(string) - 1, \
7838 .prog_type = ptype, \
7839 .expected_attach_type = eatype, \
7840 .is_exp_attach_type_optional = eatype_optional, \
7841 .is_attachable = attachable, \
7842 .is_attach_btf = attach_btf, \
7845 /* Programs that can NOT be attached. */
7846 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
7848 /* Programs that can be attached. */
7849 #define BPF_APROG_SEC(string, ptype, atype) \
7850 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
7852 /* Programs that must specify expected attach type at load time. */
7853 #define BPF_EAPROG_SEC(string, ptype, eatype) \
7854 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
7856 /* Programs that use BTF to identify attach point */
7857 #define BPF_PROG_BTF(string, ptype, eatype) \
7858 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
7860 /* Programs that can be attached but attach type can't be identified by section
7861 * name. Kept for backward compatibility.
7863 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
7865 #define SEC_DEF(sec_pfx, ptype, ...) { \
7867 .len = sizeof(sec_pfx) - 1, \
7868 .prog_type = BPF_PROG_TYPE_##ptype, \
7872 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7873 struct bpf_program *prog);
7874 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7875 struct bpf_program *prog);
7876 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7877 struct bpf_program *prog);
7878 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7879 struct bpf_program *prog);
7880 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
7881 struct bpf_program *prog);
7882 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
7883 struct bpf_program *prog);
7885 static const struct bpf_sec_def section_defs[] = {
7886 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
7887 BPF_EAPROG_SEC("sk_reuseport/migrate", BPF_PROG_TYPE_SK_REUSEPORT,
7888 BPF_SK_REUSEPORT_SELECT_OR_MIGRATE),
7889 BPF_EAPROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT,
7890 BPF_SK_REUSEPORT_SELECT),
7891 SEC_DEF("kprobe/", KPROBE,
7892 .attach_fn = attach_kprobe),
7893 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
7894 SEC_DEF("kretprobe/", KPROBE,
7895 .attach_fn = attach_kprobe),
7896 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
7897 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
7898 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
7899 SEC_DEF("tracepoint/", TRACEPOINT,
7900 .attach_fn = attach_tp),
7901 SEC_DEF("tp/", TRACEPOINT,
7902 .attach_fn = attach_tp),
7903 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
7904 .attach_fn = attach_raw_tp),
7905 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
7906 .attach_fn = attach_raw_tp),
7907 SEC_DEF("tp_btf/", TRACING,
7908 .expected_attach_type = BPF_TRACE_RAW_TP,
7909 .is_attach_btf = true,
7910 .attach_fn = attach_trace),
7911 SEC_DEF("fentry/", TRACING,
7912 .expected_attach_type = BPF_TRACE_FENTRY,
7913 .is_attach_btf = true,
7914 .attach_fn = attach_trace),
7915 SEC_DEF("fmod_ret/", TRACING,
7916 .expected_attach_type = BPF_MODIFY_RETURN,
7917 .is_attach_btf = true,
7918 .attach_fn = attach_trace),
7919 SEC_DEF("fexit/", TRACING,
7920 .expected_attach_type = BPF_TRACE_FEXIT,
7921 .is_attach_btf = true,
7922 .attach_fn = attach_trace),
7923 SEC_DEF("fentry.s/", TRACING,
7924 .expected_attach_type = BPF_TRACE_FENTRY,
7925 .is_attach_btf = true,
7926 .is_sleepable = true,
7927 .attach_fn = attach_trace),
7928 SEC_DEF("fmod_ret.s/", TRACING,
7929 .expected_attach_type = BPF_MODIFY_RETURN,
7930 .is_attach_btf = true,
7931 .is_sleepable = true,
7932 .attach_fn = attach_trace),
7933 SEC_DEF("fexit.s/", TRACING,
7934 .expected_attach_type = BPF_TRACE_FEXIT,
7935 .is_attach_btf = true,
7936 .is_sleepable = true,
7937 .attach_fn = attach_trace),
7938 SEC_DEF("freplace/", EXT,
7939 .is_attach_btf = true,
7940 .attach_fn = attach_trace),
7941 SEC_DEF("lsm/", LSM,
7942 .is_attach_btf = true,
7943 .expected_attach_type = BPF_LSM_MAC,
7944 .attach_fn = attach_lsm),
7945 SEC_DEF("lsm.s/", LSM,
7946 .is_attach_btf = true,
7947 .is_sleepable = true,
7948 .expected_attach_type = BPF_LSM_MAC,
7949 .attach_fn = attach_lsm),
7950 SEC_DEF("iter/", TRACING,
7951 .expected_attach_type = BPF_TRACE_ITER,
7952 .is_attach_btf = true,
7953 .attach_fn = attach_iter),
7954 SEC_DEF("syscall", SYSCALL,
7955 .is_sleepable = true),
7956 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
7958 BPF_EAPROG_SEC("xdp_cpumap/", BPF_PROG_TYPE_XDP,
7960 BPF_APROG_SEC("xdp", BPF_PROG_TYPE_XDP,
7962 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
7963 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
7964 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
7965 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
7966 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
7967 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
7968 BPF_CGROUP_INET_INGRESS),
7969 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
7970 BPF_CGROUP_INET_EGRESS),
7971 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
7972 BPF_EAPROG_SEC("cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK,
7973 BPF_CGROUP_INET_SOCK_CREATE),
7974 BPF_EAPROG_SEC("cgroup/sock_release", BPF_PROG_TYPE_CGROUP_SOCK,
7975 BPF_CGROUP_INET_SOCK_RELEASE),
7976 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
7977 BPF_CGROUP_INET_SOCK_CREATE),
7978 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
7979 BPF_CGROUP_INET4_POST_BIND),
7980 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
7981 BPF_CGROUP_INET6_POST_BIND),
7982 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
7984 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
7985 BPF_CGROUP_SOCK_OPS),
7986 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
7987 BPF_SK_SKB_STREAM_PARSER),
7988 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
7989 BPF_SK_SKB_STREAM_VERDICT),
7990 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
7991 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
7992 BPF_SK_MSG_VERDICT),
7993 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
7995 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
7996 BPF_FLOW_DISSECTOR),
7997 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
7998 BPF_CGROUP_INET4_BIND),
7999 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8000 BPF_CGROUP_INET6_BIND),
8001 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8002 BPF_CGROUP_INET4_CONNECT),
8003 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8004 BPF_CGROUP_INET6_CONNECT),
8005 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8006 BPF_CGROUP_UDP4_SENDMSG),
8007 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8008 BPF_CGROUP_UDP6_SENDMSG),
8009 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8010 BPF_CGROUP_UDP4_RECVMSG),
8011 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8012 BPF_CGROUP_UDP6_RECVMSG),
8013 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8014 BPF_CGROUP_INET4_GETPEERNAME),
8015 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8016 BPF_CGROUP_INET6_GETPEERNAME),
8017 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8018 BPF_CGROUP_INET4_GETSOCKNAME),
8019 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8020 BPF_CGROUP_INET6_GETSOCKNAME),
8021 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
8023 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8024 BPF_CGROUP_GETSOCKOPT),
8025 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8026 BPF_CGROUP_SETSOCKOPT),
8027 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
8028 BPF_EAPROG_SEC("sk_lookup/", BPF_PROG_TYPE_SK_LOOKUP,
8032 #undef BPF_PROG_SEC_IMPL
8034 #undef BPF_APROG_SEC
8035 #undef BPF_EAPROG_SEC
8036 #undef BPF_APROG_COMPAT
8039 #define MAX_TYPE_NAME_SIZE 32
8041 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8043 int i, n = ARRAY_SIZE(section_defs);
8045 for (i = 0; i < n; i++) {
8046 if (strncmp(sec_name,
8047 section_defs[i].sec, section_defs[i].len))
8049 return §ion_defs[i];
8054 static char *libbpf_get_type_names(bool attach_type)
8056 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8064 /* Forge string buf with all available names */
8065 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8066 if (attach_type && !section_defs[i].is_attachable)
8069 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8074 strcat(buf, section_defs[i].sec);
8080 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8081 enum bpf_attach_type *expected_attach_type)
8083 const struct bpf_sec_def *sec_def;
8087 return libbpf_err(-EINVAL);
8089 sec_def = find_sec_def(name);
8091 *prog_type = sec_def->prog_type;
8092 *expected_attach_type = sec_def->expected_attach_type;
8096 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8097 type_names = libbpf_get_type_names(false);
8098 if (type_names != NULL) {
8099 pr_debug("supported section(type) names are:%s\n", type_names);
8103 return libbpf_err(-ESRCH);
8106 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8109 struct bpf_map *map;
8112 for (i = 0; i < obj->nr_maps; i++) {
8113 map = &obj->maps[i];
8114 if (!bpf_map__is_struct_ops(map))
8116 if (map->sec_offset <= offset &&
8117 offset - map->sec_offset < map->def.value_size)
8124 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8125 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8126 GElf_Shdr *shdr, Elf_Data *data)
8128 const struct btf_member *member;
8129 struct bpf_struct_ops *st_ops;
8130 struct bpf_program *prog;
8131 unsigned int shdr_idx;
8132 const struct btf *btf;
8133 struct bpf_map *map;
8135 unsigned int moff, insn_idx;
8142 symbols = obj->efile.symbols;
8144 nrels = shdr->sh_size / shdr->sh_entsize;
8145 for (i = 0; i < nrels; i++) {
8146 if (!gelf_getrel(data, i, &rel)) {
8147 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8148 return -LIBBPF_ERRNO__FORMAT;
8151 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
8152 pr_warn("struct_ops reloc: symbol %zx not found\n",
8153 (size_t)GELF_R_SYM(rel.r_info));
8154 return -LIBBPF_ERRNO__FORMAT;
8157 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
8158 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
8160 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
8161 (size_t)rel.r_offset);
8165 moff = rel.r_offset - map->sec_offset;
8166 shdr_idx = sym.st_shndx;
8167 st_ops = map->st_ops;
8168 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",
8170 (long long)(rel.r_info >> 32),
8171 (long long)sym.st_value,
8172 shdr_idx, (size_t)rel.r_offset,
8173 map->sec_offset, sym.st_name, name);
8175 if (shdr_idx >= SHN_LORESERVE) {
8176 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
8177 map->name, (size_t)rel.r_offset, shdr_idx);
8178 return -LIBBPF_ERRNO__RELOC;
8180 if (sym.st_value % BPF_INSN_SZ) {
8181 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8182 map->name, (unsigned long long)sym.st_value);
8183 return -LIBBPF_ERRNO__FORMAT;
8185 insn_idx = sym.st_value / BPF_INSN_SZ;
8187 member = find_member_by_offset(st_ops->type, moff * 8);
8189 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8193 member_idx = member - btf_members(st_ops->type);
8194 name = btf__name_by_offset(btf, member->name_off);
8196 if (!resolve_func_ptr(btf, member->type, NULL)) {
8197 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8202 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8204 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8205 map->name, shdr_idx, name);
8209 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
8210 const struct bpf_sec_def *sec_def;
8212 sec_def = find_sec_def(prog->sec_name);
8214 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
8216 prog->type = sec_def->prog_type;
8220 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
8221 prog->attach_btf_id = st_ops->type_id;
8222 prog->expected_attach_type = member_idx;
8223 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
8224 prog->attach_btf_id != st_ops->type_id ||
8225 prog->expected_attach_type != member_idx) {
8228 st_ops->progs[member_idx] = prog;
8234 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",
8235 map->name, prog->name, prog->sec_name, prog->type,
8236 prog->attach_btf_id, prog->expected_attach_type, name);
8240 #define BTF_TRACE_PREFIX "btf_trace_"
8241 #define BTF_LSM_PREFIX "bpf_lsm_"
8242 #define BTF_ITER_PREFIX "bpf_iter_"
8243 #define BTF_MAX_NAME_SIZE 128
8245 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8246 const char **prefix, int *kind)
8248 switch (attach_type) {
8249 case BPF_TRACE_RAW_TP:
8250 *prefix = BTF_TRACE_PREFIX;
8251 *kind = BTF_KIND_TYPEDEF;
8254 *prefix = BTF_LSM_PREFIX;
8255 *kind = BTF_KIND_FUNC;
8257 case BPF_TRACE_ITER:
8258 *prefix = BTF_ITER_PREFIX;
8259 *kind = BTF_KIND_FUNC;
8263 *kind = BTF_KIND_FUNC;
8267 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8268 const char *name, __u32 kind)
8270 char btf_type_name[BTF_MAX_NAME_SIZE];
8273 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8274 "%s%s", prefix, name);
8275 /* snprintf returns the number of characters written excluding the
8276 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8277 * indicates truncation.
8279 if (ret < 0 || ret >= sizeof(btf_type_name))
8280 return -ENAMETOOLONG;
8281 return btf__find_by_name_kind(btf, btf_type_name, kind);
8284 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8285 enum bpf_attach_type attach_type)
8290 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8291 return find_btf_by_prefix_kind(btf, prefix, name, kind);
8294 int libbpf_find_vmlinux_btf_id(const char *name,
8295 enum bpf_attach_type attach_type)
8300 btf = libbpf_find_kernel_btf();
8301 err = libbpf_get_error(btf);
8303 pr_warn("vmlinux BTF is not found\n");
8304 return libbpf_err(err);
8307 err = find_attach_btf_id(btf, name, attach_type);
8309 pr_warn("%s is not found in vmlinux BTF\n", name);
8312 return libbpf_err(err);
8315 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8317 struct bpf_prog_info_linear *info_linear;
8318 struct bpf_prog_info *info;
8322 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
8323 err = libbpf_get_error(info_linear);
8325 pr_warn("failed get_prog_info_linear for FD %d\n",
8331 info = &info_linear->info;
8332 if (!info->btf_id) {
8333 pr_warn("The target program doesn't have BTF\n");
8336 btf = btf__load_from_kernel_by_id(info->btf_id);
8337 if (libbpf_get_error(btf)) {
8338 pr_warn("Failed to get BTF of the program\n");
8341 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8344 pr_warn("%s is not found in prog's BTF\n", name);
8352 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
8353 enum bpf_attach_type attach_type,
8354 int *btf_obj_fd, int *btf_type_id)
8358 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
8360 *btf_obj_fd = 0; /* vmlinux BTF */
8367 ret = load_module_btfs(obj);
8371 for (i = 0; i < obj->btf_module_cnt; i++) {
8372 const struct module_btf *mod = &obj->btf_modules[i];
8374 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
8376 *btf_obj_fd = mod->fd;
8389 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id)
8391 enum bpf_attach_type attach_type = prog->expected_attach_type;
8392 __u32 attach_prog_fd = prog->attach_prog_fd;
8393 const char *name = prog->sec_name, *attach_name;
8394 const struct bpf_sec_def *sec = NULL;
8400 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8401 if (!section_defs[i].is_attach_btf)
8403 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8406 sec = §ion_defs[i];
8411 pr_warn("failed to identify BTF ID based on ELF section name '%s'\n", name);
8414 attach_name = name + sec->len;
8416 /* BPF program's BTF ID */
8417 if (attach_prog_fd) {
8418 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
8420 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
8421 attach_prog_fd, attach_name, err);
8429 /* kernel/module BTF ID */
8430 if (prog->obj->gen_loader) {
8431 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
8435 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
8438 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
8444 int libbpf_attach_type_by_name(const char *name,
8445 enum bpf_attach_type *attach_type)
8451 return libbpf_err(-EINVAL);
8453 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8454 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8456 if (!section_defs[i].is_attachable)
8457 return libbpf_err(-EINVAL);
8458 *attach_type = section_defs[i].expected_attach_type;
8461 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
8462 type_names = libbpf_get_type_names(true);
8463 if (type_names != NULL) {
8464 pr_debug("attachable section(type) names are:%s\n", type_names);
8468 return libbpf_err(-EINVAL);
8471 int bpf_map__fd(const struct bpf_map *map)
8473 return map ? map->fd : libbpf_err(-EINVAL);
8476 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
8478 return map ? &map->def : libbpf_err_ptr(-EINVAL);
8481 const char *bpf_map__name(const struct bpf_map *map)
8483 return map ? map->name : NULL;
8486 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
8488 return map->def.type;
8491 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
8494 return libbpf_err(-EBUSY);
8495 map->def.type = type;
8499 __u32 bpf_map__map_flags(const struct bpf_map *map)
8501 return map->def.map_flags;
8504 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
8507 return libbpf_err(-EBUSY);
8508 map->def.map_flags = flags;
8512 __u32 bpf_map__numa_node(const struct bpf_map *map)
8514 return map->numa_node;
8517 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
8520 return libbpf_err(-EBUSY);
8521 map->numa_node = numa_node;
8525 __u32 bpf_map__key_size(const struct bpf_map *map)
8527 return map->def.key_size;
8530 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
8533 return libbpf_err(-EBUSY);
8534 map->def.key_size = size;
8538 __u32 bpf_map__value_size(const struct bpf_map *map)
8540 return map->def.value_size;
8543 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
8546 return libbpf_err(-EBUSY);
8547 map->def.value_size = size;
8551 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8553 return map ? map->btf_key_type_id : 0;
8556 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8558 return map ? map->btf_value_type_id : 0;
8561 int bpf_map__set_priv(struct bpf_map *map, void *priv,
8562 bpf_map_clear_priv_t clear_priv)
8565 return libbpf_err(-EINVAL);
8568 if (map->clear_priv)
8569 map->clear_priv(map, map->priv);
8573 map->clear_priv = clear_priv;
8577 void *bpf_map__priv(const struct bpf_map *map)
8579 return map ? map->priv : libbpf_err_ptr(-EINVAL);
8582 int bpf_map__set_initial_value(struct bpf_map *map,
8583 const void *data, size_t size)
8585 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
8586 size != map->def.value_size || map->fd >= 0)
8587 return libbpf_err(-EINVAL);
8589 memcpy(map->mmaped, data, size);
8593 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
8597 *psize = map->def.value_size;
8601 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
8603 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
8606 bool bpf_map__is_internal(const struct bpf_map *map)
8608 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
8611 __u32 bpf_map__ifindex(const struct bpf_map *map)
8613 return map->map_ifindex;
8616 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
8619 return libbpf_err(-EBUSY);
8620 map->map_ifindex = ifindex;
8624 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
8626 if (!bpf_map_type__is_map_in_map(map->def.type)) {
8627 pr_warn("error: unsupported map type\n");
8628 return libbpf_err(-EINVAL);
8630 if (map->inner_map_fd != -1) {
8631 pr_warn("error: inner_map_fd already specified\n");
8632 return libbpf_err(-EINVAL);
8634 zfree(&map->inner_map);
8635 map->inner_map_fd = fd;
8639 static struct bpf_map *
8640 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
8643 struct bpf_map *s, *e;
8645 if (!obj || !obj->maps)
8646 return errno = EINVAL, NULL;
8649 e = obj->maps + obj->nr_maps;
8651 if ((m < s) || (m >= e)) {
8652 pr_warn("error in %s: map handler doesn't belong to object\n",
8654 return errno = EINVAL, NULL;
8657 idx = (m - obj->maps) + i;
8658 if (idx >= obj->nr_maps || idx < 0)
8660 return &obj->maps[idx];
8664 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
8669 return __bpf_map__iter(prev, obj, 1);
8673 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
8678 return obj->maps + obj->nr_maps - 1;
8681 return __bpf_map__iter(next, obj, -1);
8685 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
8687 struct bpf_map *pos;
8689 bpf_object__for_each_map(pos, obj) {
8690 if (pos->name && !strcmp(pos->name, name))
8693 return errno = ENOENT, NULL;
8697 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
8699 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
8703 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
8705 return libbpf_err_ptr(-ENOTSUP);
8708 long libbpf_get_error(const void *ptr)
8710 if (!IS_ERR_OR_NULL(ptr))
8714 errno = -PTR_ERR(ptr);
8716 /* If ptr == NULL, then errno should be already set by the failing
8717 * API, because libbpf never returns NULL on success and it now always
8718 * sets errno on error. So no extra errno handling for ptr == NULL
8724 int bpf_prog_load(const char *file, enum bpf_prog_type type,
8725 struct bpf_object **pobj, int *prog_fd)
8727 struct bpf_prog_load_attr attr;
8729 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
8731 attr.prog_type = type;
8732 attr.expected_attach_type = 0;
8734 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
8737 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
8738 struct bpf_object **pobj, int *prog_fd)
8740 struct bpf_object_open_attr open_attr = {};
8741 struct bpf_program *prog, *first_prog = NULL;
8742 struct bpf_object *obj;
8743 struct bpf_map *map;
8747 return libbpf_err(-EINVAL);
8749 return libbpf_err(-EINVAL);
8751 open_attr.file = attr->file;
8752 open_attr.prog_type = attr->prog_type;
8754 obj = bpf_object__open_xattr(&open_attr);
8755 err = libbpf_get_error(obj);
8757 return libbpf_err(-ENOENT);
8759 bpf_object__for_each_program(prog, obj) {
8760 enum bpf_attach_type attach_type = attr->expected_attach_type;
8762 * to preserve backwards compatibility, bpf_prog_load treats
8763 * attr->prog_type, if specified, as an override to whatever
8764 * bpf_object__open guessed
8766 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
8767 bpf_program__set_type(prog, attr->prog_type);
8768 bpf_program__set_expected_attach_type(prog,
8771 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
8773 * we haven't guessed from section name and user
8774 * didn't provide a fallback type, too bad...
8776 bpf_object__close(obj);
8777 return libbpf_err(-EINVAL);
8780 prog->prog_ifindex = attr->ifindex;
8781 prog->log_level = attr->log_level;
8782 prog->prog_flags |= attr->prog_flags;
8787 bpf_object__for_each_map(map, obj) {
8788 if (!bpf_map__is_offload_neutral(map))
8789 map->map_ifindex = attr->ifindex;
8793 pr_warn("object file doesn't contain bpf program\n");
8794 bpf_object__close(obj);
8795 return libbpf_err(-ENOENT);
8798 err = bpf_object__load(obj);
8800 bpf_object__close(obj);
8801 return libbpf_err(err);
8805 *prog_fd = bpf_program__fd(first_prog);
8810 int (*detach)(struct bpf_link *link);
8811 int (*destroy)(struct bpf_link *link);
8812 char *pin_path; /* NULL, if not pinned */
8813 int fd; /* hook FD, -1 if not applicable */
8817 /* Replace link's underlying BPF program with the new one */
8818 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
8822 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
8823 return libbpf_err_errno(ret);
8826 /* Release "ownership" of underlying BPF resource (typically, BPF program
8827 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
8828 * link, when destructed through bpf_link__destroy() call won't attempt to
8829 * detach/unregisted that BPF resource. This is useful in situations where,
8830 * say, attached BPF program has to outlive userspace program that attached it
8831 * in the system. Depending on type of BPF program, though, there might be
8832 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
8833 * exit of userspace program doesn't trigger automatic detachment and clean up
8834 * inside the kernel.
8836 void bpf_link__disconnect(struct bpf_link *link)
8838 link->disconnected = true;
8841 int bpf_link__destroy(struct bpf_link *link)
8845 if (IS_ERR_OR_NULL(link))
8848 if (!link->disconnected && link->detach)
8849 err = link->detach(link);
8851 link->destroy(link);
8853 free(link->pin_path);
8856 return libbpf_err(err);
8859 int bpf_link__fd(const struct bpf_link *link)
8864 const char *bpf_link__pin_path(const struct bpf_link *link)
8866 return link->pin_path;
8869 static int bpf_link__detach_fd(struct bpf_link *link)
8871 return libbpf_err_errno(close(link->fd));
8874 struct bpf_link *bpf_link__open(const char *path)
8876 struct bpf_link *link;
8879 fd = bpf_obj_get(path);
8882 pr_warn("failed to open link at %s: %d\n", path, fd);
8883 return libbpf_err_ptr(fd);
8886 link = calloc(1, sizeof(*link));
8889 return libbpf_err_ptr(-ENOMEM);
8891 link->detach = &bpf_link__detach_fd;
8894 link->pin_path = strdup(path);
8895 if (!link->pin_path) {
8896 bpf_link__destroy(link);
8897 return libbpf_err_ptr(-ENOMEM);
8903 int bpf_link__detach(struct bpf_link *link)
8905 return bpf_link_detach(link->fd) ? -errno : 0;
8908 int bpf_link__pin(struct bpf_link *link, const char *path)
8913 return libbpf_err(-EBUSY);
8914 err = make_parent_dir(path);
8916 return libbpf_err(err);
8917 err = check_path(path);
8919 return libbpf_err(err);
8921 link->pin_path = strdup(path);
8922 if (!link->pin_path)
8923 return libbpf_err(-ENOMEM);
8925 if (bpf_obj_pin(link->fd, link->pin_path)) {
8927 zfree(&link->pin_path);
8928 return libbpf_err(err);
8931 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
8935 int bpf_link__unpin(struct bpf_link *link)
8939 if (!link->pin_path)
8940 return libbpf_err(-EINVAL);
8942 err = unlink(link->pin_path);
8946 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
8947 zfree(&link->pin_path);
8951 static int bpf_link__detach_perf_event(struct bpf_link *link)
8955 err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
8960 return libbpf_err(err);
8963 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog, int pfd)
8965 char errmsg[STRERR_BUFSIZE];
8966 struct bpf_link *link;
8970 pr_warn("prog '%s': invalid perf event FD %d\n",
8972 return libbpf_err_ptr(-EINVAL);
8974 prog_fd = bpf_program__fd(prog);
8976 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
8978 return libbpf_err_ptr(-EINVAL);
8981 link = calloc(1, sizeof(*link));
8983 return libbpf_err_ptr(-ENOMEM);
8984 link->detach = &bpf_link__detach_perf_event;
8987 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
8990 pr_warn("prog '%s': failed to attach to pfd %d: %s\n",
8991 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8993 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
8995 return libbpf_err_ptr(err);
8997 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9000 pr_warn("prog '%s': failed to enable pfd %d: %s\n",
9001 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9002 return libbpf_err_ptr(err);
9008 * this function is expected to parse integer in the range of [0, 2^31-1] from
9009 * given file using scanf format string fmt. If actual parsed value is
9010 * negative, the result might be indistinguishable from error
9012 static int parse_uint_from_file(const char *file, const char *fmt)
9014 char buf[STRERR_BUFSIZE];
9018 f = fopen(file, "r");
9021 pr_debug("failed to open '%s': %s\n", file,
9022 libbpf_strerror_r(err, buf, sizeof(buf)));
9025 err = fscanf(f, fmt, &ret);
9027 err = err == EOF ? -EIO : -errno;
9028 pr_debug("failed to parse '%s': %s\n", file,
9029 libbpf_strerror_r(err, buf, sizeof(buf)));
9037 static int determine_kprobe_perf_type(void)
9039 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9041 return parse_uint_from_file(file, "%d\n");
9044 static int determine_uprobe_perf_type(void)
9046 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9048 return parse_uint_from_file(file, "%d\n");
9051 static int determine_kprobe_retprobe_bit(void)
9053 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9055 return parse_uint_from_file(file, "config:%d\n");
9058 static int determine_uprobe_retprobe_bit(void)
9060 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9062 return parse_uint_from_file(file, "config:%d\n");
9065 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9066 uint64_t offset, int pid)
9068 struct perf_event_attr attr = {};
9069 char errmsg[STRERR_BUFSIZE];
9072 type = uprobe ? determine_uprobe_perf_type()
9073 : determine_kprobe_perf_type();
9075 pr_warn("failed to determine %s perf type: %s\n",
9076 uprobe ? "uprobe" : "kprobe",
9077 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9081 int bit = uprobe ? determine_uprobe_retprobe_bit()
9082 : determine_kprobe_retprobe_bit();
9085 pr_warn("failed to determine %s retprobe bit: %s\n",
9086 uprobe ? "uprobe" : "kprobe",
9087 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9090 attr.config |= 1 << bit;
9092 attr.size = sizeof(attr);
9094 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9095 attr.config2 = offset; /* kprobe_addr or probe_offset */
9097 /* pid filter is meaningful only for uprobes */
9098 pfd = syscall(__NR_perf_event_open, &attr,
9099 pid < 0 ? -1 : pid /* pid */,
9100 pid == -1 ? 0 : -1 /* cpu */,
9101 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9104 pr_warn("%s perf_event_open() failed: %s\n",
9105 uprobe ? "uprobe" : "kprobe",
9106 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9113 bpf_program__attach_kprobe_opts(struct bpf_program *prog,
9114 const char *func_name,
9115 struct bpf_kprobe_opts *opts)
9117 char errmsg[STRERR_BUFSIZE];
9118 struct bpf_link *link;
9119 unsigned long offset;
9123 if (!OPTS_VALID(opts, bpf_kprobe_opts))
9124 return libbpf_err_ptr(-EINVAL);
9126 retprobe = OPTS_GET(opts, retprobe, false);
9127 offset = OPTS_GET(opts, offset, 0);
9129 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
9130 offset, -1 /* pid */);
9132 pr_warn("prog '%s': failed to create %s '%s' perf event: %s\n",
9133 prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9134 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9135 return libbpf_err_ptr(pfd);
9137 link = bpf_program__attach_perf_event(prog, pfd);
9138 err = libbpf_get_error(link);
9141 pr_warn("prog '%s': failed to attach to %s '%s': %s\n",
9142 prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9143 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9144 return libbpf_err_ptr(err);
9149 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
9151 const char *func_name)
9153 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
9154 .retprobe = retprobe,
9157 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
9160 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
9161 struct bpf_program *prog)
9163 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
9164 unsigned long offset = 0;
9165 struct bpf_link *link;
9166 const char *func_name;
9170 func_name = prog->sec_name + sec->len;
9171 opts.retprobe = strcmp(sec->sec, "kretprobe/") == 0;
9173 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
9176 pr_warn("kprobe name is invalid: %s\n", func_name);
9177 return libbpf_err_ptr(err);
9179 if (opts.retprobe && offset != 0) {
9182 pr_warn("kretprobes do not support offset specification\n");
9183 return libbpf_err_ptr(err);
9186 opts.offset = offset;
9187 link = bpf_program__attach_kprobe_opts(prog, func, &opts);
9192 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
9193 bool retprobe, pid_t pid,
9194 const char *binary_path,
9197 char errmsg[STRERR_BUFSIZE];
9198 struct bpf_link *link;
9201 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
9202 binary_path, func_offset, pid);
9204 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
9205 prog->name, retprobe ? "uretprobe" : "uprobe",
9206 binary_path, func_offset,
9207 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9208 return libbpf_err_ptr(pfd);
9210 link = bpf_program__attach_perf_event(prog, pfd);
9211 err = libbpf_get_error(link);
9214 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
9215 prog->name, retprobe ? "uretprobe" : "uprobe",
9216 binary_path, func_offset,
9217 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9218 return libbpf_err_ptr(err);
9223 static int determine_tracepoint_id(const char *tp_category,
9224 const char *tp_name)
9226 char file[PATH_MAX];
9229 ret = snprintf(file, sizeof(file),
9230 "/sys/kernel/debug/tracing/events/%s/%s/id",
9231 tp_category, tp_name);
9234 if (ret >= sizeof(file)) {
9235 pr_debug("tracepoint %s/%s path is too long\n",
9236 tp_category, tp_name);
9239 return parse_uint_from_file(file, "%d\n");
9242 static int perf_event_open_tracepoint(const char *tp_category,
9243 const char *tp_name)
9245 struct perf_event_attr attr = {};
9246 char errmsg[STRERR_BUFSIZE];
9247 int tp_id, pfd, err;
9249 tp_id = determine_tracepoint_id(tp_category, tp_name);
9251 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
9252 tp_category, tp_name,
9253 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
9257 attr.type = PERF_TYPE_TRACEPOINT;
9258 attr.size = sizeof(attr);
9259 attr.config = tp_id;
9261 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
9262 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9265 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
9266 tp_category, tp_name,
9267 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9273 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
9274 const char *tp_category,
9275 const char *tp_name)
9277 char errmsg[STRERR_BUFSIZE];
9278 struct bpf_link *link;
9281 pfd = perf_event_open_tracepoint(tp_category, tp_name);
9283 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
9284 prog->name, tp_category, tp_name,
9285 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9286 return libbpf_err_ptr(pfd);
9288 link = bpf_program__attach_perf_event(prog, pfd);
9289 err = libbpf_get_error(link);
9292 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
9293 prog->name, tp_category, tp_name,
9294 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9295 return libbpf_err_ptr(err);
9300 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
9301 struct bpf_program *prog)
9303 char *sec_name, *tp_cat, *tp_name;
9304 struct bpf_link *link;
9306 sec_name = strdup(prog->sec_name);
9308 return libbpf_err_ptr(-ENOMEM);
9310 /* extract "tp/<category>/<name>" */
9311 tp_cat = sec_name + sec->len;
9312 tp_name = strchr(tp_cat, '/');
9315 return libbpf_err_ptr(-EINVAL);
9320 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
9325 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
9326 const char *tp_name)
9328 char errmsg[STRERR_BUFSIZE];
9329 struct bpf_link *link;
9332 prog_fd = bpf_program__fd(prog);
9334 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9335 return libbpf_err_ptr(-EINVAL);
9338 link = calloc(1, sizeof(*link));
9340 return libbpf_err_ptr(-ENOMEM);
9341 link->detach = &bpf_link__detach_fd;
9343 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
9347 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
9348 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9349 return libbpf_err_ptr(pfd);
9355 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
9356 struct bpf_program *prog)
9358 const char *tp_name = prog->sec_name + sec->len;
9360 return bpf_program__attach_raw_tracepoint(prog, tp_name);
9363 /* Common logic for all BPF program types that attach to a btf_id */
9364 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
9366 char errmsg[STRERR_BUFSIZE];
9367 struct bpf_link *link;
9370 prog_fd = bpf_program__fd(prog);
9372 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9373 return libbpf_err_ptr(-EINVAL);
9376 link = calloc(1, sizeof(*link));
9378 return libbpf_err_ptr(-ENOMEM);
9379 link->detach = &bpf_link__detach_fd;
9381 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
9385 pr_warn("prog '%s': failed to attach: %s\n",
9386 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9387 return libbpf_err_ptr(pfd);
9390 return (struct bpf_link *)link;
9393 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
9395 return bpf_program__attach_btf_id(prog);
9398 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
9400 return bpf_program__attach_btf_id(prog);
9403 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
9404 struct bpf_program *prog)
9406 return bpf_program__attach_trace(prog);
9409 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
9410 struct bpf_program *prog)
9412 return bpf_program__attach_lsm(prog);
9415 static struct bpf_link *
9416 bpf_program__attach_fd(struct bpf_program *prog, int target_fd, int btf_id,
9417 const char *target_name)
9419 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
9420 .target_btf_id = btf_id);
9421 enum bpf_attach_type attach_type;
9422 char errmsg[STRERR_BUFSIZE];
9423 struct bpf_link *link;
9424 int prog_fd, link_fd;
9426 prog_fd = bpf_program__fd(prog);
9428 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9429 return libbpf_err_ptr(-EINVAL);
9432 link = calloc(1, sizeof(*link));
9434 return libbpf_err_ptr(-ENOMEM);
9435 link->detach = &bpf_link__detach_fd;
9437 attach_type = bpf_program__get_expected_attach_type(prog);
9438 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
9442 pr_warn("prog '%s': failed to attach to %s: %s\n",
9443 prog->name, target_name,
9444 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9445 return libbpf_err_ptr(link_fd);
9452 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
9454 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
9458 bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
9460 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
9463 struct bpf_link *bpf_program__attach_xdp(struct bpf_program *prog, int ifindex)
9465 /* target_fd/target_ifindex use the same field in LINK_CREATE */
9466 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
9469 struct bpf_link *bpf_program__attach_freplace(struct bpf_program *prog,
9471 const char *attach_func_name)
9475 if (!!target_fd != !!attach_func_name) {
9476 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
9478 return libbpf_err_ptr(-EINVAL);
9481 if (prog->type != BPF_PROG_TYPE_EXT) {
9482 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
9484 return libbpf_err_ptr(-EINVAL);
9488 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
9490 return libbpf_err_ptr(btf_id);
9492 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
9494 /* no target, so use raw_tracepoint_open for compatibility
9497 return bpf_program__attach_trace(prog);
9502 bpf_program__attach_iter(struct bpf_program *prog,
9503 const struct bpf_iter_attach_opts *opts)
9505 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
9506 char errmsg[STRERR_BUFSIZE];
9507 struct bpf_link *link;
9508 int prog_fd, link_fd;
9509 __u32 target_fd = 0;
9511 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
9512 return libbpf_err_ptr(-EINVAL);
9514 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
9515 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
9517 prog_fd = bpf_program__fd(prog);
9519 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9520 return libbpf_err_ptr(-EINVAL);
9523 link = calloc(1, sizeof(*link));
9525 return libbpf_err_ptr(-ENOMEM);
9526 link->detach = &bpf_link__detach_fd;
9528 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
9533 pr_warn("prog '%s': failed to attach to iterator: %s\n",
9534 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9535 return libbpf_err_ptr(link_fd);
9541 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
9542 struct bpf_program *prog)
9544 return bpf_program__attach_iter(prog, NULL);
9547 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
9549 const struct bpf_sec_def *sec_def;
9551 sec_def = find_sec_def(prog->sec_name);
9552 if (!sec_def || !sec_def->attach_fn)
9553 return libbpf_err_ptr(-ESRCH);
9555 return sec_def->attach_fn(sec_def, prog);
9558 static int bpf_link__detach_struct_ops(struct bpf_link *link)
9562 if (bpf_map_delete_elem(link->fd, &zero))
9568 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
9570 struct bpf_struct_ops *st_ops;
9571 struct bpf_link *link;
9575 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
9576 return libbpf_err_ptr(-EINVAL);
9578 link = calloc(1, sizeof(*link));
9580 return libbpf_err_ptr(-EINVAL);
9582 st_ops = map->st_ops;
9583 for (i = 0; i < btf_vlen(st_ops->type); i++) {
9584 struct bpf_program *prog = st_ops->progs[i];
9591 prog_fd = bpf_program__fd(prog);
9592 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9593 *(unsigned long *)kern_data = prog_fd;
9596 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
9600 return libbpf_err_ptr(err);
9603 link->detach = bpf_link__detach_struct_ops;
9609 enum bpf_perf_event_ret
9610 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
9611 void **copy_mem, size_t *copy_size,
9612 bpf_perf_event_print_t fn, void *private_data)
9614 struct perf_event_mmap_page *header = mmap_mem;
9615 __u64 data_head = ring_buffer_read_head(header);
9616 __u64 data_tail = header->data_tail;
9617 void *base = ((__u8 *)header) + page_size;
9618 int ret = LIBBPF_PERF_EVENT_CONT;
9619 struct perf_event_header *ehdr;
9622 while (data_head != data_tail) {
9623 ehdr = base + (data_tail & (mmap_size - 1));
9624 ehdr_size = ehdr->size;
9626 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
9627 void *copy_start = ehdr;
9628 size_t len_first = base + mmap_size - copy_start;
9629 size_t len_secnd = ehdr_size - len_first;
9631 if (*copy_size < ehdr_size) {
9633 *copy_mem = malloc(ehdr_size);
9636 ret = LIBBPF_PERF_EVENT_ERROR;
9639 *copy_size = ehdr_size;
9642 memcpy(*copy_mem, copy_start, len_first);
9643 memcpy(*copy_mem + len_first, base, len_secnd);
9647 ret = fn(ehdr, private_data);
9648 data_tail += ehdr_size;
9649 if (ret != LIBBPF_PERF_EVENT_CONT)
9653 ring_buffer_write_tail(header, data_tail);
9654 return libbpf_err(ret);
9659 struct perf_buffer_params {
9660 struct perf_event_attr *attr;
9661 /* if event_cb is specified, it takes precendence */
9662 perf_buffer_event_fn event_cb;
9663 /* sample_cb and lost_cb are higher-level common-case callbacks */
9664 perf_buffer_sample_fn sample_cb;
9665 perf_buffer_lost_fn lost_cb;
9672 struct perf_cpu_buf {
9673 struct perf_buffer *pb;
9674 void *base; /* mmap()'ed memory */
9675 void *buf; /* for reconstructing segmented data */
9682 struct perf_buffer {
9683 perf_buffer_event_fn event_cb;
9684 perf_buffer_sample_fn sample_cb;
9685 perf_buffer_lost_fn lost_cb;
9686 void *ctx; /* passed into callbacks */
9690 struct perf_cpu_buf **cpu_bufs;
9691 struct epoll_event *events;
9692 int cpu_cnt; /* number of allocated CPU buffers */
9693 int epoll_fd; /* perf event FD */
9694 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
9697 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
9698 struct perf_cpu_buf *cpu_buf)
9702 if (cpu_buf->base &&
9703 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
9704 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
9705 if (cpu_buf->fd >= 0) {
9706 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
9713 void perf_buffer__free(struct perf_buffer *pb)
9717 if (IS_ERR_OR_NULL(pb))
9720 for (i = 0; i < pb->cpu_cnt; i++) {
9721 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
9726 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
9727 perf_buffer__free_cpu_buf(pb, cpu_buf);
9731 if (pb->epoll_fd >= 0)
9732 close(pb->epoll_fd);
9737 static struct perf_cpu_buf *
9738 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
9739 int cpu, int map_key)
9741 struct perf_cpu_buf *cpu_buf;
9742 char msg[STRERR_BUFSIZE];
9745 cpu_buf = calloc(1, sizeof(*cpu_buf));
9747 return ERR_PTR(-ENOMEM);
9751 cpu_buf->map_key = map_key;
9753 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
9754 -1, PERF_FLAG_FD_CLOEXEC);
9755 if (cpu_buf->fd < 0) {
9757 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
9758 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9762 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
9763 PROT_READ | PROT_WRITE, MAP_SHARED,
9765 if (cpu_buf->base == MAP_FAILED) {
9766 cpu_buf->base = NULL;
9768 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
9769 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9773 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9775 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
9776 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9783 perf_buffer__free_cpu_buf(pb, cpu_buf);
9784 return (struct perf_cpu_buf *)ERR_PTR(err);
9787 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
9788 struct perf_buffer_params *p);
9790 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
9791 const struct perf_buffer_opts *opts)
9793 struct perf_buffer_params p = {};
9794 struct perf_event_attr attr = { 0, };
9796 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
9797 attr.type = PERF_TYPE_SOFTWARE;
9798 attr.sample_type = PERF_SAMPLE_RAW;
9799 attr.sample_period = 1;
9800 attr.wakeup_events = 1;
9803 p.sample_cb = opts ? opts->sample_cb : NULL;
9804 p.lost_cb = opts ? opts->lost_cb : NULL;
9805 p.ctx = opts ? opts->ctx : NULL;
9807 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
9810 struct perf_buffer *
9811 perf_buffer__new_raw(int map_fd, size_t page_cnt,
9812 const struct perf_buffer_raw_opts *opts)
9814 struct perf_buffer_params p = {};
9816 p.attr = opts->attr;
9817 p.event_cb = opts->event_cb;
9819 p.cpu_cnt = opts->cpu_cnt;
9820 p.cpus = opts->cpus;
9821 p.map_keys = opts->map_keys;
9823 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
9826 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
9827 struct perf_buffer_params *p)
9829 const char *online_cpus_file = "/sys/devices/system/cpu/online";
9830 struct bpf_map_info map;
9831 char msg[STRERR_BUFSIZE];
9832 struct perf_buffer *pb;
9833 bool *online = NULL;
9837 if (page_cnt & (page_cnt - 1)) {
9838 pr_warn("page count should be power of two, but is %zu\n",
9840 return ERR_PTR(-EINVAL);
9843 /* best-effort sanity checks */
9844 memset(&map, 0, sizeof(map));
9845 map_info_len = sizeof(map);
9846 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
9849 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
9850 * -EBADFD, -EFAULT, or -E2BIG on real error
9852 if (err != -EINVAL) {
9853 pr_warn("failed to get map info for map FD %d: %s\n",
9854 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
9855 return ERR_PTR(err);
9857 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
9860 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
9861 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
9863 return ERR_PTR(-EINVAL);
9867 pb = calloc(1, sizeof(*pb));
9869 return ERR_PTR(-ENOMEM);
9871 pb->event_cb = p->event_cb;
9872 pb->sample_cb = p->sample_cb;
9873 pb->lost_cb = p->lost_cb;
9876 pb->page_size = getpagesize();
9877 pb->mmap_size = pb->page_size * page_cnt;
9878 pb->map_fd = map_fd;
9880 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
9881 if (pb->epoll_fd < 0) {
9883 pr_warn("failed to create epoll instance: %s\n",
9884 libbpf_strerror_r(err, msg, sizeof(msg)));
9888 if (p->cpu_cnt > 0) {
9889 pb->cpu_cnt = p->cpu_cnt;
9891 pb->cpu_cnt = libbpf_num_possible_cpus();
9892 if (pb->cpu_cnt < 0) {
9896 if (map.max_entries && map.max_entries < pb->cpu_cnt)
9897 pb->cpu_cnt = map.max_entries;
9900 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
9903 pr_warn("failed to allocate events: out of memory\n");
9906 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
9907 if (!pb->cpu_bufs) {
9909 pr_warn("failed to allocate buffers: out of memory\n");
9913 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
9915 pr_warn("failed to get online CPU mask: %d\n", err);
9919 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
9920 struct perf_cpu_buf *cpu_buf;
9923 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
9924 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
9926 /* in case user didn't explicitly requested particular CPUs to
9927 * be attached to, skip offline/not present CPUs
9929 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
9932 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
9933 if (IS_ERR(cpu_buf)) {
9934 err = PTR_ERR(cpu_buf);
9938 pb->cpu_bufs[j] = cpu_buf;
9940 err = bpf_map_update_elem(pb->map_fd, &map_key,
9944 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
9945 cpu, map_key, cpu_buf->fd,
9946 libbpf_strerror_r(err, msg, sizeof(msg)));
9950 pb->events[j].events = EPOLLIN;
9951 pb->events[j].data.ptr = cpu_buf;
9952 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
9953 &pb->events[j]) < 0) {
9955 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
9957 libbpf_strerror_r(err, msg, sizeof(msg)));
9970 perf_buffer__free(pb);
9971 return ERR_PTR(err);
9974 struct perf_sample_raw {
9975 struct perf_event_header header;
9980 struct perf_sample_lost {
9981 struct perf_event_header header;
9987 static enum bpf_perf_event_ret
9988 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
9990 struct perf_cpu_buf *cpu_buf = ctx;
9991 struct perf_buffer *pb = cpu_buf->pb;
9994 /* user wants full control over parsing perf event */
9996 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
9999 case PERF_RECORD_SAMPLE: {
10000 struct perf_sample_raw *s = data;
10003 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
10006 case PERF_RECORD_LOST: {
10007 struct perf_sample_lost *s = data;
10010 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
10014 pr_warn("unknown perf sample type %d\n", e->type);
10015 return LIBBPF_PERF_EVENT_ERROR;
10017 return LIBBPF_PERF_EVENT_CONT;
10020 static int perf_buffer__process_records(struct perf_buffer *pb,
10021 struct perf_cpu_buf *cpu_buf)
10023 enum bpf_perf_event_ret ret;
10025 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
10026 pb->page_size, &cpu_buf->buf,
10027 &cpu_buf->buf_size,
10028 perf_buffer__process_record, cpu_buf);
10029 if (ret != LIBBPF_PERF_EVENT_CONT)
10034 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
10036 return pb->epoll_fd;
10039 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
10043 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
10047 for (i = 0; i < cnt; i++) {
10048 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
10050 err = perf_buffer__process_records(pb, cpu_buf);
10052 pr_warn("error while processing records: %d\n", err);
10053 return libbpf_err(err);
10059 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
10062 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
10064 return pb->cpu_cnt;
10068 * Return perf_event FD of a ring buffer in *buf_idx* slot of
10069 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
10070 * select()/poll()/epoll() Linux syscalls.
10072 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
10074 struct perf_cpu_buf *cpu_buf;
10076 if (buf_idx >= pb->cpu_cnt)
10077 return libbpf_err(-EINVAL);
10079 cpu_buf = pb->cpu_bufs[buf_idx];
10081 return libbpf_err(-ENOENT);
10083 return cpu_buf->fd;
10087 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
10088 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
10089 * consume, do nothing and return success.
10094 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
10096 struct perf_cpu_buf *cpu_buf;
10098 if (buf_idx >= pb->cpu_cnt)
10099 return libbpf_err(-EINVAL);
10101 cpu_buf = pb->cpu_bufs[buf_idx];
10103 return libbpf_err(-ENOENT);
10105 return perf_buffer__process_records(pb, cpu_buf);
10108 int perf_buffer__consume(struct perf_buffer *pb)
10112 for (i = 0; i < pb->cpu_cnt; i++) {
10113 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10118 err = perf_buffer__process_records(pb, cpu_buf);
10120 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
10121 return libbpf_err(err);
10127 struct bpf_prog_info_array_desc {
10128 int array_offset; /* e.g. offset of jited_prog_insns */
10129 int count_offset; /* e.g. offset of jited_prog_len */
10130 int size_offset; /* > 0: offset of rec size,
10131 * < 0: fix size of -size_offset
10135 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
10136 [BPF_PROG_INFO_JITED_INSNS] = {
10137 offsetof(struct bpf_prog_info, jited_prog_insns),
10138 offsetof(struct bpf_prog_info, jited_prog_len),
10141 [BPF_PROG_INFO_XLATED_INSNS] = {
10142 offsetof(struct bpf_prog_info, xlated_prog_insns),
10143 offsetof(struct bpf_prog_info, xlated_prog_len),
10146 [BPF_PROG_INFO_MAP_IDS] = {
10147 offsetof(struct bpf_prog_info, map_ids),
10148 offsetof(struct bpf_prog_info, nr_map_ids),
10149 -(int)sizeof(__u32),
10151 [BPF_PROG_INFO_JITED_KSYMS] = {
10152 offsetof(struct bpf_prog_info, jited_ksyms),
10153 offsetof(struct bpf_prog_info, nr_jited_ksyms),
10154 -(int)sizeof(__u64),
10156 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
10157 offsetof(struct bpf_prog_info, jited_func_lens),
10158 offsetof(struct bpf_prog_info, nr_jited_func_lens),
10159 -(int)sizeof(__u32),
10161 [BPF_PROG_INFO_FUNC_INFO] = {
10162 offsetof(struct bpf_prog_info, func_info),
10163 offsetof(struct bpf_prog_info, nr_func_info),
10164 offsetof(struct bpf_prog_info, func_info_rec_size),
10166 [BPF_PROG_INFO_LINE_INFO] = {
10167 offsetof(struct bpf_prog_info, line_info),
10168 offsetof(struct bpf_prog_info, nr_line_info),
10169 offsetof(struct bpf_prog_info, line_info_rec_size),
10171 [BPF_PROG_INFO_JITED_LINE_INFO] = {
10172 offsetof(struct bpf_prog_info, jited_line_info),
10173 offsetof(struct bpf_prog_info, nr_jited_line_info),
10174 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
10176 [BPF_PROG_INFO_PROG_TAGS] = {
10177 offsetof(struct bpf_prog_info, prog_tags),
10178 offsetof(struct bpf_prog_info, nr_prog_tags),
10179 -(int)sizeof(__u8) * BPF_TAG_SIZE,
10184 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
10187 __u32 *array = (__u32 *)info;
10190 return array[offset / sizeof(__u32)];
10191 return -(int)offset;
10194 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
10197 __u64 *array = (__u64 *)info;
10200 return array[offset / sizeof(__u64)];
10201 return -(int)offset;
10204 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
10207 __u32 *array = (__u32 *)info;
10210 array[offset / sizeof(__u32)] = val;
10213 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
10216 __u64 *array = (__u64 *)info;
10219 array[offset / sizeof(__u64)] = val;
10222 struct bpf_prog_info_linear *
10223 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
10225 struct bpf_prog_info_linear *info_linear;
10226 struct bpf_prog_info info = {};
10227 __u32 info_len = sizeof(info);
10228 __u32 data_len = 0;
10232 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
10233 return libbpf_err_ptr(-EINVAL);
10235 /* step 1: get array dimensions */
10236 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
10238 pr_debug("can't get prog info: %s", strerror(errno));
10239 return libbpf_err_ptr(-EFAULT);
10242 /* step 2: calculate total size of all arrays */
10243 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10244 bool include_array = (arrays & (1UL << i)) > 0;
10245 struct bpf_prog_info_array_desc *desc;
10248 desc = bpf_prog_info_array_desc + i;
10250 /* kernel is too old to support this field */
10251 if (info_len < desc->array_offset + sizeof(__u32) ||
10252 info_len < desc->count_offset + sizeof(__u32) ||
10253 (desc->size_offset > 0 && info_len < desc->size_offset))
10254 include_array = false;
10256 if (!include_array) {
10257 arrays &= ~(1UL << i); /* clear the bit */
10261 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10262 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10264 data_len += count * size;
10267 /* step 3: allocate continuous memory */
10268 data_len = roundup(data_len, sizeof(__u64));
10269 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
10271 return libbpf_err_ptr(-ENOMEM);
10273 /* step 4: fill data to info_linear->info */
10274 info_linear->arrays = arrays;
10275 memset(&info_linear->info, 0, sizeof(info));
10276 ptr = info_linear->data;
10278 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10279 struct bpf_prog_info_array_desc *desc;
10282 if ((arrays & (1UL << i)) == 0)
10285 desc = bpf_prog_info_array_desc + i;
10286 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10287 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10288 bpf_prog_info_set_offset_u32(&info_linear->info,
10289 desc->count_offset, count);
10290 bpf_prog_info_set_offset_u32(&info_linear->info,
10291 desc->size_offset, size);
10292 bpf_prog_info_set_offset_u64(&info_linear->info,
10293 desc->array_offset,
10295 ptr += count * size;
10298 /* step 5: call syscall again to get required arrays */
10299 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
10301 pr_debug("can't get prog info: %s", strerror(errno));
10303 return libbpf_err_ptr(-EFAULT);
10306 /* step 6: verify the data */
10307 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10308 struct bpf_prog_info_array_desc *desc;
10311 if ((arrays & (1UL << i)) == 0)
10314 desc = bpf_prog_info_array_desc + i;
10315 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10316 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10317 desc->count_offset);
10319 pr_warn("%s: mismatch in element count\n", __func__);
10321 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10322 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10323 desc->size_offset);
10325 pr_warn("%s: mismatch in rec size\n", __func__);
10328 /* step 7: update info_len and data_len */
10329 info_linear->info_len = sizeof(struct bpf_prog_info);
10330 info_linear->data_len = data_len;
10332 return info_linear;
10335 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
10339 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10340 struct bpf_prog_info_array_desc *desc;
10343 if ((info_linear->arrays & (1UL << i)) == 0)
10346 desc = bpf_prog_info_array_desc + i;
10347 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
10348 desc->array_offset);
10349 offs = addr - ptr_to_u64(info_linear->data);
10350 bpf_prog_info_set_offset_u64(&info_linear->info,
10351 desc->array_offset, offs);
10355 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
10359 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10360 struct bpf_prog_info_array_desc *desc;
10363 if ((info_linear->arrays & (1UL << i)) == 0)
10366 desc = bpf_prog_info_array_desc + i;
10367 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
10368 desc->array_offset);
10369 addr = offs + ptr_to_u64(info_linear->data);
10370 bpf_prog_info_set_offset_u64(&info_linear->info,
10371 desc->array_offset, addr);
10375 int bpf_program__set_attach_target(struct bpf_program *prog,
10376 int attach_prog_fd,
10377 const char *attach_func_name)
10379 int btf_obj_fd = 0, btf_id = 0, err;
10381 if (!prog || attach_prog_fd < 0 || !attach_func_name)
10382 return libbpf_err(-EINVAL);
10384 if (prog->obj->loaded)
10385 return libbpf_err(-EINVAL);
10387 if (attach_prog_fd) {
10388 btf_id = libbpf_find_prog_btf_id(attach_func_name,
10391 return libbpf_err(btf_id);
10393 /* load btf_vmlinux, if not yet */
10394 err = bpf_object__load_vmlinux_btf(prog->obj, true);
10396 return libbpf_err(err);
10397 err = find_kernel_btf_id(prog->obj, attach_func_name,
10398 prog->expected_attach_type,
10399 &btf_obj_fd, &btf_id);
10401 return libbpf_err(err);
10404 prog->attach_btf_id = btf_id;
10405 prog->attach_btf_obj_fd = btf_obj_fd;
10406 prog->attach_prog_fd = attach_prog_fd;
10410 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
10412 int err = 0, n, len, start, end = -1;
10418 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
10420 if (*s == ',' || *s == '\n') {
10424 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
10425 if (n <= 0 || n > 2) {
10426 pr_warn("Failed to get CPU range %s: %d\n", s, n);
10429 } else if (n == 1) {
10432 if (start < 0 || start > end) {
10433 pr_warn("Invalid CPU range [%d,%d] in %s\n",
10438 tmp = realloc(*mask, end + 1);
10444 memset(tmp + *mask_sz, 0, start - *mask_sz);
10445 memset(tmp + start, 1, end - start + 1);
10446 *mask_sz = end + 1;
10450 pr_warn("Empty CPU range\n");
10460 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
10462 int fd, err = 0, len;
10465 fd = open(fcpu, O_RDONLY);
10468 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
10471 len = read(fd, buf, sizeof(buf));
10474 err = len ? -errno : -EINVAL;
10475 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
10478 if (len >= sizeof(buf)) {
10479 pr_warn("CPU mask is too big in file %s\n", fcpu);
10484 return parse_cpu_mask_str(buf, mask, mask_sz);
10487 int libbpf_num_possible_cpus(void)
10489 static const char *fcpu = "/sys/devices/system/cpu/possible";
10491 int err, n, i, tmp_cpus;
10494 tmp_cpus = READ_ONCE(cpus);
10498 err = parse_cpu_mask_file(fcpu, &mask, &n);
10500 return libbpf_err(err);
10503 for (i = 0; i < n; i++) {
10509 WRITE_ONCE(cpus, tmp_cpus);
10513 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
10514 const struct bpf_object_open_opts *opts)
10516 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
10517 .object_name = s->name,
10519 struct bpf_object *obj;
10522 /* Attempt to preserve opts->object_name, unless overriden by user
10523 * explicitly. Overwriting object name for skeletons is discouraged,
10524 * as it breaks global data maps, because they contain object name
10525 * prefix as their own map name prefix. When skeleton is generated,
10526 * bpftool is making an assumption that this name will stay the same.
10529 memcpy(&skel_opts, opts, sizeof(*opts));
10530 if (!opts->object_name)
10531 skel_opts.object_name = s->name;
10534 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
10535 err = libbpf_get_error(obj);
10537 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
10539 return libbpf_err(err);
10544 for (i = 0; i < s->map_cnt; i++) {
10545 struct bpf_map **map = s->maps[i].map;
10546 const char *name = s->maps[i].name;
10547 void **mmaped = s->maps[i].mmaped;
10549 *map = bpf_object__find_map_by_name(obj, name);
10551 pr_warn("failed to find skeleton map '%s'\n", name);
10552 return libbpf_err(-ESRCH);
10555 /* externs shouldn't be pre-setup from user code */
10556 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
10557 *mmaped = (*map)->mmaped;
10560 for (i = 0; i < s->prog_cnt; i++) {
10561 struct bpf_program **prog = s->progs[i].prog;
10562 const char *name = s->progs[i].name;
10564 *prog = bpf_object__find_program_by_name(obj, name);
10566 pr_warn("failed to find skeleton program '%s'\n", name);
10567 return libbpf_err(-ESRCH);
10574 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
10578 err = bpf_object__load(*s->obj);
10580 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
10581 return libbpf_err(err);
10584 for (i = 0; i < s->map_cnt; i++) {
10585 struct bpf_map *map = *s->maps[i].map;
10586 size_t mmap_sz = bpf_map_mmap_sz(map);
10587 int prot, map_fd = bpf_map__fd(map);
10588 void **mmaped = s->maps[i].mmaped;
10593 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
10598 if (map->def.map_flags & BPF_F_RDONLY_PROG)
10601 prot = PROT_READ | PROT_WRITE;
10603 /* Remap anonymous mmap()-ed "map initialization image" as
10604 * a BPF map-backed mmap()-ed memory, but preserving the same
10605 * memory address. This will cause kernel to change process'
10606 * page table to point to a different piece of kernel memory,
10607 * but from userspace point of view memory address (and its
10608 * contents, being identical at this point) will stay the
10609 * same. This mapping will be released by bpf_object__close()
10610 * as per normal clean up procedure, so we don't need to worry
10611 * about it from skeleton's clean up perspective.
10613 *mmaped = mmap(map->mmaped, mmap_sz, prot,
10614 MAP_SHARED | MAP_FIXED, map_fd, 0);
10615 if (*mmaped == MAP_FAILED) {
10618 pr_warn("failed to re-mmap() map '%s': %d\n",
10619 bpf_map__name(map), err);
10620 return libbpf_err(err);
10627 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
10631 for (i = 0; i < s->prog_cnt; i++) {
10632 struct bpf_program *prog = *s->progs[i].prog;
10633 struct bpf_link **link = s->progs[i].link;
10634 const struct bpf_sec_def *sec_def;
10639 sec_def = find_sec_def(prog->sec_name);
10640 if (!sec_def || !sec_def->attach_fn)
10643 *link = sec_def->attach_fn(sec_def, prog);
10644 err = libbpf_get_error(*link);
10646 pr_warn("failed to auto-attach program '%s': %d\n",
10647 bpf_program__name(prog), err);
10648 return libbpf_err(err);
10655 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
10659 for (i = 0; i < s->prog_cnt; i++) {
10660 struct bpf_link **link = s->progs[i].link;
10662 bpf_link__destroy(*link);
10667 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
10670 bpf_object__detach_skeleton(s);
10672 bpf_object__close(*s->obj);