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 __u32 libbpf_major_version(void)
173 return LIBBPF_MAJOR_VERSION;
176 __u32 libbpf_minor_version(void)
178 return LIBBPF_MINOR_VERSION;
181 const char *libbpf_version_string(void)
185 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
201 enum reloc_type type;
204 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
214 typedef int (*init_fn_t)(struct bpf_program *prog, long cookie);
215 typedef int (*preload_fn_t)(struct bpf_program *prog, struct bpf_prog_load_opts *opts, long cookie);
216 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_program *prog, long cookie);
218 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
221 /* expected_attach_type is optional, if kernel doesn't support that */
222 SEC_EXP_ATTACH_OPT = 1,
223 /* legacy, only used by libbpf_get_type_names() and
224 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
225 * This used to be associated with cgroup (and few other) BPF programs
226 * that were attachable through BPF_PROG_ATTACH command. Pretty
227 * meaningless nowadays, though.
230 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
231 /* attachment target is specified through BTF ID in either kernel or
232 * other BPF program's BTF object */
234 /* BPF program type allows sleeping/blocking in kernel */
236 /* allow non-strict prefix matching */
242 enum bpf_prog_type prog_type;
243 enum bpf_attach_type expected_attach_type;
247 preload_fn_t preload_fn;
248 attach_fn_t attach_fn;
252 * bpf_prog should be a better name but it has been used in
256 const struct bpf_sec_def *sec_def;
259 /* this program's instruction offset (in number of instructions)
260 * within its containing ELF section
263 /* number of original instructions in ELF section belonging to this
264 * program, not taking into account subprogram instructions possible
265 * appended later during relocation
268 /* Offset (in number of instructions) of the start of instruction
269 * belonging to this BPF program within its containing main BPF
270 * program. For the entry-point (main) BPF program, this is always
271 * zero. For a sub-program, this gets reset before each of main BPF
272 * programs are processed and relocated and is used to determined
273 * whether sub-program was already appended to the main program, and
274 * if yes, at which instruction offset.
279 /* name with / replaced by _; makes recursive pinning
280 * in bpf_object__pin_programs easier
284 /* instructions that belong to BPF program; insns[0] is located at
285 * sec_insn_off instruction within its ELF section in ELF file, so
286 * when mapping ELF file instruction index to the local instruction,
287 * one needs to subtract sec_insn_off; and vice versa.
289 struct bpf_insn *insns;
290 /* actual number of instruction in this BPF program's image; for
291 * entry-point BPF programs this includes the size of main program
292 * itself plus all the used sub-programs, appended at the end
296 struct reloc_desc *reloc_desc;
299 /* BPF verifier log settings */
308 bpf_program_prep_t preprocessor;
310 struct bpf_object *obj;
312 bpf_program_clear_priv_t clear_priv;
315 bool mark_btf_static;
316 enum bpf_prog_type type;
317 enum bpf_attach_type expected_attach_type;
319 __u32 attach_btf_obj_fd;
321 __u32 attach_prog_fd;
323 __u32 func_info_rec_size;
327 __u32 line_info_rec_size;
332 struct bpf_struct_ops {
334 const struct btf_type *type;
335 struct bpf_program **progs;
336 __u32 *kern_func_off;
337 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
339 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
340 * btf_vmlinux's format.
341 * struct bpf_struct_ops_tcp_congestion_ops {
342 * [... some other kernel fields ...]
343 * struct tcp_congestion_ops data;
345 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
346 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
353 #define DATA_SEC ".data"
354 #define BSS_SEC ".bss"
355 #define RODATA_SEC ".rodata"
356 #define KCONFIG_SEC ".kconfig"
357 #define KSYMS_SEC ".ksyms"
358 #define STRUCT_OPS_SEC ".struct_ops"
360 enum libbpf_map_type {
370 /* real_name is defined for special internal maps (.rodata*,
371 * .data*, .bss, .kconfig) and preserves their original ELF section
372 * name. This is important to be be able to find corresponding BTF
373 * DATASEC information.
381 struct bpf_map_def def;
384 __u32 btf_key_type_id;
385 __u32 btf_value_type_id;
386 __u32 btf_vmlinux_value_type_id;
388 bpf_map_clear_priv_t clear_priv;
389 enum libbpf_map_type libbpf_type;
391 struct bpf_struct_ops *st_ops;
392 struct bpf_map *inner_map;
418 enum extern_type type;
434 unsigned long long addr;
436 /* target btf_id of the corresponding kernel var. */
437 int kernel_btf_obj_fd;
440 /* local btf_id of the ksym extern's type. */
442 /* BTF fd index to be patched in for insn->off, this is
443 * 0 for vmlinux BTF, index in obj->fd_array for module
451 static LIST_HEAD(bpf_objects_list);
469 struct elf_sec_desc {
470 enum sec_type sec_type;
482 Elf_Data *st_ops_data;
483 size_t shstrndx; /* section index for section name strings */
485 struct elf_sec_desc *secs;
489 __u32 btf_maps_sec_btf_id;
496 char name[BPF_OBJ_NAME_LEN];
500 struct bpf_program *programs;
502 struct bpf_map *maps;
507 struct extern_desc *externs;
515 struct bpf_gen *gen_loader;
517 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
518 struct elf_state efile;
520 * All loaded bpf_object are linked in a list, which is
521 * hidden to caller. bpf_objects__<func> handlers deal with
524 struct list_head list;
527 struct btf_ext *btf_ext;
529 /* Parse and load BTF vmlinux if any of the programs in the object need
532 struct btf *btf_vmlinux;
533 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
534 * override for vmlinux BTF.
536 char *btf_custom_path;
537 /* vmlinux BTF override for CO-RE relocations */
538 struct btf *btf_vmlinux_override;
539 /* Lazily initialized kernel module BTFs */
540 struct module_btf *btf_modules;
541 bool btf_modules_loaded;
542 size_t btf_module_cnt;
543 size_t btf_module_cap;
545 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
551 bpf_object_clear_priv_t clear_priv;
560 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
561 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
562 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
563 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
564 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
565 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
566 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
567 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
568 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
570 void bpf_program__unload(struct bpf_program *prog)
578 * If the object is opened but the program was never loaded,
579 * it is possible that prog->instances.nr == -1.
581 if (prog->instances.nr > 0) {
582 for (i = 0; i < prog->instances.nr; i++)
583 zclose(prog->instances.fds[i]);
584 } else if (prog->instances.nr != -1) {
585 pr_warn("Internal error: instances.nr is %d\n",
589 prog->instances.nr = -1;
590 zfree(&prog->instances.fds);
592 zfree(&prog->func_info);
593 zfree(&prog->line_info);
596 static void bpf_program__exit(struct bpf_program *prog)
601 if (prog->clear_priv)
602 prog->clear_priv(prog, prog->priv);
605 prog->clear_priv = NULL;
607 bpf_program__unload(prog);
609 zfree(&prog->sec_name);
610 zfree(&prog->pin_name);
612 zfree(&prog->reloc_desc);
619 static char *__bpf_program__pin_name(struct bpf_program *prog)
623 if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
624 name = strdup(prog->name);
626 name = strdup(prog->sec_name);
633 while ((p = strchr(p, '/')))
639 static bool insn_is_subprog_call(const struct bpf_insn *insn)
641 return BPF_CLASS(insn->code) == BPF_JMP &&
642 BPF_OP(insn->code) == BPF_CALL &&
643 BPF_SRC(insn->code) == BPF_K &&
644 insn->src_reg == BPF_PSEUDO_CALL &&
645 insn->dst_reg == 0 &&
649 static bool is_call_insn(const struct bpf_insn *insn)
651 return insn->code == (BPF_JMP | BPF_CALL);
654 static bool insn_is_pseudo_func(struct bpf_insn *insn)
656 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
660 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
661 const char *name, size_t sec_idx, const char *sec_name,
662 size_t sec_off, void *insn_data, size_t insn_data_sz)
664 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
665 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
666 sec_name, name, sec_off, insn_data_sz);
670 memset(prog, 0, sizeof(*prog));
673 prog->sec_idx = sec_idx;
674 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
675 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
676 /* insns_cnt can later be increased by appending used subprograms */
677 prog->insns_cnt = prog->sec_insn_cnt;
679 prog->type = BPF_PROG_TYPE_UNSPEC;
682 prog->instances.fds = NULL;
683 prog->instances.nr = -1;
685 /* inherit object's log_level */
686 prog->log_level = obj->log_level;
688 prog->sec_name = strdup(sec_name);
692 prog->name = strdup(name);
696 prog->pin_name = __bpf_program__pin_name(prog);
700 prog->insns = malloc(insn_data_sz);
703 memcpy(prog->insns, insn_data, insn_data_sz);
707 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
708 bpf_program__exit(prog);
713 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
714 const char *sec_name, int sec_idx)
716 Elf_Data *symbols = obj->efile.symbols;
717 struct bpf_program *prog, *progs;
718 void *data = sec_data->d_buf;
719 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
720 int nr_progs, err, i;
724 progs = obj->programs;
725 nr_progs = obj->nr_programs;
726 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
729 for (i = 0; i < nr_syms; i++) {
730 sym = elf_sym_by_idx(obj, i);
732 if (sym->st_shndx != sec_idx)
734 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
737 prog_sz = sym->st_size;
738 sec_off = sym->st_value;
740 name = elf_sym_str(obj, sym->st_name);
742 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
744 return -LIBBPF_ERRNO__FORMAT;
747 if (sec_off + prog_sz > sec_sz) {
748 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
750 return -LIBBPF_ERRNO__FORMAT;
753 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
754 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
758 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
759 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
761 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
764 * In this case the original obj->programs
765 * is still valid, so don't need special treat for
766 * bpf_close_object().
768 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
772 obj->programs = progs;
774 prog = &progs[nr_progs];
776 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
777 sec_off, data + sec_off, prog_sz);
781 /* if function is a global/weak symbol, but has restricted
782 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
783 * as static to enable more permissive BPF verification mode
784 * with more outside context available to BPF verifier
786 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
787 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
788 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
789 prog->mark_btf_static = true;
792 obj->nr_programs = nr_progs;
798 __u32 get_kernel_version(void)
800 /* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
801 * but Ubuntu provides /proc/version_signature file, as described at
802 * https://ubuntu.com/kernel, with an example contents below, which we
803 * can use to get a proper LINUX_VERSION_CODE.
805 * Ubuntu 5.4.0-12.15-generic 5.4.8
807 * In the above, 5.4.8 is what kernel is actually expecting, while
808 * uname() call will return 5.4.0 in info.release.
810 const char *ubuntu_kver_file = "/proc/version_signature";
811 __u32 major, minor, patch;
814 if (access(ubuntu_kver_file, R_OK) == 0) {
817 f = fopen(ubuntu_kver_file, "r");
819 if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
821 return KERNEL_VERSION(major, minor, patch);
825 /* something went wrong, fall back to uname() approach */
829 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
831 return KERNEL_VERSION(major, minor, patch);
834 static const struct btf_member *
835 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
837 struct btf_member *m;
840 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
841 if (btf_member_bit_offset(t, i) == bit_offset)
848 static const struct btf_member *
849 find_member_by_name(const struct btf *btf, const struct btf_type *t,
852 struct btf_member *m;
855 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
856 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
863 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
864 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
865 const char *name, __u32 kind);
868 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
869 const struct btf_type **type, __u32 *type_id,
870 const struct btf_type **vtype, __u32 *vtype_id,
871 const struct btf_member **data_member)
873 const struct btf_type *kern_type, *kern_vtype;
874 const struct btf_member *kern_data_member;
875 __s32 kern_vtype_id, kern_type_id;
878 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
879 if (kern_type_id < 0) {
880 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
884 kern_type = btf__type_by_id(btf, kern_type_id);
886 /* Find the corresponding "map_value" type that will be used
887 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
888 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
891 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
892 tname, BTF_KIND_STRUCT);
893 if (kern_vtype_id < 0) {
894 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
895 STRUCT_OPS_VALUE_PREFIX, tname);
896 return kern_vtype_id;
898 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
900 /* Find "struct tcp_congestion_ops" from
901 * struct bpf_struct_ops_tcp_congestion_ops {
903 * struct tcp_congestion_ops data;
906 kern_data_member = btf_members(kern_vtype);
907 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
908 if (kern_data_member->type == kern_type_id)
911 if (i == btf_vlen(kern_vtype)) {
912 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
913 tname, STRUCT_OPS_VALUE_PREFIX, tname);
918 *type_id = kern_type_id;
920 *vtype_id = kern_vtype_id;
921 *data_member = kern_data_member;
926 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
928 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
931 /* Init the map's fields that depend on kern_btf */
932 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
933 const struct btf *btf,
934 const struct btf *kern_btf)
936 const struct btf_member *member, *kern_member, *kern_data_member;
937 const struct btf_type *type, *kern_type, *kern_vtype;
938 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
939 struct bpf_struct_ops *st_ops;
940 void *data, *kern_data;
944 st_ops = map->st_ops;
946 tname = st_ops->tname;
947 err = find_struct_ops_kern_types(kern_btf, tname,
948 &kern_type, &kern_type_id,
949 &kern_vtype, &kern_vtype_id,
954 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
955 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
957 map->def.value_size = kern_vtype->size;
958 map->btf_vmlinux_value_type_id = kern_vtype_id;
960 st_ops->kern_vdata = calloc(1, kern_vtype->size);
961 if (!st_ops->kern_vdata)
965 kern_data_off = kern_data_member->offset / 8;
966 kern_data = st_ops->kern_vdata + kern_data_off;
968 member = btf_members(type);
969 for (i = 0; i < btf_vlen(type); i++, member++) {
970 const struct btf_type *mtype, *kern_mtype;
971 __u32 mtype_id, kern_mtype_id;
972 void *mdata, *kern_mdata;
973 __s64 msize, kern_msize;
974 __u32 moff, kern_moff;
975 __u32 kern_member_idx;
978 mname = btf__name_by_offset(btf, member->name_off);
979 kern_member = find_member_by_name(kern_btf, kern_type, mname);
981 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
986 kern_member_idx = kern_member - btf_members(kern_type);
987 if (btf_member_bitfield_size(type, i) ||
988 btf_member_bitfield_size(kern_type, kern_member_idx)) {
989 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
994 moff = member->offset / 8;
995 kern_moff = kern_member->offset / 8;
998 kern_mdata = kern_data + kern_moff;
1000 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1001 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1003 if (BTF_INFO_KIND(mtype->info) !=
1004 BTF_INFO_KIND(kern_mtype->info)) {
1005 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1006 map->name, mname, BTF_INFO_KIND(mtype->info),
1007 BTF_INFO_KIND(kern_mtype->info));
1011 if (btf_is_ptr(mtype)) {
1012 struct bpf_program *prog;
1014 prog = st_ops->progs[i];
1018 kern_mtype = skip_mods_and_typedefs(kern_btf,
1022 /* mtype->type must be a func_proto which was
1023 * guaranteed in bpf_object__collect_st_ops_relos(),
1024 * so only check kern_mtype for func_proto here.
1026 if (!btf_is_func_proto(kern_mtype)) {
1027 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1032 prog->attach_btf_id = kern_type_id;
1033 prog->expected_attach_type = kern_member_idx;
1035 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1037 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1038 map->name, mname, prog->name, moff,
1044 msize = btf__resolve_size(btf, mtype_id);
1045 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1046 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1047 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1048 map->name, mname, (ssize_t)msize,
1049 (ssize_t)kern_msize);
1053 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1054 map->name, mname, (unsigned int)msize,
1056 memcpy(kern_mdata, mdata, msize);
1062 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1064 struct bpf_map *map;
1068 for (i = 0; i < obj->nr_maps; i++) {
1069 map = &obj->maps[i];
1071 if (!bpf_map__is_struct_ops(map))
1074 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1083 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1085 const struct btf_type *type, *datasec;
1086 const struct btf_var_secinfo *vsi;
1087 struct bpf_struct_ops *st_ops;
1088 const char *tname, *var_name;
1089 __s32 type_id, datasec_id;
1090 const struct btf *btf;
1091 struct bpf_map *map;
1094 if (obj->efile.st_ops_shndx == -1)
1098 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1100 if (datasec_id < 0) {
1101 pr_warn("struct_ops init: DATASEC %s not found\n",
1106 datasec = btf__type_by_id(btf, datasec_id);
1107 vsi = btf_var_secinfos(datasec);
1108 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1109 type = btf__type_by_id(obj->btf, vsi->type);
1110 var_name = btf__name_by_offset(obj->btf, type->name_off);
1112 type_id = btf__resolve_type(obj->btf, vsi->type);
1114 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1115 vsi->type, STRUCT_OPS_SEC);
1119 type = btf__type_by_id(obj->btf, type_id);
1120 tname = btf__name_by_offset(obj->btf, type->name_off);
1122 pr_warn("struct_ops init: anonymous type is not supported\n");
1125 if (!btf_is_struct(type)) {
1126 pr_warn("struct_ops init: %s is not a struct\n", tname);
1130 map = bpf_object__add_map(obj);
1132 return PTR_ERR(map);
1134 map->sec_idx = obj->efile.st_ops_shndx;
1135 map->sec_offset = vsi->offset;
1136 map->name = strdup(var_name);
1140 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1141 map->def.key_size = sizeof(int);
1142 map->def.value_size = type->size;
1143 map->def.max_entries = 1;
1145 map->st_ops = calloc(1, sizeof(*map->st_ops));
1148 st_ops = map->st_ops;
1149 st_ops->data = malloc(type->size);
1150 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1151 st_ops->kern_func_off = malloc(btf_vlen(type) *
1152 sizeof(*st_ops->kern_func_off));
1153 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1156 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1157 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1158 var_name, STRUCT_OPS_SEC);
1162 memcpy(st_ops->data,
1163 obj->efile.st_ops_data->d_buf + vsi->offset,
1165 st_ops->tname = tname;
1166 st_ops->type = type;
1167 st_ops->type_id = type_id;
1169 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1170 tname, type_id, var_name, vsi->offset);
1176 static struct bpf_object *bpf_object__new(const char *path,
1177 const void *obj_buf,
1179 const char *obj_name)
1181 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1182 struct bpf_object *obj;
1185 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1187 pr_warn("alloc memory failed for %s\n", path);
1188 return ERR_PTR(-ENOMEM);
1191 strcpy(obj->path, path);
1193 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1195 /* Using basename() GNU version which doesn't modify arg. */
1196 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1197 end = strchr(obj->name, '.');
1204 * Caller of this function should also call
1205 * bpf_object__elf_finish() after data collection to return
1206 * obj_buf to user. If not, we should duplicate the buffer to
1207 * avoid user freeing them before elf finish.
1209 obj->efile.obj_buf = obj_buf;
1210 obj->efile.obj_buf_sz = obj_buf_sz;
1211 obj->efile.maps_shndx = -1;
1212 obj->efile.btf_maps_shndx = -1;
1213 obj->efile.st_ops_shndx = -1;
1214 obj->kconfig_map_idx = -1;
1216 obj->kern_version = get_kernel_version();
1217 obj->loaded = false;
1219 INIT_LIST_HEAD(&obj->list);
1221 list_add(&obj->list, &bpf_objects_list);
1225 static void bpf_object__elf_finish(struct bpf_object *obj)
1227 if (!obj->efile.elf)
1230 if (obj->efile.elf) {
1231 elf_end(obj->efile.elf);
1232 obj->efile.elf = NULL;
1234 obj->efile.symbols = NULL;
1235 obj->efile.st_ops_data = NULL;
1237 zfree(&obj->efile.secs);
1238 obj->efile.sec_cnt = 0;
1239 zclose(obj->efile.fd);
1240 obj->efile.obj_buf = NULL;
1241 obj->efile.obj_buf_sz = 0;
1244 static int bpf_object__elf_init(struct bpf_object *obj)
1250 if (obj->efile.elf) {
1251 pr_warn("elf: init internal error\n");
1252 return -LIBBPF_ERRNO__LIBELF;
1255 if (obj->efile.obj_buf_sz > 0) {
1257 * obj_buf should have been validated by
1258 * bpf_object__open_buffer().
1260 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1262 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1263 if (obj->efile.fd < 0) {
1264 char errmsg[STRERR_BUFSIZE], *cp;
1267 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1268 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1272 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1276 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1277 err = -LIBBPF_ERRNO__LIBELF;
1281 obj->efile.elf = elf;
1283 if (elf_kind(elf) != ELF_K_ELF) {
1284 err = -LIBBPF_ERRNO__FORMAT;
1285 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1289 if (gelf_getclass(elf) != ELFCLASS64) {
1290 err = -LIBBPF_ERRNO__FORMAT;
1291 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1295 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1296 if (!obj->efile.ehdr) {
1297 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1298 err = -LIBBPF_ERRNO__FORMAT;
1302 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1303 pr_warn("elf: failed to get section names section index for %s: %s\n",
1304 obj->path, elf_errmsg(-1));
1305 err = -LIBBPF_ERRNO__FORMAT;
1309 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1310 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1311 pr_warn("elf: failed to get section names strings from %s: %s\n",
1312 obj->path, elf_errmsg(-1));
1313 err = -LIBBPF_ERRNO__FORMAT;
1317 /* Old LLVM set e_machine to EM_NONE */
1318 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1319 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1320 err = -LIBBPF_ERRNO__FORMAT;
1326 bpf_object__elf_finish(obj);
1330 static int bpf_object__check_endianness(struct bpf_object *obj)
1332 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1333 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1335 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1336 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1339 # error "Unrecognized __BYTE_ORDER__"
1341 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1342 return -LIBBPF_ERRNO__ENDIAN;
1346 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1348 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1349 * go over allowed ELF data section buffer
1351 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1352 pr_debug("license of %s is %s\n", obj->path, obj->license);
1357 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1361 if (size != sizeof(kver)) {
1362 pr_warn("invalid kver section in %s\n", obj->path);
1363 return -LIBBPF_ERRNO__FORMAT;
1365 memcpy(&kver, data, sizeof(kver));
1366 obj->kern_version = kver;
1367 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1371 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1373 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1374 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1379 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1389 scn = elf_sec_by_name(obj, name);
1390 data = elf_sec_data(obj, scn);
1392 ret = 0; /* found it */
1393 *size = data->d_size;
1396 return *size ? 0 : ret;
1399 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1401 Elf_Data *symbols = obj->efile.symbols;
1408 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1409 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1411 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL ||
1412 ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1415 sname = elf_sym_str(obj, sym->st_name);
1417 pr_warn("failed to get sym name string for var %s\n", name);
1420 if (strcmp(name, sname) == 0) {
1421 *off = sym->st_value;
1429 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1431 struct bpf_map *new_maps;
1435 if (obj->nr_maps < obj->maps_cap)
1436 return &obj->maps[obj->nr_maps++];
1438 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1439 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1441 pr_warn("alloc maps for object failed\n");
1442 return ERR_PTR(-ENOMEM);
1445 obj->maps_cap = new_cap;
1446 obj->maps = new_maps;
1448 /* zero out new maps */
1449 memset(obj->maps + obj->nr_maps, 0,
1450 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1452 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1453 * when failure (zclose won't close negative fd)).
1455 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1456 obj->maps[i].fd = -1;
1457 obj->maps[i].inner_map_fd = -1;
1460 return &obj->maps[obj->nr_maps++];
1463 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1465 long page_sz = sysconf(_SC_PAGE_SIZE);
1468 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1469 map_sz = roundup(map_sz, page_sz);
1473 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1475 char map_name[BPF_OBJ_NAME_LEN], *p;
1476 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1478 /* This is one of the more confusing parts of libbpf for various
1479 * reasons, some of which are historical. The original idea for naming
1480 * internal names was to include as much of BPF object name prefix as
1481 * possible, so that it can be distinguished from similar internal
1482 * maps of a different BPF object.
1483 * As an example, let's say we have bpf_object named 'my_object_name'
1484 * and internal map corresponding to '.rodata' ELF section. The final
1485 * map name advertised to user and to the kernel will be
1486 * 'my_objec.rodata', taking first 8 characters of object name and
1487 * entire 7 characters of '.rodata'.
1488 * Somewhat confusingly, if internal map ELF section name is shorter
1489 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1490 * for the suffix, even though we only have 4 actual characters, and
1491 * resulting map will be called 'my_objec.bss', not even using all 15
1492 * characters allowed by the kernel. Oh well, at least the truncated
1493 * object name is somewhat consistent in this case. But if the map
1494 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1495 * (8 chars) and thus will be left with only first 7 characters of the
1496 * object name ('my_obje'). Happy guessing, user, that the final map
1497 * name will be "my_obje.kconfig".
1498 * Now, with libbpf starting to support arbitrarily named .rodata.*
1499 * and .data.* data sections, it's possible that ELF section name is
1500 * longer than allowed 15 chars, so we now need to be careful to take
1501 * only up to 15 first characters of ELF name, taking no BPF object
1502 * name characters at all. So '.rodata.abracadabra' will result in
1503 * '.rodata.abracad' kernel and user-visible name.
1504 * We need to keep this convoluted logic intact for .data, .bss and
1505 * .rodata maps, but for new custom .data.custom and .rodata.custom
1506 * maps we use their ELF names as is, not prepending bpf_object name
1507 * in front. We still need to truncate them to 15 characters for the
1508 * kernel. Full name can be recovered for such maps by using DATASEC
1509 * BTF type associated with such map's value type, though.
1511 if (sfx_len >= BPF_OBJ_NAME_LEN)
1512 sfx_len = BPF_OBJ_NAME_LEN - 1;
1514 /* if there are two or more dots in map name, it's a custom dot map */
1515 if (strchr(real_name + 1, '.') != NULL)
1518 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1520 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1521 sfx_len, real_name);
1523 /* sanitise map name to characters allowed by kernel */
1524 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1525 if (!isalnum(*p) && *p != '_' && *p != '.')
1528 return strdup(map_name);
1532 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1533 const char *real_name, int sec_idx, void *data, size_t data_sz)
1535 struct bpf_map_def *def;
1536 struct bpf_map *map;
1539 map = bpf_object__add_map(obj);
1541 return PTR_ERR(map);
1543 map->libbpf_type = type;
1544 map->sec_idx = sec_idx;
1545 map->sec_offset = 0;
1546 map->real_name = strdup(real_name);
1547 map->name = internal_map_name(obj, real_name);
1548 if (!map->real_name || !map->name) {
1549 zfree(&map->real_name);
1555 def->type = BPF_MAP_TYPE_ARRAY;
1556 def->key_size = sizeof(int);
1557 def->value_size = data_sz;
1558 def->max_entries = 1;
1559 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1560 ? BPF_F_RDONLY_PROG : 0;
1561 def->map_flags |= BPF_F_MMAPABLE;
1563 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1564 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1566 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1567 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1568 if (map->mmaped == MAP_FAILED) {
1571 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1573 zfree(&map->real_name);
1579 memcpy(map->mmaped, data, data_sz);
1581 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1585 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1587 struct elf_sec_desc *sec_desc;
1588 const char *sec_name;
1589 int err = 0, sec_idx;
1592 * Populate obj->maps with libbpf internal maps.
1594 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1595 sec_desc = &obj->efile.secs[sec_idx];
1597 switch (sec_desc->sec_type) {
1599 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1600 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1602 sec_desc->data->d_buf,
1603 sec_desc->data->d_size);
1606 obj->has_rodata = true;
1607 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1608 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1610 sec_desc->data->d_buf,
1611 sec_desc->data->d_size);
1614 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1615 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1618 sec_desc->data->d_size);
1631 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1636 for (i = 0; i < obj->nr_extern; i++) {
1637 if (strcmp(obj->externs[i].name, name) == 0)
1638 return &obj->externs[i];
1643 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1646 switch (ext->kcfg.type) {
1649 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1653 *(bool *)ext_val = value == 'y' ? true : false;
1657 *(enum libbpf_tristate *)ext_val = TRI_YES;
1658 else if (value == 'm')
1659 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1660 else /* value == 'n' */
1661 *(enum libbpf_tristate *)ext_val = TRI_NO;
1664 *(char *)ext_val = value;
1670 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1678 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1683 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1684 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1688 len = strlen(value);
1689 if (value[len - 1] != '"') {
1690 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1697 if (len >= ext->kcfg.sz) {
1698 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1699 ext->name, value, len, ext->kcfg.sz - 1);
1700 len = ext->kcfg.sz - 1;
1702 memcpy(ext_val, value + 1, len);
1703 ext_val[len] = '\0';
1708 static int parse_u64(const char *value, __u64 *res)
1714 *res = strtoull(value, &value_end, 0);
1717 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1721 pr_warn("failed to parse '%s' as integer completely\n", value);
1727 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1729 int bit_sz = ext->kcfg.sz * 8;
1731 if (ext->kcfg.sz == 8)
1734 /* Validate that value stored in u64 fits in integer of `ext->sz`
1735 * bytes size without any loss of information. If the target integer
1736 * is signed, we rely on the following limits of integer type of
1737 * Y bits and subsequent transformation:
1739 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1740 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1741 * 0 <= X + 2^(Y-1) < 2^Y
1743 * For unsigned target integer, check that all the (64 - Y) bits are
1746 if (ext->kcfg.is_signed)
1747 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1749 return (v >> bit_sz) == 0;
1752 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1755 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1756 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1757 ext->name, (unsigned long long)value);
1760 if (!is_kcfg_value_in_range(ext, value)) {
1761 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1762 ext->name, (unsigned long long)value, ext->kcfg.sz);
1765 switch (ext->kcfg.sz) {
1766 case 1: *(__u8 *)ext_val = value; break;
1767 case 2: *(__u16 *)ext_val = value; break;
1768 case 4: *(__u32 *)ext_val = value; break;
1769 case 8: *(__u64 *)ext_val = value; break;
1777 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1778 char *buf, void *data)
1780 struct extern_desc *ext;
1786 if (!str_has_pfx(buf, "CONFIG_"))
1789 sep = strchr(buf, '=');
1791 pr_warn("failed to parse '%s': no separator\n", buf);
1795 /* Trim ending '\n' */
1797 if (buf[len - 1] == '\n')
1798 buf[len - 1] = '\0';
1799 /* Split on '=' and ensure that a value is present. */
1803 pr_warn("failed to parse '%s': no value\n", buf);
1807 ext = find_extern_by_name(obj, buf);
1808 if (!ext || ext->is_set)
1811 ext_val = data + ext->kcfg.data_off;
1815 case 'y': case 'n': case 'm':
1816 err = set_kcfg_value_tri(ext, ext_val, *value);
1819 err = set_kcfg_value_str(ext, ext_val, value);
1822 /* assume integer */
1823 err = parse_u64(value, &num);
1825 pr_warn("extern (kcfg) %s=%s should be integer\n",
1829 err = set_kcfg_value_num(ext, ext_val, num);
1834 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1838 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1846 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1849 else if (len >= PATH_MAX)
1850 return -ENAMETOOLONG;
1852 /* gzopen also accepts uncompressed files. */
1853 file = gzopen(buf, "r");
1855 file = gzopen("/proc/config.gz", "r");
1858 pr_warn("failed to open system Kconfig\n");
1862 while (gzgets(file, buf, sizeof(buf))) {
1863 err = bpf_object__process_kconfig_line(obj, buf, data);
1865 pr_warn("error parsing system Kconfig line '%s': %d\n",
1876 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1877 const char *config, void *data)
1883 file = fmemopen((void *)config, strlen(config), "r");
1886 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1890 while (fgets(buf, sizeof(buf), file)) {
1891 err = bpf_object__process_kconfig_line(obj, buf, data);
1893 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1903 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1905 struct extern_desc *last_ext = NULL, *ext;
1909 for (i = 0; i < obj->nr_extern; i++) {
1910 ext = &obj->externs[i];
1911 if (ext->type == EXT_KCFG)
1918 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1919 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1920 ".kconfig", obj->efile.symbols_shndx,
1925 obj->kconfig_map_idx = obj->nr_maps - 1;
1930 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1932 Elf_Data *symbols = obj->efile.symbols;
1933 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1934 Elf_Data *data = NULL;
1937 if (obj->efile.maps_shndx < 0)
1940 if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
1941 pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
1948 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1949 data = elf_sec_data(obj, scn);
1950 if (!scn || !data) {
1951 pr_warn("elf: failed to get legacy map definitions for %s\n",
1957 * Count number of maps. Each map has a name.
1958 * Array of maps is not supported: only the first element is
1961 * TODO: Detect array of map and report error.
1963 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
1964 for (i = 0; i < nr_syms; i++) {
1965 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
1967 if (sym->st_shndx != obj->efile.maps_shndx)
1969 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
1973 /* Assume equally sized map definitions */
1974 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1975 nr_maps, data->d_size, obj->path);
1977 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1978 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1982 map_def_sz = data->d_size / nr_maps;
1984 /* Fill obj->maps using data in "maps" section. */
1985 for (i = 0; i < nr_syms; i++) {
1986 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
1987 const char *map_name;
1988 struct bpf_map_def *def;
1989 struct bpf_map *map;
1991 if (sym->st_shndx != obj->efile.maps_shndx)
1993 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
1996 map = bpf_object__add_map(obj);
1998 return PTR_ERR(map);
2000 map_name = elf_sym_str(obj, sym->st_name);
2002 pr_warn("failed to get map #%d name sym string for obj %s\n",
2004 return -LIBBPF_ERRNO__FORMAT;
2007 pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
2009 if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
2010 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2014 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2015 map->sec_idx = sym->st_shndx;
2016 map->sec_offset = sym->st_value;
2017 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2018 map_name, map->sec_idx, map->sec_offset);
2019 if (sym->st_value + map_def_sz > data->d_size) {
2020 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2021 obj->path, map_name);
2025 map->name = strdup(map_name);
2027 pr_warn("map '%s': failed to alloc map name\n", map_name);
2030 pr_debug("map %d is \"%s\"\n", i, map->name);
2031 def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
2033 * If the definition of the map in the object file fits in
2034 * bpf_map_def, copy it. Any extra fields in our version
2035 * of bpf_map_def will default to zero as a result of the
2038 if (map_def_sz <= sizeof(struct bpf_map_def)) {
2039 memcpy(&map->def, def, map_def_sz);
2042 * Here the map structure being read is bigger than what
2043 * we expect, truncate if the excess bits are all zero.
2044 * If they are not zero, reject this map as
2049 for (b = ((char *)def) + sizeof(struct bpf_map_def);
2050 b < ((char *)def) + map_def_sz; b++) {
2052 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
2053 obj->path, map_name);
2058 memcpy(&map->def, def, sizeof(struct bpf_map_def));
2064 const struct btf_type *
2065 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2067 const struct btf_type *t = btf__type_by_id(btf, id);
2072 while (btf_is_mod(t) || btf_is_typedef(t)) {
2075 t = btf__type_by_id(btf, t->type);
2081 static const struct btf_type *
2082 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2084 const struct btf_type *t;
2086 t = skip_mods_and_typedefs(btf, id, NULL);
2090 t = skip_mods_and_typedefs(btf, t->type, res_id);
2092 return btf_is_func_proto(t) ? t : NULL;
2095 static const char *__btf_kind_str(__u16 kind)
2098 case BTF_KIND_UNKN: return "void";
2099 case BTF_KIND_INT: return "int";
2100 case BTF_KIND_PTR: return "ptr";
2101 case BTF_KIND_ARRAY: return "array";
2102 case BTF_KIND_STRUCT: return "struct";
2103 case BTF_KIND_UNION: return "union";
2104 case BTF_KIND_ENUM: return "enum";
2105 case BTF_KIND_FWD: return "fwd";
2106 case BTF_KIND_TYPEDEF: return "typedef";
2107 case BTF_KIND_VOLATILE: return "volatile";
2108 case BTF_KIND_CONST: return "const";
2109 case BTF_KIND_RESTRICT: return "restrict";
2110 case BTF_KIND_FUNC: return "func";
2111 case BTF_KIND_FUNC_PROTO: return "func_proto";
2112 case BTF_KIND_VAR: return "var";
2113 case BTF_KIND_DATASEC: return "datasec";
2114 case BTF_KIND_FLOAT: return "float";
2115 case BTF_KIND_DECL_TAG: return "decl_tag";
2116 case BTF_KIND_TYPE_TAG: return "type_tag";
2117 default: return "unknown";
2121 const char *btf_kind_str(const struct btf_type *t)
2123 return __btf_kind_str(btf_kind(t));
2127 * Fetch integer attribute of BTF map definition. Such attributes are
2128 * represented using a pointer to an array, in which dimensionality of array
2129 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2130 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2131 * type definition, while using only sizeof(void *) space in ELF data section.
2133 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2134 const struct btf_member *m, __u32 *res)
2136 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2137 const char *name = btf__name_by_offset(btf, m->name_off);
2138 const struct btf_array *arr_info;
2139 const struct btf_type *arr_t;
2141 if (!btf_is_ptr(t)) {
2142 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2143 map_name, name, btf_kind_str(t));
2147 arr_t = btf__type_by_id(btf, t->type);
2149 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2150 map_name, name, t->type);
2153 if (!btf_is_array(arr_t)) {
2154 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2155 map_name, name, btf_kind_str(arr_t));
2158 arr_info = btf_array(arr_t);
2159 *res = arr_info->nelems;
2163 static int build_map_pin_path(struct bpf_map *map, const char *path)
2169 path = "/sys/fs/bpf";
2171 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2174 else if (len >= PATH_MAX)
2175 return -ENAMETOOLONG;
2177 return bpf_map__set_pin_path(map, buf);
2180 int parse_btf_map_def(const char *map_name, struct btf *btf,
2181 const struct btf_type *def_t, bool strict,
2182 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2184 const struct btf_type *t;
2185 const struct btf_member *m;
2186 bool is_inner = inner_def == NULL;
2189 vlen = btf_vlen(def_t);
2190 m = btf_members(def_t);
2191 for (i = 0; i < vlen; i++, m++) {
2192 const char *name = btf__name_by_offset(btf, m->name_off);
2195 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2198 if (strcmp(name, "type") == 0) {
2199 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2201 map_def->parts |= MAP_DEF_MAP_TYPE;
2202 } else if (strcmp(name, "max_entries") == 0) {
2203 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2205 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2206 } else if (strcmp(name, "map_flags") == 0) {
2207 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2209 map_def->parts |= MAP_DEF_MAP_FLAGS;
2210 } else if (strcmp(name, "numa_node") == 0) {
2211 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2213 map_def->parts |= MAP_DEF_NUMA_NODE;
2214 } else if (strcmp(name, "key_size") == 0) {
2217 if (!get_map_field_int(map_name, btf, m, &sz))
2219 if (map_def->key_size && map_def->key_size != sz) {
2220 pr_warn("map '%s': conflicting key size %u != %u.\n",
2221 map_name, map_def->key_size, sz);
2224 map_def->key_size = sz;
2225 map_def->parts |= MAP_DEF_KEY_SIZE;
2226 } else if (strcmp(name, "key") == 0) {
2229 t = btf__type_by_id(btf, m->type);
2231 pr_warn("map '%s': key type [%d] not found.\n",
2235 if (!btf_is_ptr(t)) {
2236 pr_warn("map '%s': key spec is not PTR: %s.\n",
2237 map_name, btf_kind_str(t));
2240 sz = btf__resolve_size(btf, t->type);
2242 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2243 map_name, t->type, (ssize_t)sz);
2246 if (map_def->key_size && map_def->key_size != sz) {
2247 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2248 map_name, map_def->key_size, (ssize_t)sz);
2251 map_def->key_size = sz;
2252 map_def->key_type_id = t->type;
2253 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2254 } else if (strcmp(name, "value_size") == 0) {
2257 if (!get_map_field_int(map_name, btf, m, &sz))
2259 if (map_def->value_size && map_def->value_size != sz) {
2260 pr_warn("map '%s': conflicting value size %u != %u.\n",
2261 map_name, map_def->value_size, sz);
2264 map_def->value_size = sz;
2265 map_def->parts |= MAP_DEF_VALUE_SIZE;
2266 } else if (strcmp(name, "value") == 0) {
2269 t = btf__type_by_id(btf, m->type);
2271 pr_warn("map '%s': value type [%d] not found.\n",
2275 if (!btf_is_ptr(t)) {
2276 pr_warn("map '%s': value spec is not PTR: %s.\n",
2277 map_name, btf_kind_str(t));
2280 sz = btf__resolve_size(btf, t->type);
2282 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2283 map_name, t->type, (ssize_t)sz);
2286 if (map_def->value_size && map_def->value_size != sz) {
2287 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2288 map_name, map_def->value_size, (ssize_t)sz);
2291 map_def->value_size = sz;
2292 map_def->value_type_id = t->type;
2293 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2295 else if (strcmp(name, "values") == 0) {
2296 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2297 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2298 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2299 char inner_map_name[128];
2303 pr_warn("map '%s': multi-level inner maps not supported.\n",
2307 if (i != vlen - 1) {
2308 pr_warn("map '%s': '%s' member should be last.\n",
2312 if (!is_map_in_map && !is_prog_array) {
2313 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2317 if (map_def->value_size && map_def->value_size != 4) {
2318 pr_warn("map '%s': conflicting value size %u != 4.\n",
2319 map_name, map_def->value_size);
2322 map_def->value_size = 4;
2323 t = btf__type_by_id(btf, m->type);
2325 pr_warn("map '%s': %s type [%d] not found.\n",
2326 map_name, desc, m->type);
2329 if (!btf_is_array(t) || btf_array(t)->nelems) {
2330 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2334 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2335 if (!btf_is_ptr(t)) {
2336 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2337 map_name, desc, btf_kind_str(t));
2340 t = skip_mods_and_typedefs(btf, t->type, NULL);
2341 if (is_prog_array) {
2342 if (!btf_is_func_proto(t)) {
2343 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2344 map_name, btf_kind_str(t));
2349 if (!btf_is_struct(t)) {
2350 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2351 map_name, btf_kind_str(t));
2355 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2356 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2360 map_def->parts |= MAP_DEF_INNER_MAP;
2361 } else if (strcmp(name, "pinning") == 0) {
2365 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2368 if (!get_map_field_int(map_name, btf, m, &val))
2370 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2371 pr_warn("map '%s': invalid pinning value %u.\n",
2375 map_def->pinning = val;
2376 map_def->parts |= MAP_DEF_PINNING;
2377 } else if (strcmp(name, "map_extra") == 0) {
2380 if (!get_map_field_int(map_name, btf, m, &map_extra))
2382 map_def->map_extra = map_extra;
2383 map_def->parts |= MAP_DEF_MAP_EXTRA;
2386 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2389 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2393 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2394 pr_warn("map '%s': map type isn't specified.\n", map_name);
2401 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2403 map->def.type = def->map_type;
2404 map->def.key_size = def->key_size;
2405 map->def.value_size = def->value_size;
2406 map->def.max_entries = def->max_entries;
2407 map->def.map_flags = def->map_flags;
2408 map->map_extra = def->map_extra;
2410 map->numa_node = def->numa_node;
2411 map->btf_key_type_id = def->key_type_id;
2412 map->btf_value_type_id = def->value_type_id;
2414 if (def->parts & MAP_DEF_MAP_TYPE)
2415 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2417 if (def->parts & MAP_DEF_KEY_TYPE)
2418 pr_debug("map '%s': found key [%u], sz = %u.\n",
2419 map->name, def->key_type_id, def->key_size);
2420 else if (def->parts & MAP_DEF_KEY_SIZE)
2421 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2423 if (def->parts & MAP_DEF_VALUE_TYPE)
2424 pr_debug("map '%s': found value [%u], sz = %u.\n",
2425 map->name, def->value_type_id, def->value_size);
2426 else if (def->parts & MAP_DEF_VALUE_SIZE)
2427 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2429 if (def->parts & MAP_DEF_MAX_ENTRIES)
2430 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2431 if (def->parts & MAP_DEF_MAP_FLAGS)
2432 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2433 if (def->parts & MAP_DEF_MAP_EXTRA)
2434 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2435 (unsigned long long)def->map_extra);
2436 if (def->parts & MAP_DEF_PINNING)
2437 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2438 if (def->parts & MAP_DEF_NUMA_NODE)
2439 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2441 if (def->parts & MAP_DEF_INNER_MAP)
2442 pr_debug("map '%s': found inner map definition.\n", map->name);
2445 static const char *btf_var_linkage_str(__u32 linkage)
2448 case BTF_VAR_STATIC: return "static";
2449 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2450 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2451 default: return "unknown";
2455 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2456 const struct btf_type *sec,
2457 int var_idx, int sec_idx,
2458 const Elf_Data *data, bool strict,
2459 const char *pin_root_path)
2461 struct btf_map_def map_def = {}, inner_def = {};
2462 const struct btf_type *var, *def;
2463 const struct btf_var_secinfo *vi;
2464 const struct btf_var *var_extra;
2465 const char *map_name;
2466 struct bpf_map *map;
2469 vi = btf_var_secinfos(sec) + var_idx;
2470 var = btf__type_by_id(obj->btf, vi->type);
2471 var_extra = btf_var(var);
2472 map_name = btf__name_by_offset(obj->btf, var->name_off);
2474 if (map_name == NULL || map_name[0] == '\0') {
2475 pr_warn("map #%d: empty name.\n", var_idx);
2478 if ((__u64)vi->offset + vi->size > data->d_size) {
2479 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2482 if (!btf_is_var(var)) {
2483 pr_warn("map '%s': unexpected var kind %s.\n",
2484 map_name, btf_kind_str(var));
2487 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2488 pr_warn("map '%s': unsupported map linkage %s.\n",
2489 map_name, btf_var_linkage_str(var_extra->linkage));
2493 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2494 if (!btf_is_struct(def)) {
2495 pr_warn("map '%s': unexpected def kind %s.\n",
2496 map_name, btf_kind_str(var));
2499 if (def->size > vi->size) {
2500 pr_warn("map '%s': invalid def size.\n", map_name);
2504 map = bpf_object__add_map(obj);
2506 return PTR_ERR(map);
2507 map->name = strdup(map_name);
2509 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2512 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2513 map->def.type = BPF_MAP_TYPE_UNSPEC;
2514 map->sec_idx = sec_idx;
2515 map->sec_offset = vi->offset;
2516 map->btf_var_idx = var_idx;
2517 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2518 map_name, map->sec_idx, map->sec_offset);
2520 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2524 fill_map_from_def(map, &map_def);
2526 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2527 err = build_map_pin_path(map, pin_root_path);
2529 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2534 if (map_def.parts & MAP_DEF_INNER_MAP) {
2535 map->inner_map = calloc(1, sizeof(*map->inner_map));
2536 if (!map->inner_map)
2538 map->inner_map->fd = -1;
2539 map->inner_map->sec_idx = sec_idx;
2540 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2541 if (!map->inner_map->name)
2543 sprintf(map->inner_map->name, "%s.inner", map_name);
2545 fill_map_from_def(map->inner_map, &inner_def);
2551 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2552 const char *pin_root_path)
2554 const struct btf_type *sec = NULL;
2555 int nr_types, i, vlen, err;
2556 const struct btf_type *t;
2561 if (obj->efile.btf_maps_shndx < 0)
2564 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2565 data = elf_sec_data(obj, scn);
2566 if (!scn || !data) {
2567 pr_warn("elf: failed to get %s map definitions for %s\n",
2568 MAPS_ELF_SEC, obj->path);
2572 nr_types = btf__type_cnt(obj->btf);
2573 for (i = 1; i < nr_types; i++) {
2574 t = btf__type_by_id(obj->btf, i);
2575 if (!btf_is_datasec(t))
2577 name = btf__name_by_offset(obj->btf, t->name_off);
2578 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2580 obj->efile.btf_maps_sec_btf_id = i;
2586 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2590 vlen = btf_vlen(sec);
2591 for (i = 0; i < vlen; i++) {
2592 err = bpf_object__init_user_btf_map(obj, sec, i,
2593 obj->efile.btf_maps_shndx,
2603 static int bpf_object__init_maps(struct bpf_object *obj,
2604 const struct bpf_object_open_opts *opts)
2606 const char *pin_root_path;
2610 strict = !OPTS_GET(opts, relaxed_maps, false);
2611 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2613 err = bpf_object__init_user_maps(obj, strict);
2614 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2615 err = err ?: bpf_object__init_global_data_maps(obj);
2616 err = err ?: bpf_object__init_kconfig_map(obj);
2617 err = err ?: bpf_object__init_struct_ops_maps(obj);
2622 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2626 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2630 return sh->sh_flags & SHF_EXECINSTR;
2633 static bool btf_needs_sanitization(struct bpf_object *obj)
2635 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2636 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2637 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2638 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2639 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2640 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2642 return !has_func || !has_datasec || !has_func_global || !has_float ||
2643 !has_decl_tag || !has_type_tag;
2646 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2648 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2649 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2650 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2651 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2652 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2653 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2657 for (i = 1; i < btf__type_cnt(btf); i++) {
2658 t = (struct btf_type *)btf__type_by_id(btf, i);
2660 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2661 /* replace VAR/DECL_TAG with INT */
2662 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2664 * using size = 1 is the safest choice, 4 will be too
2665 * big and cause kernel BTF validation failure if
2666 * original variable took less than 4 bytes
2669 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2670 } else if (!has_datasec && btf_is_datasec(t)) {
2671 /* replace DATASEC with STRUCT */
2672 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2673 struct btf_member *m = btf_members(t);
2674 struct btf_type *vt;
2677 name = (char *)btf__name_by_offset(btf, t->name_off);
2685 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2686 for (j = 0; j < vlen; j++, v++, m++) {
2687 /* order of field assignments is important */
2688 m->offset = v->offset * 8;
2690 /* preserve variable name as member name */
2691 vt = (void *)btf__type_by_id(btf, v->type);
2692 m->name_off = vt->name_off;
2694 } else if (!has_func && btf_is_func_proto(t)) {
2695 /* replace FUNC_PROTO with ENUM */
2697 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2698 t->size = sizeof(__u32); /* kernel enforced */
2699 } else if (!has_func && btf_is_func(t)) {
2700 /* replace FUNC with TYPEDEF */
2701 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2702 } else if (!has_func_global && btf_is_func(t)) {
2703 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2704 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2705 } else if (!has_float && btf_is_float(t)) {
2706 /* replace FLOAT with an equally-sized empty STRUCT;
2707 * since C compilers do not accept e.g. "float" as a
2708 * valid struct name, make it anonymous
2711 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2712 } else if (!has_type_tag && btf_is_type_tag(t)) {
2713 /* replace TYPE_TAG with a CONST */
2715 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2720 static bool libbpf_needs_btf(const struct bpf_object *obj)
2722 return obj->efile.btf_maps_shndx >= 0 ||
2723 obj->efile.st_ops_shndx >= 0 ||
2727 static bool kernel_needs_btf(const struct bpf_object *obj)
2729 return obj->efile.st_ops_shndx >= 0;
2732 static int bpf_object__init_btf(struct bpf_object *obj,
2734 Elf_Data *btf_ext_data)
2739 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2740 err = libbpf_get_error(obj->btf);
2743 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2746 /* enforce 8-byte pointers for BPF-targeted BTFs */
2747 btf__set_pointer_size(obj->btf, 8);
2751 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2752 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2755 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2756 err = libbpf_get_error(obj->btf_ext);
2758 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2759 BTF_EXT_ELF_SEC, err);
2760 obj->btf_ext = NULL;
2765 if (err && libbpf_needs_btf(obj)) {
2766 pr_warn("BTF is required, but is missing or corrupted.\n");
2772 static int compare_vsi_off(const void *_a, const void *_b)
2774 const struct btf_var_secinfo *a = _a;
2775 const struct btf_var_secinfo *b = _b;
2777 return a->offset - b->offset;
2780 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2783 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
2784 const char *name = btf__name_by_offset(btf, t->name_off);
2785 const struct btf_type *t_var;
2786 struct btf_var_secinfo *vsi;
2787 const struct btf_var *var;
2791 pr_debug("No name found in string section for DATASEC kind.\n");
2795 /* .extern datasec size and var offsets were set correctly during
2796 * extern collection step, so just skip straight to sorting variables
2801 ret = find_elf_sec_sz(obj, name, &size);
2802 if (ret || !size || (t->size && t->size != size)) {
2803 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2809 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2810 t_var = btf__type_by_id(btf, vsi->type);
2811 if (!t_var || !btf_is_var(t_var)) {
2812 pr_debug("Non-VAR type seen in section %s\n", name);
2816 var = btf_var(t_var);
2817 if (var->linkage == BTF_VAR_STATIC)
2820 name = btf__name_by_offset(btf, t_var->name_off);
2822 pr_debug("No name found in string section for VAR kind\n");
2826 ret = find_elf_var_offset(obj, name, &off);
2828 pr_debug("No offset found in symbol table for VAR %s\n",
2837 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2841 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2844 __u32 i, n = btf__type_cnt(btf);
2846 for (i = 1; i < n; i++) {
2847 struct btf_type *t = btf_type_by_id(btf, i);
2849 /* Loader needs to fix up some of the things compiler
2850 * couldn't get its hands on while emitting BTF. This
2851 * is section size and global variable offset. We use
2852 * the info from the ELF itself for this purpose.
2854 if (btf_is_datasec(t)) {
2855 err = btf_fixup_datasec(obj, btf, t);
2861 return libbpf_err(err);
2864 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
2866 return btf_finalize_data(obj, btf);
2869 static int bpf_object__finalize_btf(struct bpf_object *obj)
2876 err = btf_finalize_data(obj, obj->btf);
2878 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2885 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2887 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2888 prog->type == BPF_PROG_TYPE_LSM)
2891 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2892 * also need vmlinux BTF
2894 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2900 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2902 struct bpf_program *prog;
2905 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2908 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2911 /* Support for typed ksyms needs kernel BTF */
2912 for (i = 0; i < obj->nr_extern; i++) {
2913 const struct extern_desc *ext;
2915 ext = &obj->externs[i];
2916 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2920 bpf_object__for_each_program(prog, obj) {
2923 if (prog_needs_vmlinux_btf(prog))
2930 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2934 /* btf_vmlinux could be loaded earlier */
2935 if (obj->btf_vmlinux || obj->gen_loader)
2938 if (!force && !obj_needs_vmlinux_btf(obj))
2941 obj->btf_vmlinux = btf__load_vmlinux_btf();
2942 err = libbpf_get_error(obj->btf_vmlinux);
2944 pr_warn("Error loading vmlinux BTF: %d\n", err);
2945 obj->btf_vmlinux = NULL;
2951 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2953 struct btf *kern_btf = obj->btf;
2954 bool btf_mandatory, sanitize;
2960 if (!kernel_supports(obj, FEAT_BTF)) {
2961 if (kernel_needs_btf(obj)) {
2965 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2969 /* Even though some subprogs are global/weak, user might prefer more
2970 * permissive BPF verification process that BPF verifier performs for
2971 * static functions, taking into account more context from the caller
2972 * functions. In such case, they need to mark such subprogs with
2973 * __attribute__((visibility("hidden"))) and libbpf will adjust
2974 * corresponding FUNC BTF type to be marked as static and trigger more
2975 * involved BPF verification process.
2977 for (i = 0; i < obj->nr_programs; i++) {
2978 struct bpf_program *prog = &obj->programs[i];
2983 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2986 n = btf__type_cnt(obj->btf);
2987 for (j = 1; j < n; j++) {
2988 t = btf_type_by_id(obj->btf, j);
2989 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2992 name = btf__str_by_offset(obj->btf, t->name_off);
2993 if (strcmp(name, prog->name) != 0)
2996 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3001 sanitize = btf_needs_sanitization(obj);
3003 const void *raw_data;
3006 /* clone BTF to sanitize a copy and leave the original intact */
3007 raw_data = btf__raw_data(obj->btf, &sz);
3008 kern_btf = btf__new(raw_data, sz);
3009 err = libbpf_get_error(kern_btf);
3013 /* enforce 8-byte pointers for BPF-targeted BTFs */
3014 btf__set_pointer_size(obj->btf, 8);
3015 bpf_object__sanitize_btf(obj, kern_btf);
3018 if (obj->gen_loader) {
3020 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3024 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3025 /* Pretend to have valid FD to pass various fd >= 0 checks.
3026 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3028 btf__set_fd(kern_btf, 0);
3030 /* currently BPF_BTF_LOAD only supports log_level 1 */
3031 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3032 obj->log_level ? 1 : 0);
3036 /* move fd to libbpf's BTF */
3037 btf__set_fd(obj->btf, btf__fd(kern_btf));
3038 btf__set_fd(kern_btf, -1);
3040 btf__free(kern_btf);
3044 btf_mandatory = kernel_needs_btf(obj);
3045 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3046 btf_mandatory ? "BTF is mandatory, can't proceed."
3047 : "BTF is optional, ignoring.");
3054 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3058 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3060 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3061 off, obj->path, elf_errmsg(-1));
3068 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3072 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3074 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3075 off, obj->path, elf_errmsg(-1));
3082 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3086 scn = elf_getscn(obj->efile.elf, idx);
3088 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3089 idx, obj->path, elf_errmsg(-1));
3095 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3097 Elf_Scn *scn = NULL;
3098 Elf *elf = obj->efile.elf;
3099 const char *sec_name;
3101 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3102 sec_name = elf_sec_name(obj, scn);
3106 if (strcmp(sec_name, name) != 0)
3114 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3121 shdr = elf64_getshdr(scn);
3123 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3124 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3131 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3139 sh = elf_sec_hdr(obj, scn);
3143 name = elf_sec_str(obj, sh->sh_name);
3145 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3146 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3153 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3160 data = elf_getdata(scn, 0);
3162 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3163 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3164 obj->path, elf_errmsg(-1));
3171 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3173 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3176 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3179 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3181 if (idx >= data->d_size / sizeof(Elf64_Rel))
3184 return (Elf64_Rel *)data->d_buf + idx;
3187 static bool is_sec_name_dwarf(const char *name)
3189 /* approximation, but the actual list is too long */
3190 return str_has_pfx(name, ".debug_");
3193 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3195 /* no special handling of .strtab */
3196 if (hdr->sh_type == SHT_STRTAB)
3199 /* ignore .llvm_addrsig section as well */
3200 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3203 /* no subprograms will lead to an empty .text section, ignore it */
3204 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3205 strcmp(name, ".text") == 0)
3208 /* DWARF sections */
3209 if (is_sec_name_dwarf(name))
3212 if (str_has_pfx(name, ".rel")) {
3213 name += sizeof(".rel") - 1;
3214 /* DWARF section relocations */
3215 if (is_sec_name_dwarf(name))
3218 /* .BTF and .BTF.ext don't need relocations */
3219 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3220 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3227 static int cmp_progs(const void *_a, const void *_b)
3229 const struct bpf_program *a = _a;
3230 const struct bpf_program *b = _b;
3232 if (a->sec_idx != b->sec_idx)
3233 return a->sec_idx < b->sec_idx ? -1 : 1;
3235 /* sec_insn_off can't be the same within the section */
3236 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3239 static int bpf_object__elf_collect(struct bpf_object *obj)
3241 struct elf_sec_desc *sec_desc;
3242 Elf *elf = obj->efile.elf;
3243 Elf_Data *btf_ext_data = NULL;
3244 Elf_Data *btf_data = NULL;
3245 int idx = 0, err = 0;
3251 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3252 * section. e_shnum does include sec #0, so e_shnum is the necessary
3253 * size of an array to keep all the sections.
3255 obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3256 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3257 if (!obj->efile.secs)
3260 /* a bunch of ELF parsing functionality depends on processing symbols,
3261 * so do the first pass and find the symbol table
3264 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3265 sh = elf_sec_hdr(obj, scn);
3267 return -LIBBPF_ERRNO__FORMAT;
3269 if (sh->sh_type == SHT_SYMTAB) {
3270 if (obj->efile.symbols) {
3271 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3272 return -LIBBPF_ERRNO__FORMAT;
3275 data = elf_sec_data(obj, scn);
3277 return -LIBBPF_ERRNO__FORMAT;
3279 idx = elf_ndxscn(scn);
3281 obj->efile.symbols = data;
3282 obj->efile.symbols_shndx = idx;
3283 obj->efile.strtabidx = sh->sh_link;
3287 if (!obj->efile.symbols) {
3288 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3294 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3295 idx = elf_ndxscn(scn);
3296 sec_desc = &obj->efile.secs[idx];
3298 sh = elf_sec_hdr(obj, scn);
3300 return -LIBBPF_ERRNO__FORMAT;
3302 name = elf_sec_str(obj, sh->sh_name);
3304 return -LIBBPF_ERRNO__FORMAT;
3306 if (ignore_elf_section(sh, name))
3309 data = elf_sec_data(obj, scn);
3311 return -LIBBPF_ERRNO__FORMAT;
3313 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3314 idx, name, (unsigned long)data->d_size,
3315 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3318 if (strcmp(name, "license") == 0) {
3319 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3322 } else if (strcmp(name, "version") == 0) {
3323 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3326 } else if (strcmp(name, "maps") == 0) {
3327 obj->efile.maps_shndx = idx;
3328 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3329 obj->efile.btf_maps_shndx = idx;
3330 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3331 if (sh->sh_type != SHT_PROGBITS)
3332 return -LIBBPF_ERRNO__FORMAT;
3334 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3335 if (sh->sh_type != SHT_PROGBITS)
3336 return -LIBBPF_ERRNO__FORMAT;
3337 btf_ext_data = data;
3338 } else if (sh->sh_type == SHT_SYMTAB) {
3339 /* already processed during the first pass above */
3340 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3341 if (sh->sh_flags & SHF_EXECINSTR) {
3342 if (strcmp(name, ".text") == 0)
3343 obj->efile.text_shndx = idx;
3344 err = bpf_object__add_programs(obj, data, name, idx);
3347 } else if (strcmp(name, DATA_SEC) == 0 ||
3348 str_has_pfx(name, DATA_SEC ".")) {
3349 sec_desc->sec_type = SEC_DATA;
3350 sec_desc->shdr = sh;
3351 sec_desc->data = data;
3352 } else if (strcmp(name, RODATA_SEC) == 0 ||
3353 str_has_pfx(name, RODATA_SEC ".")) {
3354 sec_desc->sec_type = SEC_RODATA;
3355 sec_desc->shdr = sh;
3356 sec_desc->data = data;
3357 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3358 obj->efile.st_ops_data = data;
3359 obj->efile.st_ops_shndx = idx;
3361 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3364 } else if (sh->sh_type == SHT_REL) {
3365 int targ_sec_idx = sh->sh_info; /* points to other section */
3367 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3368 targ_sec_idx >= obj->efile.sec_cnt)
3369 return -LIBBPF_ERRNO__FORMAT;
3371 /* Only do relo for section with exec instructions */
3372 if (!section_have_execinstr(obj, targ_sec_idx) &&
3373 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3374 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3375 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3376 idx, name, targ_sec_idx,
3377 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3381 sec_desc->sec_type = SEC_RELO;
3382 sec_desc->shdr = sh;
3383 sec_desc->data = data;
3384 } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3385 sec_desc->sec_type = SEC_BSS;
3386 sec_desc->shdr = sh;
3387 sec_desc->data = data;
3389 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3390 (size_t)sh->sh_size);
3394 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3395 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3396 return -LIBBPF_ERRNO__FORMAT;
3399 /* sort BPF programs by section name and in-section instruction offset
3400 * for faster search */
3401 if (obj->nr_programs)
3402 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3404 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3407 static bool sym_is_extern(const Elf64_Sym *sym)
3409 int bind = ELF64_ST_BIND(sym->st_info);
3410 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3411 return sym->st_shndx == SHN_UNDEF &&
3412 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3413 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3416 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3418 int bind = ELF64_ST_BIND(sym->st_info);
3419 int type = ELF64_ST_TYPE(sym->st_info);
3421 /* in .text section */
3422 if (sym->st_shndx != text_shndx)
3425 /* local function */
3426 if (bind == STB_LOCAL && type == STT_SECTION)
3429 /* global function */
3430 return bind == STB_GLOBAL && type == STT_FUNC;
3433 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3435 const struct btf_type *t;
3442 n = btf__type_cnt(btf);
3443 for (i = 1; i < n; i++) {
3444 t = btf__type_by_id(btf, i);
3446 if (!btf_is_var(t) && !btf_is_func(t))
3449 tname = btf__name_by_offset(btf, t->name_off);
3450 if (strcmp(tname, ext_name))
3453 if (btf_is_var(t) &&
3454 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3457 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3466 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3467 const struct btf_var_secinfo *vs;
3468 const struct btf_type *t;
3474 n = btf__type_cnt(btf);
3475 for (i = 1; i < n; i++) {
3476 t = btf__type_by_id(btf, i);
3478 if (!btf_is_datasec(t))
3481 vs = btf_var_secinfos(t);
3482 for (j = 0; j < btf_vlen(t); j++, vs++) {
3483 if (vs->type == ext_btf_id)
3491 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3494 const struct btf_type *t;
3497 t = skip_mods_and_typedefs(btf, id, NULL);
3498 name = btf__name_by_offset(btf, t->name_off);
3502 switch (btf_kind(t)) {
3503 case BTF_KIND_INT: {
3504 int enc = btf_int_encoding(t);
3506 if (enc & BTF_INT_BOOL)
3507 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3509 *is_signed = enc & BTF_INT_SIGNED;
3512 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3513 return KCFG_UNKNOWN;
3518 return KCFG_UNKNOWN;
3519 if (strcmp(name, "libbpf_tristate"))
3520 return KCFG_UNKNOWN;
3521 return KCFG_TRISTATE;
3522 case BTF_KIND_ARRAY:
3523 if (btf_array(t)->nelems == 0)
3524 return KCFG_UNKNOWN;
3525 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3526 return KCFG_UNKNOWN;
3527 return KCFG_CHAR_ARR;
3529 return KCFG_UNKNOWN;
3533 static int cmp_externs(const void *_a, const void *_b)
3535 const struct extern_desc *a = _a;
3536 const struct extern_desc *b = _b;
3538 if (a->type != b->type)
3539 return a->type < b->type ? -1 : 1;
3541 if (a->type == EXT_KCFG) {
3542 /* descending order by alignment requirements */
3543 if (a->kcfg.align != b->kcfg.align)
3544 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3545 /* ascending order by size, within same alignment class */
3546 if (a->kcfg.sz != b->kcfg.sz)
3547 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3550 /* resolve ties by name */
3551 return strcmp(a->name, b->name);
3554 static int find_int_btf_id(const struct btf *btf)
3556 const struct btf_type *t;
3559 n = btf__type_cnt(btf);
3560 for (i = 1; i < n; i++) {
3561 t = btf__type_by_id(btf, i);
3563 if (btf_is_int(t) && btf_int_bits(t) == 32)
3570 static int add_dummy_ksym_var(struct btf *btf)
3572 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3573 const struct btf_var_secinfo *vs;
3574 const struct btf_type *sec;
3579 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3584 sec = btf__type_by_id(btf, sec_btf_id);
3585 vs = btf_var_secinfos(sec);
3586 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3587 const struct btf_type *vt;
3589 vt = btf__type_by_id(btf, vs->type);
3590 if (btf_is_func(vt))
3594 /* No func in ksyms sec. No need to add dummy var. */
3595 if (i == btf_vlen(sec))
3598 int_btf_id = find_int_btf_id(btf);
3599 dummy_var_btf_id = btf__add_var(btf,
3601 BTF_VAR_GLOBAL_ALLOCATED,
3603 if (dummy_var_btf_id < 0)
3604 pr_warn("cannot create a dummy_ksym var\n");
3606 return dummy_var_btf_id;
3609 static int bpf_object__collect_externs(struct bpf_object *obj)
3611 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3612 const struct btf_type *t;
3613 struct extern_desc *ext;
3614 int i, n, off, dummy_var_btf_id;
3615 const char *ext_name, *sec_name;
3619 if (!obj->efile.symbols)
3622 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3623 sh = elf_sec_hdr(obj, scn);
3624 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3625 return -LIBBPF_ERRNO__FORMAT;
3627 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3628 if (dummy_var_btf_id < 0)
3629 return dummy_var_btf_id;
3631 n = sh->sh_size / sh->sh_entsize;
3632 pr_debug("looking for externs among %d symbols...\n", n);
3634 for (i = 0; i < n; i++) {
3635 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3638 return -LIBBPF_ERRNO__FORMAT;
3639 if (!sym_is_extern(sym))
3641 ext_name = elf_sym_str(obj, sym->st_name);
3642 if (!ext_name || !ext_name[0])
3646 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3650 ext = &ext[obj->nr_extern];
3651 memset(ext, 0, sizeof(*ext));
3654 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3655 if (ext->btf_id <= 0) {
3656 pr_warn("failed to find BTF for extern '%s': %d\n",
3657 ext_name, ext->btf_id);
3660 t = btf__type_by_id(obj->btf, ext->btf_id);
3661 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3663 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3665 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3666 if (ext->sec_btf_id <= 0) {
3667 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3668 ext_name, ext->btf_id, ext->sec_btf_id);
3669 return ext->sec_btf_id;
3671 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3672 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3674 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3675 if (btf_is_func(t)) {
3676 pr_warn("extern function %s is unsupported under %s section\n",
3677 ext->name, KCONFIG_SEC);
3681 ext->type = EXT_KCFG;
3682 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3683 if (ext->kcfg.sz <= 0) {
3684 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3685 ext_name, ext->kcfg.sz);
3686 return ext->kcfg.sz;
3688 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3689 if (ext->kcfg.align <= 0) {
3690 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3691 ext_name, ext->kcfg.align);
3694 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3695 &ext->kcfg.is_signed);
3696 if (ext->kcfg.type == KCFG_UNKNOWN) {
3697 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3700 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3702 ext->type = EXT_KSYM;
3703 skip_mods_and_typedefs(obj->btf, t->type,
3704 &ext->ksym.type_id);
3706 pr_warn("unrecognized extern section '%s'\n", sec_name);
3710 pr_debug("collected %d externs total\n", obj->nr_extern);
3712 if (!obj->nr_extern)
3715 /* sort externs by type, for kcfg ones also by (align, size, name) */
3716 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3718 /* for .ksyms section, we need to turn all externs into allocated
3719 * variables in BTF to pass kernel verification; we do this by
3720 * pretending that each extern is a 8-byte variable
3723 /* find existing 4-byte integer type in BTF to use for fake
3724 * extern variables in DATASEC
3726 int int_btf_id = find_int_btf_id(obj->btf);
3727 /* For extern function, a dummy_var added earlier
3728 * will be used to replace the vs->type and
3729 * its name string will be used to refill
3730 * the missing param's name.
3732 const struct btf_type *dummy_var;
3734 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3735 for (i = 0; i < obj->nr_extern; i++) {
3736 ext = &obj->externs[i];
3737 if (ext->type != EXT_KSYM)
3739 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3740 i, ext->sym_idx, ext->name);
3745 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3746 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3747 struct btf_type *vt;
3749 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3750 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3751 ext = find_extern_by_name(obj, ext_name);
3753 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3754 btf_kind_str(vt), ext_name);
3757 if (btf_is_func(vt)) {
3758 const struct btf_type *func_proto;
3759 struct btf_param *param;
3762 func_proto = btf__type_by_id(obj->btf,
3764 param = btf_params(func_proto);
3765 /* Reuse the dummy_var string if the
3766 * func proto does not have param name.
3768 for (j = 0; j < btf_vlen(func_proto); j++)
3769 if (param[j].type && !param[j].name_off)
3771 dummy_var->name_off;
3772 vs->type = dummy_var_btf_id;
3773 vt->info &= ~0xffff;
3774 vt->info |= BTF_FUNC_GLOBAL;
3776 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3777 vt->type = int_btf_id;
3780 vs->size = sizeof(int);
3787 /* for kcfg externs calculate their offsets within a .kconfig map */
3789 for (i = 0; i < obj->nr_extern; i++) {
3790 ext = &obj->externs[i];
3791 if (ext->type != EXT_KCFG)
3794 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3795 off = ext->kcfg.data_off + ext->kcfg.sz;
3796 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3797 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3801 for (i = 0; i < n; i++) {
3802 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3804 t = btf__type_by_id(obj->btf, vs->type);
3805 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3806 ext = find_extern_by_name(obj, ext_name);
3808 pr_warn("failed to find extern definition for BTF var '%s'\n",
3812 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3813 vs->offset = ext->kcfg.data_off;
3819 struct bpf_program *
3820 bpf_object__find_program_by_title(const struct bpf_object *obj,
3823 struct bpf_program *pos;
3825 bpf_object__for_each_program(pos, obj) {
3826 if (pos->sec_name && !strcmp(pos->sec_name, title))
3829 return errno = ENOENT, NULL;
3832 static bool prog_is_subprog(const struct bpf_object *obj,
3833 const struct bpf_program *prog)
3835 /* For legacy reasons, libbpf supports an entry-point BPF programs
3836 * without SEC() attribute, i.e., those in the .text section. But if
3837 * there are 2 or more such programs in the .text section, they all
3838 * must be subprograms called from entry-point BPF programs in
3839 * designated SEC()'tions, otherwise there is no way to distinguish
3840 * which of those programs should be loaded vs which are a subprogram.
3841 * Similarly, if there is a function/program in .text and at least one
3842 * other BPF program with custom SEC() attribute, then we just assume
3843 * .text programs are subprograms (even if they are not called from
3844 * other programs), because libbpf never explicitly supported mixing
3845 * SEC()-designated BPF programs and .text entry-point BPF programs.
3847 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3850 struct bpf_program *
3851 bpf_object__find_program_by_name(const struct bpf_object *obj,
3854 struct bpf_program *prog;
3856 bpf_object__for_each_program(prog, obj) {
3857 if (prog_is_subprog(obj, prog))
3859 if (!strcmp(prog->name, name))
3862 return errno = ENOENT, NULL;
3865 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3868 switch (obj->efile.secs[shndx].sec_type) {
3878 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3881 return shndx == obj->efile.maps_shndx ||
3882 shndx == obj->efile.btf_maps_shndx;
3885 static enum libbpf_map_type
3886 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3888 if (shndx == obj->efile.symbols_shndx)
3889 return LIBBPF_MAP_KCONFIG;
3891 switch (obj->efile.secs[shndx].sec_type) {
3893 return LIBBPF_MAP_BSS;
3895 return LIBBPF_MAP_DATA;
3897 return LIBBPF_MAP_RODATA;
3899 return LIBBPF_MAP_UNSPEC;
3903 static int bpf_program__record_reloc(struct bpf_program *prog,
3904 struct reloc_desc *reloc_desc,
3905 __u32 insn_idx, const char *sym_name,
3906 const Elf64_Sym *sym, const Elf64_Rel *rel)
3908 struct bpf_insn *insn = &prog->insns[insn_idx];
3909 size_t map_idx, nr_maps = prog->obj->nr_maps;
3910 struct bpf_object *obj = prog->obj;
3911 __u32 shdr_idx = sym->st_shndx;
3912 enum libbpf_map_type type;
3913 const char *sym_sec_name;
3914 struct bpf_map *map;
3916 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3917 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3918 prog->name, sym_name, insn_idx, insn->code);
3919 return -LIBBPF_ERRNO__RELOC;
3922 if (sym_is_extern(sym)) {
3923 int sym_idx = ELF64_R_SYM(rel->r_info);
3924 int i, n = obj->nr_extern;
3925 struct extern_desc *ext;
3927 for (i = 0; i < n; i++) {
3928 ext = &obj->externs[i];
3929 if (ext->sym_idx == sym_idx)
3933 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3934 prog->name, sym_name, sym_idx);
3935 return -LIBBPF_ERRNO__RELOC;
3937 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3938 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3939 if (insn->code == (BPF_JMP | BPF_CALL))
3940 reloc_desc->type = RELO_EXTERN_FUNC;
3942 reloc_desc->type = RELO_EXTERN_VAR;
3943 reloc_desc->insn_idx = insn_idx;
3944 reloc_desc->sym_off = i; /* sym_off stores extern index */
3948 /* sub-program call relocation */
3949 if (is_call_insn(insn)) {
3950 if (insn->src_reg != BPF_PSEUDO_CALL) {
3951 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3952 return -LIBBPF_ERRNO__RELOC;
3954 /* text_shndx can be 0, if no default "main" program exists */
3955 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3956 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3957 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3958 prog->name, sym_name, sym_sec_name);
3959 return -LIBBPF_ERRNO__RELOC;
3961 if (sym->st_value % BPF_INSN_SZ) {
3962 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3963 prog->name, sym_name, (size_t)sym->st_value);
3964 return -LIBBPF_ERRNO__RELOC;
3966 reloc_desc->type = RELO_CALL;
3967 reloc_desc->insn_idx = insn_idx;
3968 reloc_desc->sym_off = sym->st_value;
3972 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3973 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3974 prog->name, sym_name, shdr_idx);
3975 return -LIBBPF_ERRNO__RELOC;
3978 /* loading subprog addresses */
3979 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3980 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3981 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3983 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3984 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3985 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3986 return -LIBBPF_ERRNO__RELOC;
3989 reloc_desc->type = RELO_SUBPROG_ADDR;
3990 reloc_desc->insn_idx = insn_idx;
3991 reloc_desc->sym_off = sym->st_value;
3995 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3996 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3998 /* generic map reference relocation */
3999 if (type == LIBBPF_MAP_UNSPEC) {
4000 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4001 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4002 prog->name, sym_name, sym_sec_name);
4003 return -LIBBPF_ERRNO__RELOC;
4005 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4006 map = &obj->maps[map_idx];
4007 if (map->libbpf_type != type ||
4008 map->sec_idx != sym->st_shndx ||
4009 map->sec_offset != sym->st_value)
4011 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4012 prog->name, map_idx, map->name, map->sec_idx,
4013 map->sec_offset, insn_idx);
4016 if (map_idx >= nr_maps) {
4017 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4018 prog->name, sym_sec_name, (size_t)sym->st_value);
4019 return -LIBBPF_ERRNO__RELOC;
4021 reloc_desc->type = RELO_LD64;
4022 reloc_desc->insn_idx = insn_idx;
4023 reloc_desc->map_idx = map_idx;
4024 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4028 /* global data map relocation */
4029 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4030 pr_warn("prog '%s': bad data relo against section '%s'\n",
4031 prog->name, sym_sec_name);
4032 return -LIBBPF_ERRNO__RELOC;
4034 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4035 map = &obj->maps[map_idx];
4036 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4038 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4039 prog->name, map_idx, map->name, map->sec_idx,
4040 map->sec_offset, insn_idx);
4043 if (map_idx >= nr_maps) {
4044 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4045 prog->name, sym_sec_name);
4046 return -LIBBPF_ERRNO__RELOC;
4049 reloc_desc->type = RELO_DATA;
4050 reloc_desc->insn_idx = insn_idx;
4051 reloc_desc->map_idx = map_idx;
4052 reloc_desc->sym_off = sym->st_value;
4056 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4058 return insn_idx >= prog->sec_insn_off &&
4059 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4062 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4063 size_t sec_idx, size_t insn_idx)
4065 int l = 0, r = obj->nr_programs - 1, m;
4066 struct bpf_program *prog;
4069 m = l + (r - l + 1) / 2;
4070 prog = &obj->programs[m];
4072 if (prog->sec_idx < sec_idx ||
4073 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4078 /* matching program could be at index l, but it still might be the
4079 * wrong one, so we need to double check conditions for the last time
4081 prog = &obj->programs[l];
4082 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4088 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4090 const char *relo_sec_name, *sec_name;
4091 size_t sec_idx = shdr->sh_info, sym_idx;
4092 struct bpf_program *prog;
4093 struct reloc_desc *relos;
4095 const char *sym_name;
4102 if (sec_idx >= obj->efile.sec_cnt)
4105 scn = elf_sec_by_idx(obj, sec_idx);
4106 scn_data = elf_sec_data(obj, scn);
4108 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4109 sec_name = elf_sec_name(obj, scn);
4110 if (!relo_sec_name || !sec_name)
4113 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4114 relo_sec_name, sec_idx, sec_name);
4115 nrels = shdr->sh_size / shdr->sh_entsize;
4117 for (i = 0; i < nrels; i++) {
4118 rel = elf_rel_by_idx(data, i);
4120 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4121 return -LIBBPF_ERRNO__FORMAT;
4124 sym_idx = ELF64_R_SYM(rel->r_info);
4125 sym = elf_sym_by_idx(obj, sym_idx);
4127 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4128 relo_sec_name, sym_idx, i);
4129 return -LIBBPF_ERRNO__FORMAT;
4132 if (sym->st_shndx >= obj->efile.sec_cnt) {
4133 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4134 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4135 return -LIBBPF_ERRNO__FORMAT;
4138 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4139 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4140 relo_sec_name, (size_t)rel->r_offset, i);
4141 return -LIBBPF_ERRNO__FORMAT;
4144 insn_idx = rel->r_offset / BPF_INSN_SZ;
4145 /* relocations against static functions are recorded as
4146 * relocations against the section that contains a function;
4147 * in such case, symbol will be STT_SECTION and sym.st_name
4148 * will point to empty string (0), so fetch section name
4151 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4152 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4154 sym_name = elf_sym_str(obj, sym->st_name);
4155 sym_name = sym_name ?: "<?";
4157 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4158 relo_sec_name, i, insn_idx, sym_name);
4160 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4162 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4163 relo_sec_name, i, sec_name, insn_idx);
4167 relos = libbpf_reallocarray(prog->reloc_desc,
4168 prog->nr_reloc + 1, sizeof(*relos));
4171 prog->reloc_desc = relos;
4173 /* adjust insn_idx to local BPF program frame of reference */
4174 insn_idx -= prog->sec_insn_off;
4175 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4176 insn_idx, sym_name, sym, rel);
4185 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4187 struct bpf_map_def *def = &map->def;
4188 __u32 key_type_id = 0, value_type_id = 0;
4191 /* if it's BTF-defined map, we don't need to search for type IDs.
4192 * For struct_ops map, it does not need btf_key_type_id and
4193 * btf_value_type_id.
4195 if (map->sec_idx == obj->efile.btf_maps_shndx ||
4196 bpf_map__is_struct_ops(map))
4199 if (!bpf_map__is_internal(map)) {
4200 pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
4201 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
4202 def->value_size, &key_type_id,
4206 * LLVM annotates global data differently in BTF, that is,
4207 * only as '.data', '.bss' or '.rodata'.
4209 ret = btf__find_by_name(obj->btf, map->real_name);
4214 map->btf_key_type_id = key_type_id;
4215 map->btf_value_type_id = bpf_map__is_internal(map) ?
4216 ret : value_type_id;
4220 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4222 char file[PATH_MAX], buff[4096];
4227 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4228 memset(info, 0, sizeof(*info));
4230 fp = fopen(file, "r");
4233 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4238 while (fgets(buff, sizeof(buff), fp)) {
4239 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4241 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4242 info->key_size = val;
4243 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4244 info->value_size = val;
4245 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4246 info->max_entries = val;
4247 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4248 info->map_flags = val;
4256 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4258 struct bpf_map_info info = {};
4259 __u32 len = sizeof(info);
4263 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4264 if (err && errno == EINVAL)
4265 err = bpf_get_map_info_from_fdinfo(fd, &info);
4267 return libbpf_err(err);
4269 new_name = strdup(info.name);
4271 return libbpf_err(-errno);
4273 new_fd = open("/", O_RDONLY | O_CLOEXEC);
4276 goto err_free_new_name;
4279 new_fd = dup3(fd, new_fd, O_CLOEXEC);
4282 goto err_close_new_fd;
4285 err = zclose(map->fd);
4288 goto err_close_new_fd;
4293 map->name = new_name;
4294 map->def.type = info.type;
4295 map->def.key_size = info.key_size;
4296 map->def.value_size = info.value_size;
4297 map->def.max_entries = info.max_entries;
4298 map->def.map_flags = info.map_flags;
4299 map->btf_key_type_id = info.btf_key_type_id;
4300 map->btf_value_type_id = info.btf_value_type_id;
4302 map->map_extra = info.map_extra;
4310 return libbpf_err(err);
4313 __u32 bpf_map__max_entries(const struct bpf_map *map)
4315 return map->def.max_entries;
4318 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4320 if (!bpf_map_type__is_map_in_map(map->def.type))
4321 return errno = EINVAL, NULL;
4323 return map->inner_map;
4326 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4329 return libbpf_err(-EBUSY);
4330 map->def.max_entries = max_entries;
4334 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4336 if (!map || !max_entries)
4337 return libbpf_err(-EINVAL);
4339 return bpf_map__set_max_entries(map, max_entries);
4343 bpf_object__probe_loading(struct bpf_object *obj)
4345 char *cp, errmsg[STRERR_BUFSIZE];
4346 struct bpf_insn insns[] = {
4347 BPF_MOV64_IMM(BPF_REG_0, 0),
4350 int ret, insn_cnt = ARRAY_SIZE(insns);
4352 if (obj->gen_loader)
4355 ret = bump_rlimit_memlock();
4357 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4359 /* make sure basic loading works */
4360 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4362 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4365 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4366 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4367 "program. Make sure your kernel supports BPF "
4368 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4369 "set to big enough value.\n", __func__, cp, ret);
4377 static int probe_fd(int fd)
4384 static int probe_kern_prog_name(void)
4386 struct bpf_insn insns[] = {
4387 BPF_MOV64_IMM(BPF_REG_0, 0),
4390 int ret, insn_cnt = ARRAY_SIZE(insns);
4392 /* make sure loading with name works */
4393 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
4394 return probe_fd(ret);
4397 static int probe_kern_global_data(void)
4399 char *cp, errmsg[STRERR_BUFSIZE];
4400 struct bpf_insn insns[] = {
4401 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4402 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4403 BPF_MOV64_IMM(BPF_REG_0, 0),
4406 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4408 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4411 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4412 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4413 __func__, cp, -ret);
4419 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4421 return probe_fd(ret);
4424 static int probe_kern_btf(void)
4426 static const char strs[] = "\0int";
4429 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4432 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4433 strs, sizeof(strs)));
4436 static int probe_kern_btf_func(void)
4438 static const char strs[] = "\0int\0x\0a";
4439 /* void x(int a) {} */
4442 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4443 /* FUNC_PROTO */ /* [2] */
4444 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4445 BTF_PARAM_ENC(7, 1),
4446 /* FUNC x */ /* [3] */
4447 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4450 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4451 strs, sizeof(strs)));
4454 static int probe_kern_btf_func_global(void)
4456 static const char strs[] = "\0int\0x\0a";
4457 /* static void x(int a) {} */
4460 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4461 /* FUNC_PROTO */ /* [2] */
4462 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4463 BTF_PARAM_ENC(7, 1),
4464 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4465 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4468 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4469 strs, sizeof(strs)));
4472 static int probe_kern_btf_datasec(void)
4474 static const char strs[] = "\0x\0.data";
4478 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4479 /* VAR x */ /* [2] */
4480 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4482 /* DATASEC val */ /* [3] */
4483 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4484 BTF_VAR_SECINFO_ENC(2, 0, 4),
4487 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4488 strs, sizeof(strs)));
4491 static int probe_kern_btf_float(void)
4493 static const char strs[] = "\0float";
4496 BTF_TYPE_FLOAT_ENC(1, 4),
4499 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4500 strs, sizeof(strs)));
4503 static int probe_kern_btf_decl_tag(void)
4505 static const char strs[] = "\0tag";
4508 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4509 /* VAR x */ /* [2] */
4510 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4513 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4516 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4517 strs, sizeof(strs)));
4520 static int probe_kern_btf_type_tag(void)
4522 static const char strs[] = "\0tag";
4525 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4527 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4529 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4532 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4533 strs, sizeof(strs)));
4536 static int probe_kern_array_mmap(void)
4538 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4541 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4542 return probe_fd(fd);
4545 static int probe_kern_exp_attach_type(void)
4547 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4548 struct bpf_insn insns[] = {
4549 BPF_MOV64_IMM(BPF_REG_0, 0),
4552 int fd, insn_cnt = ARRAY_SIZE(insns);
4554 /* use any valid combination of program type and (optional)
4555 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4556 * to see if kernel supports expected_attach_type field for
4557 * BPF_PROG_LOAD command
4559 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4560 return probe_fd(fd);
4563 static int probe_kern_probe_read_kernel(void)
4565 struct bpf_insn insns[] = {
4566 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4567 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4568 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4569 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4570 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4573 int fd, insn_cnt = ARRAY_SIZE(insns);
4575 fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4576 return probe_fd(fd);
4579 static int probe_prog_bind_map(void)
4581 char *cp, errmsg[STRERR_BUFSIZE];
4582 struct bpf_insn insns[] = {
4583 BPF_MOV64_IMM(BPF_REG_0, 0),
4586 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4588 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4591 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4592 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4593 __func__, cp, -ret);
4597 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4603 ret = bpf_prog_bind_map(prog, map, NULL);
4611 static int probe_module_btf(void)
4613 static const char strs[] = "\0int";
4616 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4618 struct bpf_btf_info info;
4619 __u32 len = sizeof(info);
4623 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4625 return 0; /* BTF not supported at all */
4627 memset(&info, 0, sizeof(info));
4628 info.name = ptr_to_u64(name);
4629 info.name_len = sizeof(name);
4631 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4632 * kernel's module BTF support coincides with support for
4633 * name/name_len fields in struct bpf_btf_info.
4635 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4640 static int probe_perf_link(void)
4642 struct bpf_insn insns[] = {
4643 BPF_MOV64_IMM(BPF_REG_0, 0),
4646 int prog_fd, link_fd, err;
4648 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4649 insns, ARRAY_SIZE(insns), NULL);
4653 /* use invalid perf_event FD to get EBADF, if link is supported;
4654 * otherwise EINVAL should be returned
4656 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4657 err = -errno; /* close() can clobber errno */
4663 return link_fd < 0 && err == -EBADF;
4666 enum kern_feature_result {
4672 typedef int (*feature_probe_fn)(void);
4674 static struct kern_feature_desc {
4676 feature_probe_fn probe;
4677 enum kern_feature_result res;
4678 } feature_probes[__FEAT_CNT] = {
4679 [FEAT_PROG_NAME] = {
4680 "BPF program name", probe_kern_prog_name,
4682 [FEAT_GLOBAL_DATA] = {
4683 "global variables", probe_kern_global_data,
4686 "minimal BTF", probe_kern_btf,
4689 "BTF functions", probe_kern_btf_func,
4691 [FEAT_BTF_GLOBAL_FUNC] = {
4692 "BTF global function", probe_kern_btf_func_global,
4694 [FEAT_BTF_DATASEC] = {
4695 "BTF data section and variable", probe_kern_btf_datasec,
4697 [FEAT_ARRAY_MMAP] = {
4698 "ARRAY map mmap()", probe_kern_array_mmap,
4700 [FEAT_EXP_ATTACH_TYPE] = {
4701 "BPF_PROG_LOAD expected_attach_type attribute",
4702 probe_kern_exp_attach_type,
4704 [FEAT_PROBE_READ_KERN] = {
4705 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4707 [FEAT_PROG_BIND_MAP] = {
4708 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4710 [FEAT_MODULE_BTF] = {
4711 "module BTF support", probe_module_btf,
4713 [FEAT_BTF_FLOAT] = {
4714 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4716 [FEAT_PERF_LINK] = {
4717 "BPF perf link support", probe_perf_link,
4719 [FEAT_BTF_DECL_TAG] = {
4720 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4722 [FEAT_BTF_TYPE_TAG] = {
4723 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4725 [FEAT_MEMCG_ACCOUNT] = {
4726 "memcg-based memory accounting", probe_memcg_account,
4730 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4732 struct kern_feature_desc *feat = &feature_probes[feat_id];
4735 if (obj && obj->gen_loader)
4736 /* To generate loader program assume the latest kernel
4737 * to avoid doing extra prog_load, map_create syscalls.
4741 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4742 ret = feat->probe();
4744 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4745 } else if (ret == 0) {
4746 WRITE_ONCE(feat->res, FEAT_MISSING);
4748 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4749 WRITE_ONCE(feat->res, FEAT_MISSING);
4753 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4756 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4758 struct bpf_map_info map_info = {};
4759 char msg[STRERR_BUFSIZE];
4763 map_info_len = sizeof(map_info);
4765 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4766 if (err && errno == EINVAL)
4767 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4769 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4770 libbpf_strerror_r(errno, msg, sizeof(msg)));
4774 return (map_info.type == map->def.type &&
4775 map_info.key_size == map->def.key_size &&
4776 map_info.value_size == map->def.value_size &&
4777 map_info.max_entries == map->def.max_entries &&
4778 map_info.map_flags == map->def.map_flags &&
4779 map_info.map_extra == map->map_extra);
4783 bpf_object__reuse_map(struct bpf_map *map)
4785 char *cp, errmsg[STRERR_BUFSIZE];
4788 pin_fd = bpf_obj_get(map->pin_path);
4791 if (err == -ENOENT) {
4792 pr_debug("found no pinned map to reuse at '%s'\n",
4797 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4798 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4803 if (!map_is_reuse_compat(map, pin_fd)) {
4804 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4810 err = bpf_map__reuse_fd(map, pin_fd);
4816 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4822 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4824 enum libbpf_map_type map_type = map->libbpf_type;
4825 char *cp, errmsg[STRERR_BUFSIZE];
4828 if (obj->gen_loader) {
4829 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4830 map->mmaped, map->def.value_size);
4831 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4832 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4835 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4838 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4839 pr_warn("Error setting initial map(%s) contents: %s\n",
4844 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4845 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4846 err = bpf_map_freeze(map->fd);
4849 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4850 pr_warn("Error freezing map(%s) as read-only: %s\n",
4858 static void bpf_map__destroy(struct bpf_map *map);
4860 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4862 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4863 struct bpf_map_def *def = &map->def;
4864 const char *map_name = NULL;
4868 if (kernel_supports(obj, FEAT_PROG_NAME))
4869 map_name = map->name;
4870 create_attr.map_ifindex = map->map_ifindex;
4871 create_attr.map_flags = def->map_flags;
4872 create_attr.numa_node = map->numa_node;
4873 create_attr.map_extra = map->map_extra;
4875 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4878 nr_cpus = libbpf_num_possible_cpus();
4880 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4881 map->name, nr_cpus);
4884 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4885 max_entries = nr_cpus;
4887 max_entries = def->max_entries;
4890 if (bpf_map__is_struct_ops(map))
4891 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4893 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4894 create_attr.btf_fd = btf__fd(obj->btf);
4895 create_attr.btf_key_type_id = map->btf_key_type_id;
4896 create_attr.btf_value_type_id = map->btf_value_type_id;
4899 if (bpf_map_type__is_map_in_map(def->type)) {
4900 if (map->inner_map) {
4901 err = bpf_object__create_map(obj, map->inner_map, true);
4903 pr_warn("map '%s': failed to create inner map: %d\n",
4907 map->inner_map_fd = bpf_map__fd(map->inner_map);
4909 if (map->inner_map_fd >= 0)
4910 create_attr.inner_map_fd = map->inner_map_fd;
4913 switch (def->type) {
4914 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4915 case BPF_MAP_TYPE_CGROUP_ARRAY:
4916 case BPF_MAP_TYPE_STACK_TRACE:
4917 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4918 case BPF_MAP_TYPE_HASH_OF_MAPS:
4919 case BPF_MAP_TYPE_DEVMAP:
4920 case BPF_MAP_TYPE_DEVMAP_HASH:
4921 case BPF_MAP_TYPE_CPUMAP:
4922 case BPF_MAP_TYPE_XSKMAP:
4923 case BPF_MAP_TYPE_SOCKMAP:
4924 case BPF_MAP_TYPE_SOCKHASH:
4925 case BPF_MAP_TYPE_QUEUE:
4926 case BPF_MAP_TYPE_STACK:
4927 case BPF_MAP_TYPE_RINGBUF:
4928 create_attr.btf_fd = 0;
4929 create_attr.btf_key_type_id = 0;
4930 create_attr.btf_value_type_id = 0;
4931 map->btf_key_type_id = 0;
4932 map->btf_value_type_id = 0;
4937 if (obj->gen_loader) {
4938 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
4939 def->key_size, def->value_size, max_entries,
4940 &create_attr, is_inner ? -1 : map - obj->maps);
4941 /* Pretend to have valid FD to pass various fd >= 0 checks.
4942 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4946 map->fd = bpf_map_create(def->type, map_name,
4947 def->key_size, def->value_size,
4948 max_entries, &create_attr);
4950 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4951 create_attr.btf_value_type_id)) {
4952 char *cp, errmsg[STRERR_BUFSIZE];
4955 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4956 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4957 map->name, cp, err);
4958 create_attr.btf_fd = 0;
4959 create_attr.btf_key_type_id = 0;
4960 create_attr.btf_value_type_id = 0;
4961 map->btf_key_type_id = 0;
4962 map->btf_value_type_id = 0;
4963 map->fd = bpf_map_create(def->type, map_name,
4964 def->key_size, def->value_size,
4965 max_entries, &create_attr);
4968 err = map->fd < 0 ? -errno : 0;
4970 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4971 if (obj->gen_loader)
4972 map->inner_map->fd = -1;
4973 bpf_map__destroy(map->inner_map);
4974 zfree(&map->inner_map);
4980 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
4982 const struct bpf_map *targ_map;
4986 for (i = 0; i < map->init_slots_sz; i++) {
4987 if (!map->init_slots[i])
4990 targ_map = map->init_slots[i];
4991 fd = bpf_map__fd(targ_map);
4993 if (obj->gen_loader) {
4994 bpf_gen__populate_outer_map(obj->gen_loader,
4996 targ_map - obj->maps);
4998 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5002 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5003 map->name, i, targ_map->name, fd, err);
5006 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5007 map->name, i, targ_map->name, fd);
5010 zfree(&map->init_slots);
5011 map->init_slots_sz = 0;
5016 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5018 const struct bpf_program *targ_prog;
5022 if (obj->gen_loader)
5025 for (i = 0; i < map->init_slots_sz; i++) {
5026 if (!map->init_slots[i])
5029 targ_prog = map->init_slots[i];
5030 fd = bpf_program__fd(targ_prog);
5032 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5035 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5036 map->name, i, targ_prog->name, fd, err);
5039 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5040 map->name, i, targ_prog->name, fd);
5043 zfree(&map->init_slots);
5044 map->init_slots_sz = 0;
5049 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5051 struct bpf_map *map;
5054 for (i = 0; i < obj->nr_maps; i++) {
5055 map = &obj->maps[i];
5057 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5060 err = init_prog_array_slots(obj, map);
5070 bpf_object__create_maps(struct bpf_object *obj)
5072 struct bpf_map *map;
5073 char *cp, errmsg[STRERR_BUFSIZE];
5078 for (i = 0; i < obj->nr_maps; i++) {
5079 map = &obj->maps[i];
5081 /* To support old kernels, we skip creating global data maps
5082 * (.rodata, .data, .kconfig, etc); later on, during program
5083 * loading, if we detect that at least one of the to-be-loaded
5084 * programs is referencing any global data map, we'll error
5085 * out with program name and relocation index logged.
5086 * This approach allows to accommodate Clang emitting
5087 * unnecessary .rodata.str1.1 sections for string literals,
5088 * but also it allows to have CO-RE applications that use
5089 * global variables in some of BPF programs, but not others.
5090 * If those global variable-using programs are not loaded at
5091 * runtime due to bpf_program__set_autoload(prog, false),
5092 * bpf_object loading will succeed just fine even on old
5095 if (bpf_map__is_internal(map) &&
5096 !kernel_supports(obj, FEAT_GLOBAL_DATA)) {
5097 map->skipped = true;
5103 if (map->pin_path) {
5104 err = bpf_object__reuse_map(map);
5106 pr_warn("map '%s': error reusing pinned map\n",
5110 if (retried && map->fd < 0) {
5111 pr_warn("map '%s': cannot find pinned map\n",
5119 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5120 map->name, map->fd);
5122 err = bpf_object__create_map(obj, map, false);
5126 pr_debug("map '%s': created successfully, fd=%d\n",
5127 map->name, map->fd);
5129 if (bpf_map__is_internal(map)) {
5130 err = bpf_object__populate_internal_map(obj, map);
5137 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5138 err = init_map_in_map_slots(obj, map);
5146 if (map->pin_path && !map->pinned) {
5147 err = bpf_map__pin(map, NULL);
5150 if (!retried && err == -EEXIST) {
5154 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5155 map->name, map->pin_path, err);
5164 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5165 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5167 for (j = 0; j < i; j++)
5168 zclose(obj->maps[j].fd);
5172 static bool bpf_core_is_flavor_sep(const char *s)
5174 /* check X___Y name pattern, where X and Y are not underscores */
5175 return s[0] != '_' && /* X */
5176 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5177 s[4] != '_'; /* Y */
5180 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5181 * before last triple underscore. Struct name part after last triple
5182 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5184 size_t bpf_core_essential_name_len(const char *name)
5186 size_t n = strlen(name);
5189 for (i = n - 5; i >= 0; i--) {
5190 if (bpf_core_is_flavor_sep(name + i))
5196 static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5202 static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5203 size_t local_essent_len,
5204 const struct btf *targ_btf,
5205 const char *targ_btf_name,
5207 struct bpf_core_cand_list *cands)
5209 struct bpf_core_cand *new_cands, *cand;
5210 const struct btf_type *t, *local_t;
5211 const char *targ_name, *local_name;
5212 size_t targ_essent_len;
5215 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5216 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5218 n = btf__type_cnt(targ_btf);
5219 for (i = targ_start_id; i < n; i++) {
5220 t = btf__type_by_id(targ_btf, i);
5221 if (btf_kind(t) != btf_kind(local_t))
5224 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5225 if (str_is_empty(targ_name))
5228 targ_essent_len = bpf_core_essential_name_len(targ_name);
5229 if (targ_essent_len != local_essent_len)
5232 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5235 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5236 local_cand->id, btf_kind_str(local_t),
5237 local_name, i, btf_kind_str(t), targ_name,
5239 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5240 sizeof(*cands->cands));
5244 cand = &new_cands[cands->len];
5245 cand->btf = targ_btf;
5248 cands->cands = new_cands;
5254 static int load_module_btfs(struct bpf_object *obj)
5256 struct bpf_btf_info info;
5257 struct module_btf *mod_btf;
5263 if (obj->btf_modules_loaded)
5266 if (obj->gen_loader)
5269 /* don't do this again, even if we find no module BTFs */
5270 obj->btf_modules_loaded = true;
5272 /* kernel too old to support module BTFs */
5273 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5277 err = bpf_btf_get_next_id(id, &id);
5278 if (err && errno == ENOENT)
5282 pr_warn("failed to iterate BTF objects: %d\n", err);
5286 fd = bpf_btf_get_fd_by_id(id);
5288 if (errno == ENOENT)
5289 continue; /* expected race: BTF was unloaded */
5291 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5296 memset(&info, 0, sizeof(info));
5297 info.name = ptr_to_u64(name);
5298 info.name_len = sizeof(name);
5300 err = bpf_obj_get_info_by_fd(fd, &info, &len);
5303 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5307 /* ignore non-module BTFs */
5308 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5313 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5314 err = libbpf_get_error(btf);
5316 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5321 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5322 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5326 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5331 mod_btf->name = strdup(name);
5332 if (!mod_btf->name) {
5346 static struct bpf_core_cand_list *
5347 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5349 struct bpf_core_cand local_cand = {};
5350 struct bpf_core_cand_list *cands;
5351 const struct btf *main_btf;
5352 const struct btf_type *local_t;
5353 const char *local_name;
5354 size_t local_essent_len;
5357 local_cand.btf = local_btf;
5358 local_cand.id = local_type_id;
5359 local_t = btf__type_by_id(local_btf, local_type_id);
5361 return ERR_PTR(-EINVAL);
5363 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5364 if (str_is_empty(local_name))
5365 return ERR_PTR(-EINVAL);
5366 local_essent_len = bpf_core_essential_name_len(local_name);
5368 cands = calloc(1, sizeof(*cands));
5370 return ERR_PTR(-ENOMEM);
5372 /* Attempt to find target candidates in vmlinux BTF first */
5373 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5374 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5378 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5382 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5383 if (obj->btf_vmlinux_override)
5386 /* now look through module BTFs, trying to still find candidates */
5387 err = load_module_btfs(obj);
5391 for (i = 0; i < obj->btf_module_cnt; i++) {
5392 err = bpf_core_add_cands(&local_cand, local_essent_len,
5393 obj->btf_modules[i].btf,
5394 obj->btf_modules[i].name,
5395 btf__type_cnt(obj->btf_vmlinux),
5403 bpf_core_free_cands(cands);
5404 return ERR_PTR(err);
5407 /* Check local and target types for compatibility. This check is used for
5408 * type-based CO-RE relocations and follow slightly different rules than
5409 * field-based relocations. This function assumes that root types were already
5410 * checked for name match. Beyond that initial root-level name check, names
5411 * are completely ignored. Compatibility rules are as follows:
5412 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5413 * kind should match for local and target types (i.e., STRUCT is not
5414 * compatible with UNION);
5415 * - for ENUMs, the size is ignored;
5416 * - for INT, size and signedness are ignored;
5417 * - for ARRAY, dimensionality is ignored, element types are checked for
5418 * compatibility recursively;
5419 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5420 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5421 * - FUNC_PROTOs are compatible if they have compatible signature: same
5422 * number of input args and compatible return and argument types.
5423 * These rules are not set in stone and probably will be adjusted as we get
5424 * more experience with using BPF CO-RE relocations.
5426 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5427 const struct btf *targ_btf, __u32 targ_id)
5429 const struct btf_type *local_type, *targ_type;
5430 int depth = 32; /* max recursion depth */
5432 /* caller made sure that names match (ignoring flavor suffix) */
5433 local_type = btf__type_by_id(local_btf, local_id);
5434 targ_type = btf__type_by_id(targ_btf, targ_id);
5435 if (btf_kind(local_type) != btf_kind(targ_type))
5443 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5444 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5445 if (!local_type || !targ_type)
5448 if (btf_kind(local_type) != btf_kind(targ_type))
5451 switch (btf_kind(local_type)) {
5453 case BTF_KIND_STRUCT:
5454 case BTF_KIND_UNION:
5459 /* just reject deprecated bitfield-like integers; all other
5460 * integers are by default compatible between each other
5462 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5464 local_id = local_type->type;
5465 targ_id = targ_type->type;
5467 case BTF_KIND_ARRAY:
5468 local_id = btf_array(local_type)->type;
5469 targ_id = btf_array(targ_type)->type;
5471 case BTF_KIND_FUNC_PROTO: {
5472 struct btf_param *local_p = btf_params(local_type);
5473 struct btf_param *targ_p = btf_params(targ_type);
5474 __u16 local_vlen = btf_vlen(local_type);
5475 __u16 targ_vlen = btf_vlen(targ_type);
5478 if (local_vlen != targ_vlen)
5481 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5482 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5483 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5484 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5489 /* tail recurse for return type check */
5490 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5491 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5495 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5496 btf_kind_str(local_type), local_id, targ_id);
5501 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5506 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5511 static void *u32_as_hash_key(__u32 x)
5513 return (void *)(uintptr_t)x;
5516 static int record_relo_core(struct bpf_program *prog,
5517 const struct bpf_core_relo *core_relo, int insn_idx)
5519 struct reloc_desc *relos, *relo;
5521 relos = libbpf_reallocarray(prog->reloc_desc,
5522 prog->nr_reloc + 1, sizeof(*relos));
5525 relo = &relos[prog->nr_reloc];
5526 relo->type = RELO_CORE;
5527 relo->insn_idx = insn_idx;
5528 relo->core_relo = core_relo;
5529 prog->reloc_desc = relos;
5534 static int bpf_core_apply_relo(struct bpf_program *prog,
5535 const struct bpf_core_relo *relo,
5537 const struct btf *local_btf,
5538 struct hashmap *cand_cache)
5540 struct bpf_core_spec specs_scratch[3] = {};
5541 const void *type_key = u32_as_hash_key(relo->type_id);
5542 struct bpf_core_cand_list *cands = NULL;
5543 const char *prog_name = prog->name;
5544 const struct btf_type *local_type;
5545 const char *local_name;
5546 __u32 local_id = relo->type_id;
5547 struct bpf_insn *insn;
5550 if (relo->insn_off % BPF_INSN_SZ)
5552 insn_idx = relo->insn_off / BPF_INSN_SZ;
5553 /* adjust insn_idx from section frame of reference to the local
5554 * program's frame of reference; (sub-)program code is not yet
5555 * relocated, so it's enough to just subtract in-section offset
5557 insn_idx = insn_idx - prog->sec_insn_off;
5558 if (insn_idx >= prog->insns_cnt)
5560 insn = &prog->insns[insn_idx];
5562 local_type = btf__type_by_id(local_btf, local_id);
5566 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5570 if (prog->obj->gen_loader) {
5571 const char *spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
5573 pr_debug("record_relo_core: prog %td insn[%d] %s %s %s final insn_idx %d\n",
5574 prog - prog->obj->programs, relo->insn_off / 8,
5575 btf_kind_str(local_type), local_name, spec_str, insn_idx);
5576 return record_relo_core(prog, relo, insn_idx);
5579 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5580 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5581 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5582 if (IS_ERR(cands)) {
5583 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5584 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5585 local_name, PTR_ERR(cands));
5586 return PTR_ERR(cands);
5588 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5590 bpf_core_free_cands(cands);
5595 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo,
5596 relo_idx, local_btf, cands, specs_scratch);
5600 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5602 const struct btf_ext_info_sec *sec;
5603 const struct bpf_core_relo *rec;
5604 const struct btf_ext_info *seg;
5605 struct hashmap_entry *entry;
5606 struct hashmap *cand_cache = NULL;
5607 struct bpf_program *prog;
5608 const char *sec_name;
5609 int i, err = 0, insn_idx, sec_idx;
5611 if (obj->btf_ext->core_relo_info.len == 0)
5614 if (targ_btf_path) {
5615 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5616 err = libbpf_get_error(obj->btf_vmlinux_override);
5618 pr_warn("failed to parse target BTF: %d\n", err);
5623 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5624 if (IS_ERR(cand_cache)) {
5625 err = PTR_ERR(cand_cache);
5629 seg = &obj->btf_ext->core_relo_info;
5630 for_each_btf_ext_sec(seg, sec) {
5631 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5632 if (str_is_empty(sec_name)) {
5636 /* bpf_object's ELF is gone by now so it's not easy to find
5637 * section index by section name, but we can find *any*
5638 * bpf_program within desired section name and use it's
5639 * prog->sec_idx to do a proper search by section index and
5640 * instruction offset
5643 for (i = 0; i < obj->nr_programs; i++) {
5644 prog = &obj->programs[i];
5645 if (strcmp(prog->sec_name, sec_name) == 0)
5649 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5652 sec_idx = prog->sec_idx;
5654 pr_debug("sec '%s': found %d CO-RE relocations\n",
5655 sec_name, sec->num_info);
5657 for_each_btf_ext_rec(seg, sec, i, rec) {
5658 insn_idx = rec->insn_off / BPF_INSN_SZ;
5659 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5661 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5662 sec_name, insn_idx, i);
5666 /* no need to apply CO-RE relocation if the program is
5667 * not going to be loaded
5672 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
5674 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5675 prog->name, i, err);
5682 /* obj->btf_vmlinux and module BTFs are freed after object load */
5683 btf__free(obj->btf_vmlinux_override);
5684 obj->btf_vmlinux_override = NULL;
5686 if (!IS_ERR_OR_NULL(cand_cache)) {
5687 hashmap__for_each_entry(cand_cache, entry, i) {
5688 bpf_core_free_cands(entry->value);
5690 hashmap__free(cand_cache);
5695 /* Relocate data references within program code:
5697 * - global variable references;
5698 * - extern references.
5701 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5705 for (i = 0; i < prog->nr_reloc; i++) {
5706 struct reloc_desc *relo = &prog->reloc_desc[i];
5707 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5708 struct extern_desc *ext;
5710 switch (relo->type) {
5712 if (obj->gen_loader) {
5713 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5714 insn[0].imm = relo->map_idx;
5716 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5717 insn[0].imm = obj->maps[relo->map_idx].fd;
5721 insn[1].imm = insn[0].imm + relo->sym_off;
5722 if (obj->gen_loader) {
5723 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5724 insn[0].imm = relo->map_idx;
5726 const struct bpf_map *map = &obj->maps[relo->map_idx];
5729 pr_warn("prog '%s': relo #%d: kernel doesn't support global data\n",
5733 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5734 insn[0].imm = obj->maps[relo->map_idx].fd;
5737 case RELO_EXTERN_VAR:
5738 ext = &obj->externs[relo->sym_off];
5739 if (ext->type == EXT_KCFG) {
5740 if (obj->gen_loader) {
5741 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5742 insn[0].imm = obj->kconfig_map_idx;
5744 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5745 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5747 insn[1].imm = ext->kcfg.data_off;
5748 } else /* EXT_KSYM */ {
5749 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5750 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5751 insn[0].imm = ext->ksym.kernel_btf_id;
5752 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5753 } else { /* typeless ksyms or unresolved typed ksyms */
5754 insn[0].imm = (__u32)ext->ksym.addr;
5755 insn[1].imm = ext->ksym.addr >> 32;
5759 case RELO_EXTERN_FUNC:
5760 ext = &obj->externs[relo->sym_off];
5761 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5763 insn[0].imm = ext->ksym.kernel_btf_id;
5764 insn[0].off = ext->ksym.btf_fd_idx;
5765 } else { /* unresolved weak kfunc */
5770 case RELO_SUBPROG_ADDR:
5771 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5772 pr_warn("prog '%s': relo #%d: bad insn\n",
5776 /* handled already */
5779 /* handled already */
5782 /* will be handled by bpf_program_record_relos() */
5785 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5786 prog->name, i, relo->type);
5794 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5795 const struct bpf_program *prog,
5796 const struct btf_ext_info *ext_info,
5797 void **prog_info, __u32 *prog_rec_cnt,
5800 void *copy_start = NULL, *copy_end = NULL;
5801 void *rec, *rec_end, *new_prog_info;
5802 const struct btf_ext_info_sec *sec;
5803 size_t old_sz, new_sz;
5804 const char *sec_name;
5807 for_each_btf_ext_sec(ext_info, sec) {
5808 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5811 if (strcmp(sec_name, prog->sec_name) != 0)
5814 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5815 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5817 if (insn_off < prog->sec_insn_off)
5819 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5824 copy_end = rec + ext_info->rec_size;
5830 /* append func/line info of a given (sub-)program to the main
5831 * program func/line info
5833 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5834 new_sz = old_sz + (copy_end - copy_start);
5835 new_prog_info = realloc(*prog_info, new_sz);
5838 *prog_info = new_prog_info;
5839 *prog_rec_cnt = new_sz / ext_info->rec_size;
5840 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5842 /* Kernel instruction offsets are in units of 8-byte
5843 * instructions, while .BTF.ext instruction offsets generated
5844 * by Clang are in units of bytes. So convert Clang offsets
5845 * into kernel offsets and adjust offset according to program
5846 * relocated position.
5848 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5849 rec = new_prog_info + old_sz;
5850 rec_end = new_prog_info + new_sz;
5851 for (; rec < rec_end; rec += ext_info->rec_size) {
5852 __u32 *insn_off = rec;
5854 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5856 *prog_rec_sz = ext_info->rec_size;
5864 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5865 struct bpf_program *main_prog,
5866 const struct bpf_program *prog)
5870 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5871 * supprot func/line info
5873 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5876 /* only attempt func info relocation if main program's func_info
5877 * relocation was successful
5879 if (main_prog != prog && !main_prog->func_info)
5882 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5883 &main_prog->func_info,
5884 &main_prog->func_info_cnt,
5885 &main_prog->func_info_rec_size);
5887 if (err != -ENOENT) {
5888 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5892 if (main_prog->func_info) {
5894 * Some info has already been found but has problem
5895 * in the last btf_ext reloc. Must have to error out.
5897 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5900 /* Have problem loading the very first info. Ignore the rest. */
5901 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5906 /* don't relocate line info if main program's relocation failed */
5907 if (main_prog != prog && !main_prog->line_info)
5910 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5911 &main_prog->line_info,
5912 &main_prog->line_info_cnt,
5913 &main_prog->line_info_rec_size);
5915 if (err != -ENOENT) {
5916 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5920 if (main_prog->line_info) {
5922 * Some info has already been found but has problem
5923 * in the last btf_ext reloc. Must have to error out.
5925 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5928 /* Have problem loading the very first info. Ignore the rest. */
5929 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5935 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5937 size_t insn_idx = *(const size_t *)key;
5938 const struct reloc_desc *relo = elem;
5940 if (insn_idx == relo->insn_idx)
5942 return insn_idx < relo->insn_idx ? -1 : 1;
5945 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5947 if (!prog->nr_reloc)
5949 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5950 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5953 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5955 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5956 struct reloc_desc *relos;
5959 if (main_prog == subprog)
5961 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5964 if (subprog->nr_reloc)
5965 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5966 sizeof(*relos) * subprog->nr_reloc);
5968 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5969 relos[i].insn_idx += subprog->sub_insn_off;
5970 /* After insn_idx adjustment the 'relos' array is still sorted
5971 * by insn_idx and doesn't break bsearch.
5973 main_prog->reloc_desc = relos;
5974 main_prog->nr_reloc = new_cnt;
5979 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5980 struct bpf_program *prog)
5982 size_t sub_insn_idx, insn_idx, new_cnt;
5983 struct bpf_program *subprog;
5984 struct bpf_insn *insns, *insn;
5985 struct reloc_desc *relo;
5988 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5992 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5993 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5994 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
5997 relo = find_prog_insn_relo(prog, insn_idx);
5998 if (relo && relo->type == RELO_EXTERN_FUNC)
5999 /* kfunc relocations will be handled later
6000 * in bpf_object__relocate_data()
6003 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6004 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6005 prog->name, insn_idx, relo->type);
6006 return -LIBBPF_ERRNO__RELOC;
6009 /* sub-program instruction index is a combination of
6010 * an offset of a symbol pointed to by relocation and
6011 * call instruction's imm field; for global functions,
6012 * call always has imm = -1, but for static functions
6013 * relocation is against STT_SECTION and insn->imm
6014 * points to a start of a static function
6016 * for subprog addr relocation, the relo->sym_off + insn->imm is
6017 * the byte offset in the corresponding section.
6019 if (relo->type == RELO_CALL)
6020 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6022 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6023 } else if (insn_is_pseudo_func(insn)) {
6025 * RELO_SUBPROG_ADDR relo is always emitted even if both
6026 * functions are in the same section, so it shouldn't reach here.
6028 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6029 prog->name, insn_idx);
6030 return -LIBBPF_ERRNO__RELOC;
6032 /* if subprogram call is to a static function within
6033 * the same ELF section, there won't be any relocation
6034 * emitted, but it also means there is no additional
6035 * offset necessary, insns->imm is relative to
6036 * instruction's original position within the section
6038 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6041 /* we enforce that sub-programs should be in .text section */
6042 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6044 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6046 return -LIBBPF_ERRNO__RELOC;
6049 /* if it's the first call instruction calling into this
6050 * subprogram (meaning this subprog hasn't been processed
6051 * yet) within the context of current main program:
6052 * - append it at the end of main program's instructions blog;
6053 * - process is recursively, while current program is put on hold;
6054 * - if that subprogram calls some other not yet processes
6055 * subprogram, same thing will happen recursively until
6056 * there are no more unprocesses subprograms left to append
6059 if (subprog->sub_insn_off == 0) {
6060 subprog->sub_insn_off = main_prog->insns_cnt;
6062 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6063 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6065 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6068 main_prog->insns = insns;
6069 main_prog->insns_cnt = new_cnt;
6071 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6072 subprog->insns_cnt * sizeof(*insns));
6074 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6075 main_prog->name, subprog->insns_cnt, subprog->name);
6077 /* The subprog insns are now appended. Append its relos too. */
6078 err = append_subprog_relos(main_prog, subprog);
6081 err = bpf_object__reloc_code(obj, main_prog, subprog);
6086 /* main_prog->insns memory could have been re-allocated, so
6087 * calculate pointer again
6089 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6090 /* calculate correct instruction position within current main
6091 * prog; each main prog can have a different set of
6092 * subprograms appended (potentially in different order as
6093 * well), so position of any subprog can be different for
6094 * different main programs */
6095 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6097 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6098 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6105 * Relocate sub-program calls.
6107 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6108 * main prog) is processed separately. For each subprog (non-entry functions,
6109 * that can be called from either entry progs or other subprogs) gets their
6110 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6111 * hasn't been yet appended and relocated within current main prog. Once its
6112 * relocated, sub_insn_off will point at the position within current main prog
6113 * where given subprog was appended. This will further be used to relocate all
6114 * the call instructions jumping into this subprog.
6116 * We start with main program and process all call instructions. If the call
6117 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6118 * is zero), subprog instructions are appended at the end of main program's
6119 * instruction array. Then main program is "put on hold" while we recursively
6120 * process newly appended subprogram. If that subprogram calls into another
6121 * subprogram that hasn't been appended, new subprogram is appended again to
6122 * the *main* prog's instructions (subprog's instructions are always left
6123 * untouched, as they need to be in unmodified state for subsequent main progs
6124 * and subprog instructions are always sent only as part of a main prog) and
6125 * the process continues recursively. Once all the subprogs called from a main
6126 * prog or any of its subprogs are appended (and relocated), all their
6127 * positions within finalized instructions array are known, so it's easy to
6128 * rewrite call instructions with correct relative offsets, corresponding to
6129 * desired target subprog.
6131 * Its important to realize that some subprogs might not be called from some
6132 * main prog and any of its called/used subprogs. Those will keep their
6133 * subprog->sub_insn_off as zero at all times and won't be appended to current
6134 * main prog and won't be relocated within the context of current main prog.
6135 * They might still be used from other main progs later.
6137 * Visually this process can be shown as below. Suppose we have two main
6138 * programs mainA and mainB and BPF object contains three subprogs: subA,
6139 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6140 * subC both call subB:
6142 * +--------+ +-------+
6144 * +--+---+ +--+-+-+ +---+--+
6145 * | subA | | subB | | subC |
6146 * +--+---+ +------+ +---+--+
6149 * +---+-------+ +------+----+
6150 * | mainA | | mainB |
6151 * +-----------+ +-----------+
6153 * We'll start relocating mainA, will find subA, append it and start
6154 * processing sub A recursively:
6156 * +-----------+------+
6158 * +-----------+------+
6160 * At this point we notice that subB is used from subA, so we append it and
6161 * relocate (there are no further subcalls from subB):
6163 * +-----------+------+------+
6164 * | mainA | subA | subB |
6165 * +-----------+------+------+
6167 * At this point, we relocate subA calls, then go one level up and finish with
6168 * relocatin mainA calls. mainA is done.
6170 * For mainB process is similar but results in different order. We start with
6171 * mainB and skip subA and subB, as mainB never calls them (at least
6172 * directly), but we see subC is needed, so we append and start processing it:
6174 * +-----------+------+
6176 * +-----------+------+
6177 * Now we see subC needs subB, so we go back to it, append and relocate it:
6179 * +-----------+------+------+
6180 * | mainB | subC | subB |
6181 * +-----------+------+------+
6183 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6186 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6188 struct bpf_program *subprog;
6191 /* mark all subprogs as not relocated (yet) within the context of
6192 * current main program
6194 for (i = 0; i < obj->nr_programs; i++) {
6195 subprog = &obj->programs[i];
6196 if (!prog_is_subprog(obj, subprog))
6199 subprog->sub_insn_off = 0;
6202 err = bpf_object__reloc_code(obj, prog, prog);
6211 bpf_object__free_relocs(struct bpf_object *obj)
6213 struct bpf_program *prog;
6216 /* free up relocation descriptors */
6217 for (i = 0; i < obj->nr_programs; i++) {
6218 prog = &obj->programs[i];
6219 zfree(&prog->reloc_desc);
6224 static int cmp_relocs(const void *_a, const void *_b)
6226 const struct reloc_desc *a = _a;
6227 const struct reloc_desc *b = _b;
6229 if (a->insn_idx != b->insn_idx)
6230 return a->insn_idx < b->insn_idx ? -1 : 1;
6232 /* no two relocations should have the same insn_idx, but ... */
6233 if (a->type != b->type)
6234 return a->type < b->type ? -1 : 1;
6239 static void bpf_object__sort_relos(struct bpf_object *obj)
6243 for (i = 0; i < obj->nr_programs; i++) {
6244 struct bpf_program *p = &obj->programs[i];
6249 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6254 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6256 struct bpf_program *prog;
6261 err = bpf_object__relocate_core(obj, targ_btf_path);
6263 pr_warn("failed to perform CO-RE relocations: %d\n",
6267 if (obj->gen_loader)
6268 bpf_object__sort_relos(obj);
6271 /* Before relocating calls pre-process relocations and mark
6272 * few ld_imm64 instructions that points to subprogs.
6273 * Otherwise bpf_object__reloc_code() later would have to consider
6274 * all ld_imm64 insns as relocation candidates. That would
6275 * reduce relocation speed, since amount of find_prog_insn_relo()
6276 * would increase and most of them will fail to find a relo.
6278 for (i = 0; i < obj->nr_programs; i++) {
6279 prog = &obj->programs[i];
6280 for (j = 0; j < prog->nr_reloc; j++) {
6281 struct reloc_desc *relo = &prog->reloc_desc[j];
6282 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6284 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6285 if (relo->type == RELO_SUBPROG_ADDR)
6286 insn[0].src_reg = BPF_PSEUDO_FUNC;
6290 /* relocate subprogram calls and append used subprograms to main
6291 * programs; each copy of subprogram code needs to be relocated
6292 * differently for each main program, because its code location might
6294 * Append subprog relos to main programs to allow data relos to be
6295 * processed after text is completely relocated.
6297 for (i = 0; i < obj->nr_programs; i++) {
6298 prog = &obj->programs[i];
6299 /* sub-program's sub-calls are relocated within the context of
6300 * its main program only
6302 if (prog_is_subprog(obj, prog))
6307 err = bpf_object__relocate_calls(obj, prog);
6309 pr_warn("prog '%s': failed to relocate calls: %d\n",
6314 /* Process data relos for main programs */
6315 for (i = 0; i < obj->nr_programs; i++) {
6316 prog = &obj->programs[i];
6317 if (prog_is_subprog(obj, prog))
6321 err = bpf_object__relocate_data(obj, prog);
6323 pr_warn("prog '%s': failed to relocate data references: %d\n",
6328 if (!obj->gen_loader)
6329 bpf_object__free_relocs(obj);
6333 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6334 Elf64_Shdr *shdr, Elf_Data *data);
6336 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6337 Elf64_Shdr *shdr, Elf_Data *data)
6339 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6340 int i, j, nrels, new_sz;
6341 const struct btf_var_secinfo *vi = NULL;
6342 const struct btf_type *sec, *var, *def;
6343 struct bpf_map *map = NULL, *targ_map = NULL;
6344 struct bpf_program *targ_prog = NULL;
6345 bool is_prog_array, is_map_in_map;
6346 const struct btf_member *member;
6347 const char *name, *mname, *type;
6353 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6355 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6359 nrels = shdr->sh_size / shdr->sh_entsize;
6360 for (i = 0; i < nrels; i++) {
6361 rel = elf_rel_by_idx(data, i);
6363 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6364 return -LIBBPF_ERRNO__FORMAT;
6367 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6369 pr_warn(".maps relo #%d: symbol %zx not found\n",
6370 i, (size_t)ELF64_R_SYM(rel->r_info));
6371 return -LIBBPF_ERRNO__FORMAT;
6373 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6375 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6376 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6377 (size_t)rel->r_offset, sym->st_name, name);
6379 for (j = 0; j < obj->nr_maps; j++) {
6380 map = &obj->maps[j];
6381 if (map->sec_idx != obj->efile.btf_maps_shndx)
6384 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6385 if (vi->offset <= rel->r_offset &&
6386 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6389 if (j == obj->nr_maps) {
6390 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6391 i, name, (size_t)rel->r_offset);
6395 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6396 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6397 type = is_map_in_map ? "map" : "prog";
6398 if (is_map_in_map) {
6399 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6400 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6402 return -LIBBPF_ERRNO__RELOC;
6404 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6405 map->def.key_size != sizeof(int)) {
6406 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6407 i, map->name, sizeof(int));
6410 targ_map = bpf_object__find_map_by_name(obj, name);
6412 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6416 } else if (is_prog_array) {
6417 targ_prog = bpf_object__find_program_by_name(obj, name);
6419 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6423 if (targ_prog->sec_idx != sym->st_shndx ||
6424 targ_prog->sec_insn_off * 8 != sym->st_value ||
6425 prog_is_subprog(obj, targ_prog)) {
6426 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6428 return -LIBBPF_ERRNO__RELOC;
6434 var = btf__type_by_id(obj->btf, vi->type);
6435 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6436 if (btf_vlen(def) == 0)
6438 member = btf_members(def) + btf_vlen(def) - 1;
6439 mname = btf__name_by_offset(obj->btf, member->name_off);
6440 if (strcmp(mname, "values"))
6443 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6444 if (rel->r_offset - vi->offset < moff)
6447 moff = rel->r_offset - vi->offset - moff;
6448 /* here we use BPF pointer size, which is always 64 bit, as we
6449 * are parsing ELF that was built for BPF target
6451 if (moff % bpf_ptr_sz)
6454 if (moff >= map->init_slots_sz) {
6456 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6459 map->init_slots = tmp;
6460 memset(map->init_slots + map->init_slots_sz, 0,
6461 (new_sz - map->init_slots_sz) * host_ptr_sz);
6462 map->init_slots_sz = new_sz;
6464 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6466 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6467 i, map->name, moff, type, name);
6473 static int bpf_object__collect_relos(struct bpf_object *obj)
6477 for (i = 0; i < obj->efile.sec_cnt; i++) {
6478 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6483 if (sec_desc->sec_type != SEC_RELO)
6486 shdr = sec_desc->shdr;
6487 data = sec_desc->data;
6488 idx = shdr->sh_info;
6490 if (shdr->sh_type != SHT_REL) {
6491 pr_warn("internal error at %d\n", __LINE__);
6492 return -LIBBPF_ERRNO__INTERNAL;
6495 if (idx == obj->efile.st_ops_shndx)
6496 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6497 else if (idx == obj->efile.btf_maps_shndx)
6498 err = bpf_object__collect_map_relos(obj, shdr, data);
6500 err = bpf_object__collect_prog_relos(obj, shdr, data);
6505 bpf_object__sort_relos(obj);
6509 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6511 if (BPF_CLASS(insn->code) == BPF_JMP &&
6512 BPF_OP(insn->code) == BPF_CALL &&
6513 BPF_SRC(insn->code) == BPF_K &&
6514 insn->src_reg == 0 &&
6515 insn->dst_reg == 0) {
6516 *func_id = insn->imm;
6522 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6524 struct bpf_insn *insn = prog->insns;
6525 enum bpf_func_id func_id;
6528 if (obj->gen_loader)
6531 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6532 if (!insn_is_helper_call(insn, &func_id))
6535 /* on kernels that don't yet support
6536 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6537 * to bpf_probe_read() which works well for old kernels
6540 case BPF_FUNC_probe_read_kernel:
6541 case BPF_FUNC_probe_read_user:
6542 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6543 insn->imm = BPF_FUNC_probe_read;
6545 case BPF_FUNC_probe_read_kernel_str:
6546 case BPF_FUNC_probe_read_user_str:
6547 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6548 insn->imm = BPF_FUNC_probe_read_str;
6557 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6558 int *btf_obj_fd, int *btf_type_id);
6560 /* this is called as prog->sec_def->preload_fn for libbpf-supported sec_defs */
6561 static int libbpf_preload_prog(struct bpf_program *prog,
6562 struct bpf_prog_load_opts *opts, long cookie)
6564 enum sec_def_flags def = cookie;
6566 /* old kernels might not support specifying expected_attach_type */
6567 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6568 opts->expected_attach_type = 0;
6570 if (def & SEC_SLEEPABLE)
6571 opts->prog_flags |= BPF_F_SLEEPABLE;
6573 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6574 prog->type == BPF_PROG_TYPE_LSM ||
6575 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6576 int btf_obj_fd = 0, btf_type_id = 0, err;
6577 const char *attach_name;
6579 attach_name = strchr(prog->sec_name, '/') + 1;
6580 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6584 /* cache resolved BTF FD and BTF type ID in the prog */
6585 prog->attach_btf_obj_fd = btf_obj_fd;
6586 prog->attach_btf_id = btf_type_id;
6588 /* but by now libbpf common logic is not utilizing
6589 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6590 * this callback is called after opts were populated by
6591 * libbpf, so this callback has to update opts explicitly here
6593 opts->attach_btf_obj_fd = btf_obj_fd;
6594 opts->attach_btf_id = btf_type_id;
6599 static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6600 struct bpf_insn *insns, int insns_cnt,
6601 const char *license, __u32 kern_version,
6604 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6605 const char *prog_name = NULL;
6606 char *cp, errmsg[STRERR_BUFSIZE];
6607 size_t log_buf_size = 0;
6608 char *log_buf = NULL, *tmp;
6609 int btf_fd, ret, err;
6610 bool own_log_buf = true;
6611 __u32 log_level = prog->log_level;
6613 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6615 * The program type must be set. Most likely we couldn't find a proper
6616 * section definition at load time, and thus we didn't infer the type.
6618 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6619 prog->name, prog->sec_name);
6623 if (!insns || !insns_cnt)
6626 load_attr.expected_attach_type = prog->expected_attach_type;
6627 if (kernel_supports(obj, FEAT_PROG_NAME))
6628 prog_name = prog->name;
6629 load_attr.attach_prog_fd = prog->attach_prog_fd;
6630 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6631 load_attr.attach_btf_id = prog->attach_btf_id;
6632 load_attr.kern_version = kern_version;
6633 load_attr.prog_ifindex = prog->prog_ifindex;
6635 /* specify func_info/line_info only if kernel supports them */
6636 btf_fd = bpf_object__btf_fd(obj);
6637 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6638 load_attr.prog_btf_fd = btf_fd;
6639 load_attr.func_info = prog->func_info;
6640 load_attr.func_info_rec_size = prog->func_info_rec_size;
6641 load_attr.func_info_cnt = prog->func_info_cnt;
6642 load_attr.line_info = prog->line_info;
6643 load_attr.line_info_rec_size = prog->line_info_rec_size;
6644 load_attr.line_info_cnt = prog->line_info_cnt;
6646 load_attr.log_level = log_level;
6647 load_attr.prog_flags = prog->prog_flags;
6648 load_attr.fd_array = obj->fd_array;
6650 /* adjust load_attr if sec_def provides custom preload callback */
6651 if (prog->sec_def && prog->sec_def->preload_fn) {
6652 err = prog->sec_def->preload_fn(prog, &load_attr, prog->sec_def->cookie);
6654 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6660 if (obj->gen_loader) {
6661 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6662 license, insns, insns_cnt, &load_attr,
6663 prog - obj->programs);
6669 /* if log_level is zero, we don't request logs initiallly even if
6670 * custom log_buf is specified; if the program load fails, then we'll
6671 * bump log_level to 1 and use either custom log_buf or we'll allocate
6672 * our own and retry the load to get details on what failed
6675 if (prog->log_buf) {
6676 log_buf = prog->log_buf;
6677 log_buf_size = prog->log_size;
6678 own_log_buf = false;
6679 } else if (obj->log_buf) {
6680 log_buf = obj->log_buf;
6681 log_buf_size = obj->log_size;
6682 own_log_buf = false;
6684 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6685 tmp = realloc(log_buf, log_buf_size);
6696 load_attr.log_buf = log_buf;
6697 load_attr.log_size = log_buf_size;
6698 load_attr.log_level = log_level;
6700 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6702 if (log_level && own_log_buf) {
6703 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6704 prog->name, log_buf);
6707 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6708 struct bpf_map *map;
6711 for (i = 0; i < obj->nr_maps; i++) {
6712 map = &prog->obj->maps[i];
6713 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6716 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6717 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6718 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6719 prog->name, map->real_name, cp);
6720 /* Don't fail hard if can't bind rodata. */
6730 if (log_level == 0) {
6734 /* On ENOSPC, increase log buffer size and retry, unless custom
6735 * log_buf is specified.
6736 * Be careful to not overflow u32, though. Kernel's log buf size limit
6737 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6738 * multiply by 2 unless we are sure we'll fit within 32 bits.
6739 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6741 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6745 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6746 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6749 if (own_log_buf && log_buf && log_buf[0] != '\0') {
6750 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6751 prog->name, log_buf);
6753 if (insns_cnt >= BPF_MAXINSNS) {
6754 pr_warn("prog '%s': program too large (%d insns), at most %d insns\n",
6755 prog->name, insns_cnt, BPF_MAXINSNS);
6764 static int bpf_program_record_relos(struct bpf_program *prog)
6766 struct bpf_object *obj = prog->obj;
6769 for (i = 0; i < prog->nr_reloc; i++) {
6770 struct reloc_desc *relo = &prog->reloc_desc[i];
6771 struct extern_desc *ext = &obj->externs[relo->sym_off];
6773 switch (relo->type) {
6774 case RELO_EXTERN_VAR:
6775 if (ext->type != EXT_KSYM)
6777 bpf_gen__record_extern(obj->gen_loader, ext->name,
6778 ext->is_weak, !ext->ksym.type_id,
6779 BTF_KIND_VAR, relo->insn_idx);
6781 case RELO_EXTERN_FUNC:
6782 bpf_gen__record_extern(obj->gen_loader, ext->name,
6783 ext->is_weak, false, BTF_KIND_FUNC,
6787 struct bpf_core_relo cr = {
6788 .insn_off = relo->insn_idx * 8,
6789 .type_id = relo->core_relo->type_id,
6790 .access_str_off = relo->core_relo->access_str_off,
6791 .kind = relo->core_relo->kind,
6794 bpf_gen__record_relo_core(obj->gen_loader, &cr);
6804 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6805 const char *license, __u32 kern_ver)
6810 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6811 return libbpf_err(-EINVAL);
6814 if (prog->instances.nr < 0 || !prog->instances.fds) {
6815 if (prog->preprocessor) {
6816 pr_warn("Internal error: can't load program '%s'\n",
6818 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
6821 prog->instances.fds = malloc(sizeof(int));
6822 if (!prog->instances.fds) {
6823 pr_warn("Not enough memory for BPF fds\n");
6824 return libbpf_err(-ENOMEM);
6826 prog->instances.nr = 1;
6827 prog->instances.fds[0] = -1;
6830 if (!prog->preprocessor) {
6831 if (prog->instances.nr != 1) {
6832 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6833 prog->name, prog->instances.nr);
6835 if (obj->gen_loader)
6836 bpf_program_record_relos(prog);
6837 err = bpf_object_load_prog_instance(obj, prog,
6838 prog->insns, prog->insns_cnt,
6839 license, kern_ver, &fd);
6841 prog->instances.fds[0] = fd;
6845 for (i = 0; i < prog->instances.nr; i++) {
6846 struct bpf_prog_prep_result result;
6847 bpf_program_prep_t preprocessor = prog->preprocessor;
6849 memset(&result, 0, sizeof(result));
6850 err = preprocessor(prog, i, prog->insns,
6851 prog->insns_cnt, &result);
6853 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6858 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6859 pr_debug("Skip loading the %dth instance of program '%s'\n",
6861 prog->instances.fds[i] = -1;
6867 err = bpf_object_load_prog_instance(obj, prog,
6868 result.new_insn_ptr, result.new_insn_cnt,
6869 license, kern_ver, &fd);
6871 pr_warn("Loading the %dth instance of program '%s' failed\n",
6878 prog->instances.fds[i] = fd;
6882 pr_warn("failed to load program '%s'\n", prog->name);
6883 return libbpf_err(err);
6886 int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
6888 return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
6892 bpf_object__load_progs(struct bpf_object *obj, int log_level)
6894 struct bpf_program *prog;
6898 for (i = 0; i < obj->nr_programs; i++) {
6899 prog = &obj->programs[i];
6900 err = bpf_object__sanitize_prog(obj, prog);
6905 for (i = 0; i < obj->nr_programs; i++) {
6906 prog = &obj->programs[i];
6907 if (prog_is_subprog(obj, prog))
6910 pr_debug("prog '%s': skipped loading\n", prog->name);
6913 prog->log_level |= log_level;
6914 err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
6918 if (obj->gen_loader)
6919 bpf_object__free_relocs(obj);
6923 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6925 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
6927 struct bpf_program *prog;
6930 bpf_object__for_each_program(prog, obj) {
6931 prog->sec_def = find_sec_def(prog->sec_name);
6932 if (!prog->sec_def) {
6933 /* couldn't guess, but user might manually specify */
6934 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6935 prog->name, prog->sec_name);
6939 bpf_program__set_type(prog, prog->sec_def->prog_type);
6940 bpf_program__set_expected_attach_type(prog, prog->sec_def->expected_attach_type);
6942 #pragma GCC diagnostic push
6943 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
6944 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6945 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6946 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6947 #pragma GCC diagnostic pop
6949 /* sec_def can have custom callback which should be called
6950 * after bpf_program is initialized to adjust its properties
6952 if (prog->sec_def->init_fn) {
6953 err = prog->sec_def->init_fn(prog, prog->sec_def->cookie);
6955 pr_warn("prog '%s': failed to initialize: %d\n",
6965 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6966 const struct bpf_object_open_opts *opts)
6968 const char *obj_name, *kconfig, *btf_tmp_path;
6969 struct bpf_object *obj;
6976 if (elf_version(EV_CURRENT) == EV_NONE) {
6977 pr_warn("failed to init libelf for %s\n",
6978 path ? : "(mem buf)");
6979 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6982 if (!OPTS_VALID(opts, bpf_object_open_opts))
6983 return ERR_PTR(-EINVAL);
6985 obj_name = OPTS_GET(opts, object_name, NULL);
6988 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6989 (unsigned long)obj_buf,
6990 (unsigned long)obj_buf_sz);
6991 obj_name = tmp_name;
6994 pr_debug("loading object '%s' from buffer\n", obj_name);
6997 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
6998 log_size = OPTS_GET(opts, kernel_log_size, 0);
6999 log_level = OPTS_GET(opts, kernel_log_level, 0);
7000 if (log_size > UINT_MAX)
7001 return ERR_PTR(-EINVAL);
7002 if (log_size && !log_buf)
7003 return ERR_PTR(-EINVAL);
7005 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7009 obj->log_buf = log_buf;
7010 obj->log_size = log_size;
7011 obj->log_level = log_level;
7013 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7015 if (strlen(btf_tmp_path) >= PATH_MAX) {
7016 err = -ENAMETOOLONG;
7019 obj->btf_custom_path = strdup(btf_tmp_path);
7020 if (!obj->btf_custom_path) {
7026 kconfig = OPTS_GET(opts, kconfig, NULL);
7028 obj->kconfig = strdup(kconfig);
7029 if (!obj->kconfig) {
7035 err = bpf_object__elf_init(obj);
7036 err = err ? : bpf_object__check_endianness(obj);
7037 err = err ? : bpf_object__elf_collect(obj);
7038 err = err ? : bpf_object__collect_externs(obj);
7039 err = err ? : bpf_object__finalize_btf(obj);
7040 err = err ? : bpf_object__init_maps(obj, opts);
7041 err = err ? : bpf_object_init_progs(obj, opts);
7042 err = err ? : bpf_object__collect_relos(obj);
7046 bpf_object__elf_finish(obj);
7050 bpf_object__close(obj);
7051 return ERR_PTR(err);
7054 static struct bpf_object *
7055 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
7057 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7058 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
7061 /* param validation */
7065 pr_debug("loading %s\n", attr->file);
7066 return bpf_object_open(attr->file, NULL, 0, &opts);
7069 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7071 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
7074 struct bpf_object *bpf_object__open(const char *path)
7076 struct bpf_object_open_attr attr = {
7078 .prog_type = BPF_PROG_TYPE_UNSPEC,
7081 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
7085 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7088 return libbpf_err_ptr(-EINVAL);
7090 pr_debug("loading %s\n", path);
7092 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7096 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7097 const struct bpf_object_open_opts *opts)
7099 if (!obj_buf || obj_buf_sz == 0)
7100 return libbpf_err_ptr(-EINVAL);
7102 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7106 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7109 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7110 .object_name = name,
7111 /* wrong default, but backwards-compatible */
7112 .relaxed_maps = true,
7115 /* returning NULL is wrong, but backwards-compatible */
7116 if (!obj_buf || obj_buf_sz == 0)
7117 return errno = EINVAL, NULL;
7119 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
7122 static int bpf_object_unload(struct bpf_object *obj)
7127 return libbpf_err(-EINVAL);
7129 for (i = 0; i < obj->nr_maps; i++) {
7130 zclose(obj->maps[i].fd);
7131 if (obj->maps[i].st_ops)
7132 zfree(&obj->maps[i].st_ops->kern_vdata);
7135 for (i = 0; i < obj->nr_programs; i++)
7136 bpf_program__unload(&obj->programs[i]);
7141 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7143 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7147 bpf_object__for_each_map(m, obj) {
7148 if (!bpf_map__is_internal(m))
7150 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7151 m->def.map_flags ^= BPF_F_MMAPABLE;
7157 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7159 char sym_type, sym_name[500];
7160 unsigned long long sym_addr;
7161 const struct btf_type *t;
7162 struct extern_desc *ext;
7166 f = fopen("/proc/kallsyms", "r");
7169 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7174 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7175 &sym_addr, &sym_type, sym_name);
7176 if (ret == EOF && feof(f))
7179 pr_warn("failed to read kallsyms entry: %d\n", ret);
7184 ext = find_extern_by_name(obj, sym_name);
7185 if (!ext || ext->type != EXT_KSYM)
7188 t = btf__type_by_id(obj->btf, ext->btf_id);
7192 if (ext->is_set && ext->ksym.addr != sym_addr) {
7193 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7194 sym_name, ext->ksym.addr, sym_addr);
7200 ext->ksym.addr = sym_addr;
7201 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7210 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7211 __u16 kind, struct btf **res_btf,
7212 struct module_btf **res_mod_btf)
7214 struct module_btf *mod_btf;
7218 btf = obj->btf_vmlinux;
7220 id = btf__find_by_name_kind(btf, ksym_name, kind);
7222 if (id == -ENOENT) {
7223 err = load_module_btfs(obj);
7227 for (i = 0; i < obj->btf_module_cnt; i++) {
7228 /* we assume module_btf's BTF FD is always >0 */
7229 mod_btf = &obj->btf_modules[i];
7231 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7240 *res_mod_btf = mod_btf;
7244 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7245 struct extern_desc *ext)
7247 const struct btf_type *targ_var, *targ_type;
7248 __u32 targ_type_id, local_type_id;
7249 struct module_btf *mod_btf = NULL;
7250 const char *targ_var_name;
7251 struct btf *btf = NULL;
7254 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7256 if (id == -ESRCH && ext->is_weak)
7258 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7263 /* find local type_id */
7264 local_type_id = ext->ksym.type_id;
7266 /* find target type_id */
7267 targ_var = btf__type_by_id(btf, id);
7268 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7269 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7271 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7274 const struct btf_type *local_type;
7275 const char *targ_name, *local_name;
7277 local_type = btf__type_by_id(obj->btf, local_type_id);
7278 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7279 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7281 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7282 ext->name, local_type_id,
7283 btf_kind_str(local_type), local_name, targ_type_id,
7284 btf_kind_str(targ_type), targ_name);
7289 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7290 ext->ksym.kernel_btf_id = id;
7291 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7292 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7297 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7298 struct extern_desc *ext)
7300 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7301 struct module_btf *mod_btf = NULL;
7302 const struct btf_type *kern_func;
7303 struct btf *kern_btf = NULL;
7306 local_func_proto_id = ext->ksym.type_id;
7308 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7310 if (kfunc_id == -ESRCH && ext->is_weak)
7312 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7317 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7318 kfunc_proto_id = kern_func->type;
7320 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7321 kern_btf, kfunc_proto_id);
7323 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7324 ext->name, local_func_proto_id, kfunc_proto_id);
7328 /* set index for module BTF fd in fd_array, if unset */
7329 if (mod_btf && !mod_btf->fd_array_idx) {
7330 /* insn->off is s16 */
7331 if (obj->fd_array_cnt == INT16_MAX) {
7332 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7333 ext->name, mod_btf->fd_array_idx);
7336 /* Cannot use index 0 for module BTF fd */
7337 if (!obj->fd_array_cnt)
7338 obj->fd_array_cnt = 1;
7340 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7341 obj->fd_array_cnt + 1);
7344 mod_btf->fd_array_idx = obj->fd_array_cnt;
7345 /* we assume module BTF FD is always >0 */
7346 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7350 ext->ksym.kernel_btf_id = kfunc_id;
7351 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7352 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7353 ext->name, kfunc_id);
7358 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7360 const struct btf_type *t;
7361 struct extern_desc *ext;
7364 for (i = 0; i < obj->nr_extern; i++) {
7365 ext = &obj->externs[i];
7366 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7369 if (obj->gen_loader) {
7371 ext->ksym.kernel_btf_obj_fd = 0;
7372 ext->ksym.kernel_btf_id = 0;
7375 t = btf__type_by_id(obj->btf, ext->btf_id);
7377 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7379 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7386 static int bpf_object__resolve_externs(struct bpf_object *obj,
7387 const char *extra_kconfig)
7389 bool need_config = false, need_kallsyms = false;
7390 bool need_vmlinux_btf = false;
7391 struct extern_desc *ext;
7392 void *kcfg_data = NULL;
7395 if (obj->nr_extern == 0)
7398 if (obj->kconfig_map_idx >= 0)
7399 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7401 for (i = 0; i < obj->nr_extern; i++) {
7402 ext = &obj->externs[i];
7404 if (ext->type == EXT_KCFG &&
7405 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7406 void *ext_val = kcfg_data + ext->kcfg.data_off;
7407 __u32 kver = get_kernel_version();
7410 pr_warn("failed to get kernel version\n");
7413 err = set_kcfg_value_num(ext, ext_val, kver);
7416 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
7417 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
7419 } else if (ext->type == EXT_KSYM) {
7420 if (ext->ksym.type_id)
7421 need_vmlinux_btf = true;
7423 need_kallsyms = true;
7425 pr_warn("unrecognized extern '%s'\n", ext->name);
7429 if (need_config && extra_kconfig) {
7430 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7433 need_config = false;
7434 for (i = 0; i < obj->nr_extern; i++) {
7435 ext = &obj->externs[i];
7436 if (ext->type == EXT_KCFG && !ext->is_set) {
7443 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7447 if (need_kallsyms) {
7448 err = bpf_object__read_kallsyms_file(obj);
7452 if (need_vmlinux_btf) {
7453 err = bpf_object__resolve_ksyms_btf_id(obj);
7457 for (i = 0; i < obj->nr_extern; i++) {
7458 ext = &obj->externs[i];
7460 if (!ext->is_set && !ext->is_weak) {
7461 pr_warn("extern %s (strong) not resolved\n", ext->name);
7463 } else if (!ext->is_set) {
7464 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7472 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7477 return libbpf_err(-EINVAL);
7480 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7481 return libbpf_err(-EINVAL);
7484 if (obj->gen_loader)
7485 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7487 err = bpf_object__probe_loading(obj);
7488 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7489 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7490 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7491 err = err ? : bpf_object__sanitize_maps(obj);
7492 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7493 err = err ? : bpf_object__create_maps(obj);
7494 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7495 err = err ? : bpf_object__load_progs(obj, extra_log_level);
7496 err = err ? : bpf_object_init_prog_arrays(obj);
7498 if (obj->gen_loader) {
7501 btf__set_fd(obj->btf, -1);
7502 for (i = 0; i < obj->nr_maps; i++)
7503 obj->maps[i].fd = -1;
7505 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7508 /* clean up fd_array */
7509 zfree(&obj->fd_array);
7511 /* clean up module BTFs */
7512 for (i = 0; i < obj->btf_module_cnt; i++) {
7513 close(obj->btf_modules[i].fd);
7514 btf__free(obj->btf_modules[i].btf);
7515 free(obj->btf_modules[i].name);
7517 free(obj->btf_modules);
7519 /* clean up vmlinux BTF */
7520 btf__free(obj->btf_vmlinux);
7521 obj->btf_vmlinux = NULL;
7523 obj->loaded = true; /* doesn't matter if successfully or not */
7530 /* unpin any maps that were auto-pinned during load */
7531 for (i = 0; i < obj->nr_maps; i++)
7532 if (obj->maps[i].pinned && !obj->maps[i].reused)
7533 bpf_map__unpin(&obj->maps[i], NULL);
7535 bpf_object_unload(obj);
7536 pr_warn("failed to load object '%s'\n", obj->path);
7537 return libbpf_err(err);
7540 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
7542 return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
7545 int bpf_object__load(struct bpf_object *obj)
7547 return bpf_object_load(obj, 0, NULL);
7550 static int make_parent_dir(const char *path)
7552 char *cp, errmsg[STRERR_BUFSIZE];
7556 dname = strdup(path);
7560 dir = dirname(dname);
7561 if (mkdir(dir, 0700) && errno != EEXIST)
7566 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7567 pr_warn("failed to mkdir %s: %s\n", path, cp);
7572 static int check_path(const char *path)
7574 char *cp, errmsg[STRERR_BUFSIZE];
7575 struct statfs st_fs;
7582 dname = strdup(path);
7586 dir = dirname(dname);
7587 if (statfs(dir, &st_fs)) {
7588 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7589 pr_warn("failed to statfs %s: %s\n", dir, cp);
7594 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7595 pr_warn("specified path %s is not on BPF FS\n", path);
7602 static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
7604 char *cp, errmsg[STRERR_BUFSIZE];
7607 err = make_parent_dir(path);
7609 return libbpf_err(err);
7611 err = check_path(path);
7613 return libbpf_err(err);
7616 pr_warn("invalid program pointer\n");
7617 return libbpf_err(-EINVAL);
7620 if (instance < 0 || instance >= prog->instances.nr) {
7621 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7622 instance, prog->name, prog->instances.nr);
7623 return libbpf_err(-EINVAL);
7626 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
7628 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7629 pr_warn("failed to pin program: %s\n", cp);
7630 return libbpf_err(err);
7632 pr_debug("pinned program '%s'\n", path);
7637 static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
7641 err = check_path(path);
7643 return libbpf_err(err);
7646 pr_warn("invalid program pointer\n");
7647 return libbpf_err(-EINVAL);
7650 if (instance < 0 || instance >= prog->instances.nr) {
7651 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7652 instance, prog->name, prog->instances.nr);
7653 return libbpf_err(-EINVAL);
7658 return libbpf_err(-errno);
7660 pr_debug("unpinned program '%s'\n", path);
7665 __attribute__((alias("bpf_program_pin_instance")))
7666 int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
7668 __attribute__((alias("bpf_program_unpin_instance")))
7669 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
7671 int bpf_program__pin(struct bpf_program *prog, const char *path)
7675 err = make_parent_dir(path);
7677 return libbpf_err(err);
7679 err = check_path(path);
7681 return libbpf_err(err);
7684 pr_warn("invalid program pointer\n");
7685 return libbpf_err(-EINVAL);
7688 if (prog->instances.nr <= 0) {
7689 pr_warn("no instances of prog %s to pin\n", prog->name);
7690 return libbpf_err(-EINVAL);
7693 if (prog->instances.nr == 1) {
7694 /* don't create subdirs when pinning single instance */
7695 return bpf_program_pin_instance(prog, path, 0);
7698 for (i = 0; i < prog->instances.nr; i++) {
7702 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7706 } else if (len >= PATH_MAX) {
7707 err = -ENAMETOOLONG;
7711 err = bpf_program_pin_instance(prog, buf, i);
7719 for (i = i - 1; i >= 0; i--) {
7723 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7726 else if (len >= PATH_MAX)
7729 bpf_program_unpin_instance(prog, buf, i);
7734 return libbpf_err(err);
7737 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7741 err = check_path(path);
7743 return libbpf_err(err);
7746 pr_warn("invalid program pointer\n");
7747 return libbpf_err(-EINVAL);
7750 if (prog->instances.nr <= 0) {
7751 pr_warn("no instances of prog %s to pin\n", prog->name);
7752 return libbpf_err(-EINVAL);
7755 if (prog->instances.nr == 1) {
7756 /* don't create subdirs when pinning single instance */
7757 return bpf_program_unpin_instance(prog, path, 0);
7760 for (i = 0; i < prog->instances.nr; i++) {
7764 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7766 return libbpf_err(-EINVAL);
7767 else if (len >= PATH_MAX)
7768 return libbpf_err(-ENAMETOOLONG);
7770 err = bpf_program_unpin_instance(prog, buf, i);
7777 return libbpf_err(-errno);
7782 int bpf_map__pin(struct bpf_map *map, const char *path)
7784 char *cp, errmsg[STRERR_BUFSIZE];
7788 pr_warn("invalid map pointer\n");
7789 return libbpf_err(-EINVAL);
7792 if (map->pin_path) {
7793 if (path && strcmp(path, map->pin_path)) {
7794 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7795 bpf_map__name(map), map->pin_path, path);
7796 return libbpf_err(-EINVAL);
7797 } else if (map->pinned) {
7798 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7799 bpf_map__name(map), map->pin_path);
7804 pr_warn("missing a path to pin map '%s' at\n",
7805 bpf_map__name(map));
7806 return libbpf_err(-EINVAL);
7807 } else if (map->pinned) {
7808 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7809 return libbpf_err(-EEXIST);
7812 map->pin_path = strdup(path);
7813 if (!map->pin_path) {
7819 err = make_parent_dir(map->pin_path);
7821 return libbpf_err(err);
7823 err = check_path(map->pin_path);
7825 return libbpf_err(err);
7827 if (bpf_obj_pin(map->fd, map->pin_path)) {
7833 pr_debug("pinned map '%s'\n", map->pin_path);
7838 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7839 pr_warn("failed to pin map: %s\n", cp);
7840 return libbpf_err(err);
7843 int bpf_map__unpin(struct bpf_map *map, const char *path)
7848 pr_warn("invalid map pointer\n");
7849 return libbpf_err(-EINVAL);
7852 if (map->pin_path) {
7853 if (path && strcmp(path, map->pin_path)) {
7854 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7855 bpf_map__name(map), map->pin_path, path);
7856 return libbpf_err(-EINVAL);
7858 path = map->pin_path;
7860 pr_warn("no path to unpin map '%s' from\n",
7861 bpf_map__name(map));
7862 return libbpf_err(-EINVAL);
7865 err = check_path(path);
7867 return libbpf_err(err);
7871 return libbpf_err(-errno);
7873 map->pinned = false;
7874 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7879 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7886 return libbpf_err(-errno);
7889 free(map->pin_path);
7890 map->pin_path = new;
7894 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7896 return map->pin_path;
7899 const char *bpf_map__pin_path(const struct bpf_map *map)
7901 return map->pin_path;
7904 bool bpf_map__is_pinned(const struct bpf_map *map)
7909 static void sanitize_pin_path(char *s)
7911 /* bpffs disallows periods in path names */
7919 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7921 struct bpf_map *map;
7925 return libbpf_err(-ENOENT);
7928 pr_warn("object not yet loaded; load it first\n");
7929 return libbpf_err(-ENOENT);
7932 bpf_object__for_each_map(map, obj) {
7933 char *pin_path = NULL;
7942 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7943 bpf_map__name(map));
7946 goto err_unpin_maps;
7947 } else if (len >= PATH_MAX) {
7948 err = -ENAMETOOLONG;
7949 goto err_unpin_maps;
7951 sanitize_pin_path(buf);
7953 } else if (!map->pin_path) {
7957 err = bpf_map__pin(map, pin_path);
7959 goto err_unpin_maps;
7965 while ((map = bpf_object__prev_map(obj, map))) {
7969 bpf_map__unpin(map, NULL);
7972 return libbpf_err(err);
7975 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7977 struct bpf_map *map;
7981 return libbpf_err(-ENOENT);
7983 bpf_object__for_each_map(map, obj) {
7984 char *pin_path = NULL;
7990 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7991 bpf_map__name(map));
7993 return libbpf_err(-EINVAL);
7994 else if (len >= PATH_MAX)
7995 return libbpf_err(-ENAMETOOLONG);
7996 sanitize_pin_path(buf);
7998 } else if (!map->pin_path) {
8002 err = bpf_map__unpin(map, pin_path);
8004 return libbpf_err(err);
8010 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8012 struct bpf_program *prog;
8016 return libbpf_err(-ENOENT);
8019 pr_warn("object not yet loaded; load it first\n");
8020 return libbpf_err(-ENOENT);
8023 bpf_object__for_each_program(prog, obj) {
8027 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8031 goto err_unpin_programs;
8032 } else if (len >= PATH_MAX) {
8033 err = -ENAMETOOLONG;
8034 goto err_unpin_programs;
8037 err = bpf_program__pin(prog, buf);
8039 goto err_unpin_programs;
8045 while ((prog = bpf_object__prev_program(obj, prog))) {
8049 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8053 else if (len >= PATH_MAX)
8056 bpf_program__unpin(prog, buf);
8059 return libbpf_err(err);
8062 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8064 struct bpf_program *prog;
8068 return libbpf_err(-ENOENT);
8070 bpf_object__for_each_program(prog, obj) {
8074 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8077 return libbpf_err(-EINVAL);
8078 else if (len >= PATH_MAX)
8079 return libbpf_err(-ENAMETOOLONG);
8081 err = bpf_program__unpin(prog, buf);
8083 return libbpf_err(err);
8089 int bpf_object__pin(struct bpf_object *obj, const char *path)
8093 err = bpf_object__pin_maps(obj, path);
8095 return libbpf_err(err);
8097 err = bpf_object__pin_programs(obj, path);
8099 bpf_object__unpin_maps(obj, path);
8100 return libbpf_err(err);
8106 static void bpf_map__destroy(struct bpf_map *map)
8108 if (map->clear_priv)
8109 map->clear_priv(map, map->priv);
8111 map->clear_priv = NULL;
8113 if (map->inner_map) {
8114 bpf_map__destroy(map->inner_map);
8115 zfree(&map->inner_map);
8118 zfree(&map->init_slots);
8119 map->init_slots_sz = 0;
8122 munmap(map->mmaped, bpf_map_mmap_sz(map));
8127 zfree(&map->st_ops->data);
8128 zfree(&map->st_ops->progs);
8129 zfree(&map->st_ops->kern_func_off);
8130 zfree(&map->st_ops);
8134 zfree(&map->real_name);
8135 zfree(&map->pin_path);
8141 void bpf_object__close(struct bpf_object *obj)
8145 if (IS_ERR_OR_NULL(obj))
8148 if (obj->clear_priv)
8149 obj->clear_priv(obj, obj->priv);
8151 bpf_gen__free(obj->gen_loader);
8152 bpf_object__elf_finish(obj);
8153 bpf_object_unload(obj);
8154 btf__free(obj->btf);
8155 btf_ext__free(obj->btf_ext);
8157 for (i = 0; i < obj->nr_maps; i++)
8158 bpf_map__destroy(&obj->maps[i]);
8160 zfree(&obj->btf_custom_path);
8161 zfree(&obj->kconfig);
8162 zfree(&obj->externs);
8168 if (obj->programs && obj->nr_programs) {
8169 for (i = 0; i < obj->nr_programs; i++)
8170 bpf_program__exit(&obj->programs[i]);
8172 zfree(&obj->programs);
8174 list_del(&obj->list);
8179 bpf_object__next(struct bpf_object *prev)
8181 struct bpf_object *next;
8182 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8188 next = list_first_entry(&bpf_objects_list,
8192 next = list_next_entry(prev, list);
8194 /* Empty list is noticed here so don't need checking on entry. */
8195 if (&next->list == &bpf_objects_list)
8201 const char *bpf_object__name(const struct bpf_object *obj)
8203 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8206 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8208 return obj ? obj->kern_version : 0;
8211 struct btf *bpf_object__btf(const struct bpf_object *obj)
8213 return obj ? obj->btf : NULL;
8216 int bpf_object__btf_fd(const struct bpf_object *obj)
8218 return obj->btf ? btf__fd(obj->btf) : -1;
8221 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8224 return libbpf_err(-EINVAL);
8226 obj->kern_version = kern_version;
8231 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8232 bpf_object_clear_priv_t clear_priv)
8234 if (obj->priv && obj->clear_priv)
8235 obj->clear_priv(obj, obj->priv);
8238 obj->clear_priv = clear_priv;
8242 void *bpf_object__priv(const struct bpf_object *obj)
8244 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
8247 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8249 struct bpf_gen *gen;
8253 if (!OPTS_VALID(opts, gen_loader_opts))
8255 gen = calloc(sizeof(*gen), 1);
8259 obj->gen_loader = gen;
8263 static struct bpf_program *
8264 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8267 size_t nr_programs = obj->nr_programs;
8274 /* Iter from the beginning */
8275 return forward ? &obj->programs[0] :
8276 &obj->programs[nr_programs - 1];
8278 if (p->obj != obj) {
8279 pr_warn("error: program handler doesn't match object\n");
8280 return errno = EINVAL, NULL;
8283 idx = (p - obj->programs) + (forward ? 1 : -1);
8284 if (idx >= obj->nr_programs || idx < 0)
8286 return &obj->programs[idx];
8289 struct bpf_program *
8290 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
8292 return bpf_object__next_program(obj, prev);
8295 struct bpf_program *
8296 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8298 struct bpf_program *prog = prev;
8301 prog = __bpf_program__iter(prog, obj, true);
8302 } while (prog && prog_is_subprog(obj, prog));
8307 struct bpf_program *
8308 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8310 return bpf_object__prev_program(obj, next);
8313 struct bpf_program *
8314 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8316 struct bpf_program *prog = next;
8319 prog = __bpf_program__iter(prog, obj, false);
8320 } while (prog && prog_is_subprog(obj, prog));
8325 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8326 bpf_program_clear_priv_t clear_priv)
8328 if (prog->priv && prog->clear_priv)
8329 prog->clear_priv(prog, prog->priv);
8332 prog->clear_priv = clear_priv;
8336 void *bpf_program__priv(const struct bpf_program *prog)
8338 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
8341 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8343 prog->prog_ifindex = ifindex;
8346 const char *bpf_program__name(const struct bpf_program *prog)
8351 const char *bpf_program__section_name(const struct bpf_program *prog)
8353 return prog->sec_name;
8356 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
8360 title = prog->sec_name;
8362 title = strdup(title);
8364 pr_warn("failed to strdup program title\n");
8365 return libbpf_err_ptr(-ENOMEM);
8372 bool bpf_program__autoload(const struct bpf_program *prog)
8377 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8379 if (prog->obj->loaded)
8380 return libbpf_err(-EINVAL);
8382 prog->load = autoload;
8386 static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8388 int bpf_program__fd(const struct bpf_program *prog)
8390 return bpf_program_nth_fd(prog, 0);
8393 size_t bpf_program__size(const struct bpf_program *prog)
8395 return prog->insns_cnt * BPF_INSN_SZ;
8398 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8403 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8405 return prog->insns_cnt;
8408 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8409 bpf_program_prep_t prep)
8413 if (nr_instances <= 0 || !prep)
8414 return libbpf_err(-EINVAL);
8416 if (prog->instances.nr > 0 || prog->instances.fds) {
8417 pr_warn("Can't set pre-processor after loading\n");
8418 return libbpf_err(-EINVAL);
8421 instances_fds = malloc(sizeof(int) * nr_instances);
8422 if (!instances_fds) {
8423 pr_warn("alloc memory failed for fds\n");
8424 return libbpf_err(-ENOMEM);
8427 /* fill all fd with -1 */
8428 memset(instances_fds, -1, sizeof(int) * nr_instances);
8430 prog->instances.nr = nr_instances;
8431 prog->instances.fds = instances_fds;
8432 prog->preprocessor = prep;
8436 __attribute__((alias("bpf_program_nth_fd")))
8437 int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8439 static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
8444 return libbpf_err(-EINVAL);
8446 if (n >= prog->instances.nr || n < 0) {
8447 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
8448 n, prog->name, prog->instances.nr);
8449 return libbpf_err(-EINVAL);
8452 fd = prog->instances.fds[n];
8454 pr_warn("%dth instance of program '%s' is invalid\n",
8456 return libbpf_err(-ENOENT);
8462 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
8467 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8472 static bool bpf_program__is_type(const struct bpf_program *prog,
8473 enum bpf_prog_type type)
8475 return prog ? (prog->type == type) : false;
8478 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
8479 int bpf_program__set_##NAME(struct bpf_program *prog) \
8482 return libbpf_err(-EINVAL); \
8483 bpf_program__set_type(prog, TYPE); \
8487 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
8489 return bpf_program__is_type(prog, TYPE); \
8492 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
8493 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
8494 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
8495 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8496 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
8497 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
8498 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
8499 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8500 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
8501 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
8502 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
8503 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
8504 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
8506 enum bpf_attach_type
8507 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
8509 return prog->expected_attach_type;
8512 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
8513 enum bpf_attach_type type)
8515 prog->expected_attach_type = type;
8518 __u32 bpf_program__flags(const struct bpf_program *prog)
8520 return prog->prog_flags;
8523 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8525 if (prog->obj->loaded)
8526 return libbpf_err(-EBUSY);
8528 prog->prog_flags = flags;
8532 __u32 bpf_program__log_level(const struct bpf_program *prog)
8534 return prog->log_level;
8537 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8539 if (prog->obj->loaded)
8540 return libbpf_err(-EBUSY);
8542 prog->log_level = log_level;
8546 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8548 *log_size = prog->log_size;
8549 return prog->log_buf;
8552 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8554 if (log_size && !log_buf)
8556 if (prog->log_size > UINT_MAX)
8558 if (prog->obj->loaded)
8561 prog->log_buf = log_buf;
8562 prog->log_size = log_size;
8566 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8568 .prog_type = BPF_PROG_TYPE_##ptype, \
8569 .expected_attach_type = atype, \
8570 .cookie = (long)(flags), \
8571 .preload_fn = libbpf_preload_prog, \
8575 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie);
8576 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie);
8577 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie);
8578 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie);
8579 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie);
8580 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie);
8582 static const struct bpf_sec_def section_defs[] = {
8583 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
8584 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8585 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8586 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8587 SEC_DEF("uprobe/", KPROBE, 0, SEC_NONE),
8588 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8589 SEC_DEF("uretprobe/", KPROBE, 0, SEC_NONE),
8590 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
8591 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX),
8592 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8593 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8594 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8595 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8596 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8597 SEC_DEF("raw_tracepoint.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8598 SEC_DEF("raw_tp.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8599 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8600 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8601 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8602 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8603 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8604 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8605 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8606 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8607 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8608 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8609 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8610 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8611 SEC_DEF("xdp_devmap/", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8612 SEC_DEF("xdp_cpumap/", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8613 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8614 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8615 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
8616 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8617 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8618 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
8619 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8620 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8621 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8622 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8623 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8624 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8625 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8626 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8627 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8628 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8629 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8630 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8631 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8632 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8633 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8634 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8635 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8636 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8637 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8638 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8639 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8640 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8641 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8642 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8643 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8644 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8645 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8646 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8647 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8648 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8649 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8650 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8651 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8654 #define MAX_TYPE_NAME_SIZE 32
8656 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8658 const struct bpf_sec_def *sec_def;
8659 enum sec_def_flags sec_flags;
8660 int i, n = ARRAY_SIZE(section_defs), len;
8661 bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME;
8663 for (i = 0; i < n; i++) {
8664 sec_def = §ion_defs[i];
8665 sec_flags = sec_def->cookie;
8666 len = strlen(sec_def->sec);
8668 /* "type/" always has to have proper SEC("type/extras") form */
8669 if (sec_def->sec[len - 1] == '/') {
8670 if (str_has_pfx(sec_name, sec_def->sec))
8675 /* "type+" means it can be either exact SEC("type") or
8676 * well-formed SEC("type/extras") with proper '/' separator
8678 if (sec_def->sec[len - 1] == '+') {
8680 /* not even a prefix */
8681 if (strncmp(sec_name, sec_def->sec, len) != 0)
8683 /* exact match or has '/' separator */
8684 if (sec_name[len] == '\0' || sec_name[len] == '/')
8689 /* SEC_SLOPPY_PFX definitions are allowed to be just prefix
8690 * matches, unless strict section name mode
8691 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
8692 * match has to be exact.
8694 if ((sec_flags & SEC_SLOPPY_PFX) && !strict) {
8695 if (str_has_pfx(sec_name, sec_def->sec))
8700 /* Definitions not marked SEC_SLOPPY_PFX (e.g.,
8701 * SEC("syscall")) are exact matches in both modes.
8703 if (strcmp(sec_name, sec_def->sec) == 0)
8709 static char *libbpf_get_type_names(bool attach_type)
8711 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8719 /* Forge string buf with all available names */
8720 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8721 const struct bpf_sec_def *sec_def = §ion_defs[i];
8724 if (sec_def->preload_fn != libbpf_preload_prog)
8727 if (!(sec_def->cookie & SEC_ATTACHABLE))
8731 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8736 strcat(buf, section_defs[i].sec);
8742 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8743 enum bpf_attach_type *expected_attach_type)
8745 const struct bpf_sec_def *sec_def;
8749 return libbpf_err(-EINVAL);
8751 sec_def = find_sec_def(name);
8753 *prog_type = sec_def->prog_type;
8754 *expected_attach_type = sec_def->expected_attach_type;
8758 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8759 type_names = libbpf_get_type_names(false);
8760 if (type_names != NULL) {
8761 pr_debug("supported section(type) names are:%s\n", type_names);
8765 return libbpf_err(-ESRCH);
8768 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8771 struct bpf_map *map;
8774 for (i = 0; i < obj->nr_maps; i++) {
8775 map = &obj->maps[i];
8776 if (!bpf_map__is_struct_ops(map))
8778 if (map->sec_offset <= offset &&
8779 offset - map->sec_offset < map->def.value_size)
8786 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8787 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8788 Elf64_Shdr *shdr, Elf_Data *data)
8790 const struct btf_member *member;
8791 struct bpf_struct_ops *st_ops;
8792 struct bpf_program *prog;
8793 unsigned int shdr_idx;
8794 const struct btf *btf;
8795 struct bpf_map *map;
8796 unsigned int moff, insn_idx;
8804 nrels = shdr->sh_size / shdr->sh_entsize;
8805 for (i = 0; i < nrels; i++) {
8806 rel = elf_rel_by_idx(data, i);
8808 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8809 return -LIBBPF_ERRNO__FORMAT;
8812 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8814 pr_warn("struct_ops reloc: symbol %zx not found\n",
8815 (size_t)ELF64_R_SYM(rel->r_info));
8816 return -LIBBPF_ERRNO__FORMAT;
8819 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8820 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8822 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8823 (size_t)rel->r_offset);
8827 moff = rel->r_offset - map->sec_offset;
8828 shdr_idx = sym->st_shndx;
8829 st_ops = map->st_ops;
8830 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",
8832 (long long)(rel->r_info >> 32),
8833 (long long)sym->st_value,
8834 shdr_idx, (size_t)rel->r_offset,
8835 map->sec_offset, sym->st_name, name);
8837 if (shdr_idx >= SHN_LORESERVE) {
8838 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8839 map->name, (size_t)rel->r_offset, shdr_idx);
8840 return -LIBBPF_ERRNO__RELOC;
8842 if (sym->st_value % BPF_INSN_SZ) {
8843 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8844 map->name, (unsigned long long)sym->st_value);
8845 return -LIBBPF_ERRNO__FORMAT;
8847 insn_idx = sym->st_value / BPF_INSN_SZ;
8849 member = find_member_by_offset(st_ops->type, moff * 8);
8851 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8855 member_idx = member - btf_members(st_ops->type);
8856 name = btf__name_by_offset(btf, member->name_off);
8858 if (!resolve_func_ptr(btf, member->type, NULL)) {
8859 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8864 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8866 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8867 map->name, shdr_idx, name);
8871 /* prevent the use of BPF prog with invalid type */
8872 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8873 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8874 map->name, prog->name);
8878 /* if we haven't yet processed this BPF program, record proper
8879 * attach_btf_id and member_idx
8881 if (!prog->attach_btf_id) {
8882 prog->attach_btf_id = st_ops->type_id;
8883 prog->expected_attach_type = member_idx;
8886 /* struct_ops BPF prog can be re-used between multiple
8887 * .struct_ops as long as it's the same struct_ops struct
8888 * definition and the same function pointer field
8890 if (prog->attach_btf_id != st_ops->type_id ||
8891 prog->expected_attach_type != member_idx) {
8892 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",
8893 map->name, prog->name, prog->sec_name, prog->type,
8894 prog->attach_btf_id, prog->expected_attach_type, name);
8898 st_ops->progs[member_idx] = prog;
8904 #define BTF_TRACE_PREFIX "btf_trace_"
8905 #define BTF_LSM_PREFIX "bpf_lsm_"
8906 #define BTF_ITER_PREFIX "bpf_iter_"
8907 #define BTF_MAX_NAME_SIZE 128
8909 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8910 const char **prefix, int *kind)
8912 switch (attach_type) {
8913 case BPF_TRACE_RAW_TP:
8914 *prefix = BTF_TRACE_PREFIX;
8915 *kind = BTF_KIND_TYPEDEF;
8918 *prefix = BTF_LSM_PREFIX;
8919 *kind = BTF_KIND_FUNC;
8921 case BPF_TRACE_ITER:
8922 *prefix = BTF_ITER_PREFIX;
8923 *kind = BTF_KIND_FUNC;
8927 *kind = BTF_KIND_FUNC;
8931 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8932 const char *name, __u32 kind)
8934 char btf_type_name[BTF_MAX_NAME_SIZE];
8937 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8938 "%s%s", prefix, name);
8939 /* snprintf returns the number of characters written excluding the
8940 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8941 * indicates truncation.
8943 if (ret < 0 || ret >= sizeof(btf_type_name))
8944 return -ENAMETOOLONG;
8945 return btf__find_by_name_kind(btf, btf_type_name, kind);
8948 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8949 enum bpf_attach_type attach_type)
8954 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8955 return find_btf_by_prefix_kind(btf, prefix, name, kind);
8958 int libbpf_find_vmlinux_btf_id(const char *name,
8959 enum bpf_attach_type attach_type)
8964 btf = btf__load_vmlinux_btf();
8965 err = libbpf_get_error(btf);
8967 pr_warn("vmlinux BTF is not found\n");
8968 return libbpf_err(err);
8971 err = find_attach_btf_id(btf, name, attach_type);
8973 pr_warn("%s is not found in vmlinux BTF\n", name);
8976 return libbpf_err(err);
8979 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8981 struct bpf_prog_info info = {};
8982 __u32 info_len = sizeof(info);
8986 err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
8988 pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
8989 attach_prog_fd, err);
8995 pr_warn("The target program doesn't have BTF\n");
8998 btf = btf__load_from_kernel_by_id(info.btf_id);
8999 err = libbpf_get_error(btf);
9001 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9004 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9007 pr_warn("%s is not found in prog's BTF\n", name);
9014 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9015 enum bpf_attach_type attach_type,
9016 int *btf_obj_fd, int *btf_type_id)
9020 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9022 *btf_obj_fd = 0; /* vmlinux BTF */
9029 ret = load_module_btfs(obj);
9033 for (i = 0; i < obj->btf_module_cnt; i++) {
9034 const struct module_btf *mod = &obj->btf_modules[i];
9036 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9038 *btf_obj_fd = mod->fd;
9051 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9052 int *btf_obj_fd, int *btf_type_id)
9054 enum bpf_attach_type attach_type = prog->expected_attach_type;
9055 __u32 attach_prog_fd = prog->attach_prog_fd;
9058 /* BPF program's BTF ID */
9059 if (attach_prog_fd) {
9060 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9062 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9063 attach_prog_fd, attach_name, err);
9071 /* kernel/module BTF ID */
9072 if (prog->obj->gen_loader) {
9073 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9077 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9080 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9086 int libbpf_attach_type_by_name(const char *name,
9087 enum bpf_attach_type *attach_type)
9090 const struct bpf_sec_def *sec_def;
9093 return libbpf_err(-EINVAL);
9095 sec_def = find_sec_def(name);
9097 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9098 type_names = libbpf_get_type_names(true);
9099 if (type_names != NULL) {
9100 pr_debug("attachable section(type) names are:%s\n", type_names);
9104 return libbpf_err(-EINVAL);
9107 if (sec_def->preload_fn != libbpf_preload_prog)
9108 return libbpf_err(-EINVAL);
9109 if (!(sec_def->cookie & SEC_ATTACHABLE))
9110 return libbpf_err(-EINVAL);
9112 *attach_type = sec_def->expected_attach_type;
9116 int bpf_map__fd(const struct bpf_map *map)
9118 return map ? map->fd : libbpf_err(-EINVAL);
9121 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9123 return map ? &map->def : libbpf_err_ptr(-EINVAL);
9126 static bool map_uses_real_name(const struct bpf_map *map)
9128 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9129 * their user-visible name differs from kernel-visible name. Users see
9130 * such map's corresponding ELF section name as a map name.
9131 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9132 * maps to know which name has to be returned to the user.
9134 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9136 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9141 const char *bpf_map__name(const struct bpf_map *map)
9146 if (map_uses_real_name(map))
9147 return map->real_name;
9152 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9154 return map->def.type;
9157 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9160 return libbpf_err(-EBUSY);
9161 map->def.type = type;
9165 __u32 bpf_map__map_flags(const struct bpf_map *map)
9167 return map->def.map_flags;
9170 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9173 return libbpf_err(-EBUSY);
9174 map->def.map_flags = flags;
9178 __u64 bpf_map__map_extra(const struct bpf_map *map)
9180 return map->map_extra;
9183 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9186 return libbpf_err(-EBUSY);
9187 map->map_extra = map_extra;
9191 __u32 bpf_map__numa_node(const struct bpf_map *map)
9193 return map->numa_node;
9196 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9199 return libbpf_err(-EBUSY);
9200 map->numa_node = numa_node;
9204 __u32 bpf_map__key_size(const struct bpf_map *map)
9206 return map->def.key_size;
9209 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9212 return libbpf_err(-EBUSY);
9213 map->def.key_size = size;
9217 __u32 bpf_map__value_size(const struct bpf_map *map)
9219 return map->def.value_size;
9222 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9225 return libbpf_err(-EBUSY);
9226 map->def.value_size = size;
9230 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9232 return map ? map->btf_key_type_id : 0;
9235 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9237 return map ? map->btf_value_type_id : 0;
9240 int bpf_map__set_priv(struct bpf_map *map, void *priv,
9241 bpf_map_clear_priv_t clear_priv)
9244 return libbpf_err(-EINVAL);
9247 if (map->clear_priv)
9248 map->clear_priv(map, map->priv);
9252 map->clear_priv = clear_priv;
9256 void *bpf_map__priv(const struct bpf_map *map)
9258 return map ? map->priv : libbpf_err_ptr(-EINVAL);
9261 int bpf_map__set_initial_value(struct bpf_map *map,
9262 const void *data, size_t size)
9264 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9265 size != map->def.value_size || map->fd >= 0)
9266 return libbpf_err(-EINVAL);
9268 memcpy(map->mmaped, data, size);
9272 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9276 *psize = map->def.value_size;
9280 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
9282 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9285 bool bpf_map__is_internal(const struct bpf_map *map)
9287 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9290 __u32 bpf_map__ifindex(const struct bpf_map *map)
9292 return map->map_ifindex;
9295 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9298 return libbpf_err(-EBUSY);
9299 map->map_ifindex = ifindex;
9303 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9305 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9306 pr_warn("error: unsupported map type\n");
9307 return libbpf_err(-EINVAL);
9309 if (map->inner_map_fd != -1) {
9310 pr_warn("error: inner_map_fd already specified\n");
9311 return libbpf_err(-EINVAL);
9313 if (map->inner_map) {
9314 bpf_map__destroy(map->inner_map);
9315 zfree(&map->inner_map);
9317 map->inner_map_fd = fd;
9321 static struct bpf_map *
9322 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9325 struct bpf_map *s, *e;
9327 if (!obj || !obj->maps)
9328 return errno = EINVAL, NULL;
9331 e = obj->maps + obj->nr_maps;
9333 if ((m < s) || (m >= e)) {
9334 pr_warn("error in %s: map handler doesn't belong to object\n",
9336 return errno = EINVAL, NULL;
9339 idx = (m - obj->maps) + i;
9340 if (idx >= obj->nr_maps || idx < 0)
9342 return &obj->maps[idx];
9346 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
9348 return bpf_object__next_map(obj, prev);
9352 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9357 return __bpf_map__iter(prev, obj, 1);
9361 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
9363 return bpf_object__prev_map(obj, next);
9367 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9372 return obj->maps + obj->nr_maps - 1;
9375 return __bpf_map__iter(next, obj, -1);
9379 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9381 struct bpf_map *pos;
9383 bpf_object__for_each_map(pos, obj) {
9384 /* if it's a special internal map name (which always starts
9385 * with dot) then check if that special name matches the
9386 * real map name (ELF section name)
9388 if (name[0] == '.') {
9389 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9393 /* otherwise map name has to be an exact match */
9394 if (map_uses_real_name(pos)) {
9395 if (strcmp(pos->real_name, name) == 0)
9399 if (strcmp(pos->name, name) == 0)
9402 return errno = ENOENT, NULL;
9406 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9408 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9412 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9414 return libbpf_err_ptr(-ENOTSUP);
9417 long libbpf_get_error(const void *ptr)
9419 if (!IS_ERR_OR_NULL(ptr))
9423 errno = -PTR_ERR(ptr);
9425 /* If ptr == NULL, then errno should be already set by the failing
9426 * API, because libbpf never returns NULL on success and it now always
9427 * sets errno on error. So no extra errno handling for ptr == NULL
9433 __attribute__((alias("bpf_prog_load_xattr2")))
9434 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
9435 struct bpf_object **pobj, int *prog_fd);
9437 static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
9438 struct bpf_object **pobj, int *prog_fd)
9440 struct bpf_object_open_attr open_attr = {};
9441 struct bpf_program *prog, *first_prog = NULL;
9442 struct bpf_object *obj;
9443 struct bpf_map *map;
9447 return libbpf_err(-EINVAL);
9449 return libbpf_err(-EINVAL);
9451 open_attr.file = attr->file;
9452 open_attr.prog_type = attr->prog_type;
9454 obj = bpf_object__open_xattr(&open_attr);
9455 err = libbpf_get_error(obj);
9457 return libbpf_err(-ENOENT);
9459 bpf_object__for_each_program(prog, obj) {
9460 enum bpf_attach_type attach_type = attr->expected_attach_type;
9462 * to preserve backwards compatibility, bpf_prog_load treats
9463 * attr->prog_type, if specified, as an override to whatever
9464 * bpf_object__open guessed
9466 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
9467 bpf_program__set_type(prog, attr->prog_type);
9468 bpf_program__set_expected_attach_type(prog,
9471 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
9473 * we haven't guessed from section name and user
9474 * didn't provide a fallback type, too bad...
9476 bpf_object__close(obj);
9477 return libbpf_err(-EINVAL);
9480 prog->prog_ifindex = attr->ifindex;
9481 prog->log_level = attr->log_level;
9482 prog->prog_flags |= attr->prog_flags;
9487 bpf_object__for_each_map(map, obj) {
9488 if (!bpf_map__is_offload_neutral(map))
9489 map->map_ifindex = attr->ifindex;
9493 pr_warn("object file doesn't contain bpf program\n");
9494 bpf_object__close(obj);
9495 return libbpf_err(-ENOENT);
9498 err = bpf_object__load(obj);
9500 bpf_object__close(obj);
9501 return libbpf_err(err);
9505 *prog_fd = bpf_program__fd(first_prog);
9509 COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
9510 int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
9511 struct bpf_object **pobj, int *prog_fd)
9513 struct bpf_prog_load_attr attr;
9515 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9517 attr.prog_type = type;
9518 attr.expected_attach_type = 0;
9520 return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
9524 int (*detach)(struct bpf_link *link);
9525 void (*dealloc)(struct bpf_link *link);
9526 char *pin_path; /* NULL, if not pinned */
9527 int fd; /* hook FD, -1 if not applicable */
9531 /* Replace link's underlying BPF program with the new one */
9532 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9536 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9537 return libbpf_err_errno(ret);
9540 /* Release "ownership" of underlying BPF resource (typically, BPF program
9541 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9542 * link, when destructed through bpf_link__destroy() call won't attempt to
9543 * detach/unregisted that BPF resource. This is useful in situations where,
9544 * say, attached BPF program has to outlive userspace program that attached it
9545 * in the system. Depending on type of BPF program, though, there might be
9546 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9547 * exit of userspace program doesn't trigger automatic detachment and clean up
9548 * inside the kernel.
9550 void bpf_link__disconnect(struct bpf_link *link)
9552 link->disconnected = true;
9555 int bpf_link__destroy(struct bpf_link *link)
9559 if (IS_ERR_OR_NULL(link))
9562 if (!link->disconnected && link->detach)
9563 err = link->detach(link);
9565 free(link->pin_path);
9567 link->dealloc(link);
9571 return libbpf_err(err);
9574 int bpf_link__fd(const struct bpf_link *link)
9579 const char *bpf_link__pin_path(const struct bpf_link *link)
9581 return link->pin_path;
9584 static int bpf_link__detach_fd(struct bpf_link *link)
9586 return libbpf_err_errno(close(link->fd));
9589 struct bpf_link *bpf_link__open(const char *path)
9591 struct bpf_link *link;
9594 fd = bpf_obj_get(path);
9597 pr_warn("failed to open link at %s: %d\n", path, fd);
9598 return libbpf_err_ptr(fd);
9601 link = calloc(1, sizeof(*link));
9604 return libbpf_err_ptr(-ENOMEM);
9606 link->detach = &bpf_link__detach_fd;
9609 link->pin_path = strdup(path);
9610 if (!link->pin_path) {
9611 bpf_link__destroy(link);
9612 return libbpf_err_ptr(-ENOMEM);
9618 int bpf_link__detach(struct bpf_link *link)
9620 return bpf_link_detach(link->fd) ? -errno : 0;
9623 int bpf_link__pin(struct bpf_link *link, const char *path)
9628 return libbpf_err(-EBUSY);
9629 err = make_parent_dir(path);
9631 return libbpf_err(err);
9632 err = check_path(path);
9634 return libbpf_err(err);
9636 link->pin_path = strdup(path);
9637 if (!link->pin_path)
9638 return libbpf_err(-ENOMEM);
9640 if (bpf_obj_pin(link->fd, link->pin_path)) {
9642 zfree(&link->pin_path);
9643 return libbpf_err(err);
9646 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9650 int bpf_link__unpin(struct bpf_link *link)
9654 if (!link->pin_path)
9655 return libbpf_err(-EINVAL);
9657 err = unlink(link->pin_path);
9661 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9662 zfree(&link->pin_path);
9666 struct bpf_link_perf {
9667 struct bpf_link link;
9669 /* legacy kprobe support: keep track of probe identifier and type */
9670 char *legacy_probe_name;
9671 bool legacy_is_kprobe;
9672 bool legacy_is_retprobe;
9675 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9676 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9678 static int bpf_link_perf_detach(struct bpf_link *link)
9680 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9683 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9686 if (perf_link->perf_event_fd != link->fd)
9687 close(perf_link->perf_event_fd);
9690 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9691 if (perf_link->legacy_probe_name) {
9692 if (perf_link->legacy_is_kprobe) {
9693 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9694 perf_link->legacy_is_retprobe);
9696 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9697 perf_link->legacy_is_retprobe);
9704 static void bpf_link_perf_dealloc(struct bpf_link *link)
9706 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9708 free(perf_link->legacy_probe_name);
9712 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9713 const struct bpf_perf_event_opts *opts)
9715 char errmsg[STRERR_BUFSIZE];
9716 struct bpf_link_perf *link;
9717 int prog_fd, link_fd = -1, err;
9719 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9720 return libbpf_err_ptr(-EINVAL);
9723 pr_warn("prog '%s': invalid perf event FD %d\n",
9725 return libbpf_err_ptr(-EINVAL);
9727 prog_fd = bpf_program__fd(prog);
9729 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9731 return libbpf_err_ptr(-EINVAL);
9734 link = calloc(1, sizeof(*link));
9736 return libbpf_err_ptr(-ENOMEM);
9737 link->link.detach = &bpf_link_perf_detach;
9738 link->link.dealloc = &bpf_link_perf_dealloc;
9739 link->perf_event_fd = pfd;
9741 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9742 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9743 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9745 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9748 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9750 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9753 link->link.fd = link_fd;
9755 if (OPTS_GET(opts, bpf_cookie, 0)) {
9756 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9761 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9763 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9764 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9766 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9770 link->link.fd = pfd;
9772 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9774 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9775 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9784 return libbpf_err_ptr(err);
9787 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9789 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9793 * this function is expected to parse integer in the range of [0, 2^31-1] from
9794 * given file using scanf format string fmt. If actual parsed value is
9795 * negative, the result might be indistinguishable from error
9797 static int parse_uint_from_file(const char *file, const char *fmt)
9799 char buf[STRERR_BUFSIZE];
9803 f = fopen(file, "r");
9806 pr_debug("failed to open '%s': %s\n", file,
9807 libbpf_strerror_r(err, buf, sizeof(buf)));
9810 err = fscanf(f, fmt, &ret);
9812 err = err == EOF ? -EIO : -errno;
9813 pr_debug("failed to parse '%s': %s\n", file,
9814 libbpf_strerror_r(err, buf, sizeof(buf)));
9822 static int determine_kprobe_perf_type(void)
9824 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9826 return parse_uint_from_file(file, "%d\n");
9829 static int determine_uprobe_perf_type(void)
9831 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9833 return parse_uint_from_file(file, "%d\n");
9836 static int determine_kprobe_retprobe_bit(void)
9838 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9840 return parse_uint_from_file(file, "config:%d\n");
9843 static int determine_uprobe_retprobe_bit(void)
9845 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9847 return parse_uint_from_file(file, "config:%d\n");
9850 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9851 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9853 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9854 uint64_t offset, int pid, size_t ref_ctr_off)
9856 struct perf_event_attr attr = {};
9857 char errmsg[STRERR_BUFSIZE];
9860 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9863 type = uprobe ? determine_uprobe_perf_type()
9864 : determine_kprobe_perf_type();
9866 pr_warn("failed to determine %s perf type: %s\n",
9867 uprobe ? "uprobe" : "kprobe",
9868 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9872 int bit = uprobe ? determine_uprobe_retprobe_bit()
9873 : determine_kprobe_retprobe_bit();
9876 pr_warn("failed to determine %s retprobe bit: %s\n",
9877 uprobe ? "uprobe" : "kprobe",
9878 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9881 attr.config |= 1 << bit;
9883 attr.size = sizeof(attr);
9885 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9886 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9887 attr.config2 = offset; /* kprobe_addr or probe_offset */
9889 /* pid filter is meaningful only for uprobes */
9890 pfd = syscall(__NR_perf_event_open, &attr,
9891 pid < 0 ? -1 : pid /* pid */,
9892 pid == -1 ? 0 : -1 /* cpu */,
9893 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9896 pr_warn("%s perf_event_open() failed: %s\n",
9897 uprobe ? "uprobe" : "kprobe",
9898 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9904 static int append_to_file(const char *file, const char *fmt, ...)
9909 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9914 n = vdprintf(fd, fmt, ap);
9924 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9925 const char *kfunc_name, size_t offset)
9927 static int index = 0;
9929 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
9930 __sync_fetch_and_add(&index, 1));
9933 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9934 const char *kfunc_name, size_t offset)
9936 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9938 return append_to_file(file, "%c:%s/%s %s+0x%zx",
9939 retprobe ? 'r' : 'p',
9940 retprobe ? "kretprobes" : "kprobes",
9941 probe_name, kfunc_name, offset);
9944 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9946 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9948 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
9951 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9955 snprintf(file, sizeof(file),
9956 "/sys/kernel/debug/tracing/events/%s/%s/id",
9957 retprobe ? "kretprobes" : "kprobes", probe_name);
9959 return parse_uint_from_file(file, "%d\n");
9962 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9963 const char *kfunc_name, size_t offset, int pid)
9965 struct perf_event_attr attr = {};
9966 char errmsg[STRERR_BUFSIZE];
9969 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9971 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9973 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9976 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
9978 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9980 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9983 attr.size = sizeof(attr);
9985 attr.type = PERF_TYPE_TRACEPOINT;
9987 pfd = syscall(__NR_perf_event_open, &attr,
9988 pid < 0 ? -1 : pid, /* pid */
9989 pid == -1 ? 0 : -1, /* cpu */
9990 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9993 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
9994 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10001 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10002 const char *func_name,
10003 const struct bpf_kprobe_opts *opts)
10005 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10006 char errmsg[STRERR_BUFSIZE];
10007 char *legacy_probe = NULL;
10008 struct bpf_link *link;
10010 bool retprobe, legacy;
10013 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10014 return libbpf_err_ptr(-EINVAL);
10016 retprobe = OPTS_GET(opts, retprobe, false);
10017 offset = OPTS_GET(opts, offset, 0);
10018 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10020 legacy = determine_kprobe_perf_type() < 0;
10022 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10024 -1 /* pid */, 0 /* ref_ctr_off */);
10026 char probe_name[256];
10028 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10029 func_name, offset);
10031 legacy_probe = strdup(probe_name);
10033 return libbpf_err_ptr(-ENOMEM);
10035 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10036 offset, -1 /* pid */);
10040 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10041 prog->name, retprobe ? "kretprobe" : "kprobe",
10043 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10046 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10047 err = libbpf_get_error(link);
10050 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10051 prog->name, retprobe ? "kretprobe" : "kprobe",
10053 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10057 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10059 perf_link->legacy_probe_name = legacy_probe;
10060 perf_link->legacy_is_kprobe = true;
10061 perf_link->legacy_is_retprobe = retprobe;
10066 free(legacy_probe);
10067 return libbpf_err_ptr(err);
10070 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10072 const char *func_name)
10074 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10075 .retprobe = retprobe,
10078 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10081 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie)
10083 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10084 unsigned long offset = 0;
10085 struct bpf_link *link;
10086 const char *func_name;
10090 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10092 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10094 func_name = prog->sec_name + sizeof("kprobe/") - 1;
10096 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10099 pr_warn("kprobe name is invalid: %s\n", func_name);
10100 return libbpf_err_ptr(err);
10102 if (opts.retprobe && offset != 0) {
10105 pr_warn("kretprobes do not support offset specification\n");
10106 return libbpf_err_ptr(err);
10109 opts.offset = offset;
10110 link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10115 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10116 const char *binary_path, uint64_t offset)
10120 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10122 /* sanitize binary_path in the probe name */
10123 for (i = 0; buf[i]; i++) {
10124 if (!isalnum(buf[i]))
10129 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10130 const char *binary_path, size_t offset)
10132 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10134 return append_to_file(file, "%c:%s/%s %s:0x%zx",
10135 retprobe ? 'r' : 'p',
10136 retprobe ? "uretprobes" : "uprobes",
10137 probe_name, binary_path, offset);
10140 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10142 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10144 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
10147 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10151 snprintf(file, sizeof(file),
10152 "/sys/kernel/debug/tracing/events/%s/%s/id",
10153 retprobe ? "uretprobes" : "uprobes", probe_name);
10155 return parse_uint_from_file(file, "%d\n");
10158 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10159 const char *binary_path, size_t offset, int pid)
10161 struct perf_event_attr attr;
10162 int type, pfd, err;
10164 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10166 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10167 binary_path, (size_t)offset, err);
10170 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10172 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10173 binary_path, offset, err);
10177 memset(&attr, 0, sizeof(attr));
10178 attr.size = sizeof(attr);
10179 attr.config = type;
10180 attr.type = PERF_TYPE_TRACEPOINT;
10182 pfd = syscall(__NR_perf_event_open, &attr,
10183 pid < 0 ? -1 : pid, /* pid */
10184 pid == -1 ? 0 : -1, /* cpu */
10185 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10188 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10194 LIBBPF_API struct bpf_link *
10195 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10196 const char *binary_path, size_t func_offset,
10197 const struct bpf_uprobe_opts *opts)
10199 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10200 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10201 struct bpf_link *link;
10202 size_t ref_ctr_off;
10204 bool retprobe, legacy;
10206 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10207 return libbpf_err_ptr(-EINVAL);
10209 retprobe = OPTS_GET(opts, retprobe, false);
10210 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10211 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10213 legacy = determine_uprobe_perf_type() < 0;
10215 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10216 func_offset, pid, ref_ctr_off);
10218 char probe_name[512];
10221 return libbpf_err_ptr(-EINVAL);
10223 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10224 binary_path, func_offset);
10226 legacy_probe = strdup(probe_name);
10228 return libbpf_err_ptr(-ENOMEM);
10230 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10231 binary_path, func_offset, pid);
10235 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10236 prog->name, retprobe ? "uretprobe" : "uprobe",
10237 binary_path, func_offset,
10238 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10242 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10243 err = libbpf_get_error(link);
10246 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10247 prog->name, retprobe ? "uretprobe" : "uprobe",
10248 binary_path, func_offset,
10249 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10253 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10255 perf_link->legacy_probe_name = legacy_probe;
10256 perf_link->legacy_is_kprobe = false;
10257 perf_link->legacy_is_retprobe = retprobe;
10261 free(legacy_probe);
10262 return libbpf_err_ptr(err);
10266 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
10267 bool retprobe, pid_t pid,
10268 const char *binary_path,
10269 size_t func_offset)
10271 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10273 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10276 static int determine_tracepoint_id(const char *tp_category,
10277 const char *tp_name)
10279 char file[PATH_MAX];
10282 ret = snprintf(file, sizeof(file),
10283 "/sys/kernel/debug/tracing/events/%s/%s/id",
10284 tp_category, tp_name);
10287 if (ret >= sizeof(file)) {
10288 pr_debug("tracepoint %s/%s path is too long\n",
10289 tp_category, tp_name);
10292 return parse_uint_from_file(file, "%d\n");
10295 static int perf_event_open_tracepoint(const char *tp_category,
10296 const char *tp_name)
10298 struct perf_event_attr attr = {};
10299 char errmsg[STRERR_BUFSIZE];
10300 int tp_id, pfd, err;
10302 tp_id = determine_tracepoint_id(tp_category, tp_name);
10304 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
10305 tp_category, tp_name,
10306 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
10310 attr.type = PERF_TYPE_TRACEPOINT;
10311 attr.size = sizeof(attr);
10312 attr.config = tp_id;
10314 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
10315 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10318 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
10319 tp_category, tp_name,
10320 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10326 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
10327 const char *tp_category,
10328 const char *tp_name,
10329 const struct bpf_tracepoint_opts *opts)
10331 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10332 char errmsg[STRERR_BUFSIZE];
10333 struct bpf_link *link;
10336 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
10337 return libbpf_err_ptr(-EINVAL);
10339 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10341 pfd = perf_event_open_tracepoint(tp_category, tp_name);
10343 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
10344 prog->name, tp_category, tp_name,
10345 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10346 return libbpf_err_ptr(pfd);
10348 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10349 err = libbpf_get_error(link);
10352 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
10353 prog->name, tp_category, tp_name,
10354 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10355 return libbpf_err_ptr(err);
10360 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
10361 const char *tp_category,
10362 const char *tp_name)
10364 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
10367 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie)
10369 char *sec_name, *tp_cat, *tp_name;
10370 struct bpf_link *link;
10372 sec_name = strdup(prog->sec_name);
10374 return libbpf_err_ptr(-ENOMEM);
10376 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
10377 if (str_has_pfx(prog->sec_name, "tp/"))
10378 tp_cat = sec_name + sizeof("tp/") - 1;
10380 tp_cat = sec_name + sizeof("tracepoint/") - 1;
10381 tp_name = strchr(tp_cat, '/');
10384 return libbpf_err_ptr(-EINVAL);
10389 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
10394 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
10395 const char *tp_name)
10397 char errmsg[STRERR_BUFSIZE];
10398 struct bpf_link *link;
10401 prog_fd = bpf_program__fd(prog);
10403 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10404 return libbpf_err_ptr(-EINVAL);
10407 link = calloc(1, sizeof(*link));
10409 return libbpf_err_ptr(-ENOMEM);
10410 link->detach = &bpf_link__detach_fd;
10412 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
10416 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
10417 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10418 return libbpf_err_ptr(pfd);
10424 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie)
10426 static const char *const prefixes[] = {
10430 "raw_tracepoint.w/",
10433 const char *tp_name = NULL;
10435 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
10436 if (str_has_pfx(prog->sec_name, prefixes[i])) {
10437 tp_name = prog->sec_name + strlen(prefixes[i]);
10442 pr_warn("prog '%s': invalid section name '%s'\n",
10443 prog->name, prog->sec_name);
10444 return libbpf_err_ptr(-EINVAL);
10447 return bpf_program__attach_raw_tracepoint(prog, tp_name);
10450 /* Common logic for all BPF program types that attach to a btf_id */
10451 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
10453 char errmsg[STRERR_BUFSIZE];
10454 struct bpf_link *link;
10457 prog_fd = bpf_program__fd(prog);
10459 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10460 return libbpf_err_ptr(-EINVAL);
10463 link = calloc(1, sizeof(*link));
10465 return libbpf_err_ptr(-ENOMEM);
10466 link->detach = &bpf_link__detach_fd;
10468 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
10472 pr_warn("prog '%s': failed to attach: %s\n",
10473 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10474 return libbpf_err_ptr(pfd);
10477 return (struct bpf_link *)link;
10480 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
10482 return bpf_program__attach_btf_id(prog);
10485 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
10487 return bpf_program__attach_btf_id(prog);
10490 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie)
10492 return bpf_program__attach_trace(prog);
10495 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie)
10497 return bpf_program__attach_lsm(prog);
10500 static struct bpf_link *
10501 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
10502 const char *target_name)
10504 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
10505 .target_btf_id = btf_id);
10506 enum bpf_attach_type attach_type;
10507 char errmsg[STRERR_BUFSIZE];
10508 struct bpf_link *link;
10509 int prog_fd, link_fd;
10511 prog_fd = bpf_program__fd(prog);
10513 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10514 return libbpf_err_ptr(-EINVAL);
10517 link = calloc(1, sizeof(*link));
10519 return libbpf_err_ptr(-ENOMEM);
10520 link->detach = &bpf_link__detach_fd;
10522 attach_type = bpf_program__get_expected_attach_type(prog);
10523 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
10527 pr_warn("prog '%s': failed to attach to %s: %s\n",
10528 prog->name, target_name,
10529 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10530 return libbpf_err_ptr(link_fd);
10532 link->fd = link_fd;
10537 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
10539 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
10543 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
10545 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
10548 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
10550 /* target_fd/target_ifindex use the same field in LINK_CREATE */
10551 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
10554 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
10556 const char *attach_func_name)
10560 if (!!target_fd != !!attach_func_name) {
10561 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
10563 return libbpf_err_ptr(-EINVAL);
10566 if (prog->type != BPF_PROG_TYPE_EXT) {
10567 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
10569 return libbpf_err_ptr(-EINVAL);
10573 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
10575 return libbpf_err_ptr(btf_id);
10577 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
10579 /* no target, so use raw_tracepoint_open for compatibility
10582 return bpf_program__attach_trace(prog);
10587 bpf_program__attach_iter(const struct bpf_program *prog,
10588 const struct bpf_iter_attach_opts *opts)
10590 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
10591 char errmsg[STRERR_BUFSIZE];
10592 struct bpf_link *link;
10593 int prog_fd, link_fd;
10594 __u32 target_fd = 0;
10596 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
10597 return libbpf_err_ptr(-EINVAL);
10599 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
10600 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
10602 prog_fd = bpf_program__fd(prog);
10604 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10605 return libbpf_err_ptr(-EINVAL);
10608 link = calloc(1, sizeof(*link));
10610 return libbpf_err_ptr(-ENOMEM);
10611 link->detach = &bpf_link__detach_fd;
10613 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
10614 &link_create_opts);
10618 pr_warn("prog '%s': failed to attach to iterator: %s\n",
10619 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10620 return libbpf_err_ptr(link_fd);
10622 link->fd = link_fd;
10626 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)
10628 return bpf_program__attach_iter(prog, NULL);
10631 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
10633 if (!prog->sec_def || !prog->sec_def->attach_fn)
10634 return libbpf_err_ptr(-ESRCH);
10636 return prog->sec_def->attach_fn(prog, prog->sec_def->cookie);
10639 static int bpf_link__detach_struct_ops(struct bpf_link *link)
10643 if (bpf_map_delete_elem(link->fd, &zero))
10649 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
10651 struct bpf_struct_ops *st_ops;
10652 struct bpf_link *link;
10656 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
10657 return libbpf_err_ptr(-EINVAL);
10659 link = calloc(1, sizeof(*link));
10661 return libbpf_err_ptr(-EINVAL);
10663 st_ops = map->st_ops;
10664 for (i = 0; i < btf_vlen(st_ops->type); i++) {
10665 struct bpf_program *prog = st_ops->progs[i];
10672 prog_fd = bpf_program__fd(prog);
10673 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10674 *(unsigned long *)kern_data = prog_fd;
10677 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10681 return libbpf_err_ptr(err);
10684 link->detach = bpf_link__detach_struct_ops;
10685 link->fd = map->fd;
10690 static enum bpf_perf_event_ret
10691 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10692 void **copy_mem, size_t *copy_size,
10693 bpf_perf_event_print_t fn, void *private_data)
10695 struct perf_event_mmap_page *header = mmap_mem;
10696 __u64 data_head = ring_buffer_read_head(header);
10697 __u64 data_tail = header->data_tail;
10698 void *base = ((__u8 *)header) + page_size;
10699 int ret = LIBBPF_PERF_EVENT_CONT;
10700 struct perf_event_header *ehdr;
10703 while (data_head != data_tail) {
10704 ehdr = base + (data_tail & (mmap_size - 1));
10705 ehdr_size = ehdr->size;
10707 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10708 void *copy_start = ehdr;
10709 size_t len_first = base + mmap_size - copy_start;
10710 size_t len_secnd = ehdr_size - len_first;
10712 if (*copy_size < ehdr_size) {
10714 *copy_mem = malloc(ehdr_size);
10717 ret = LIBBPF_PERF_EVENT_ERROR;
10720 *copy_size = ehdr_size;
10723 memcpy(*copy_mem, copy_start, len_first);
10724 memcpy(*copy_mem + len_first, base, len_secnd);
10728 ret = fn(ehdr, private_data);
10729 data_tail += ehdr_size;
10730 if (ret != LIBBPF_PERF_EVENT_CONT)
10734 ring_buffer_write_tail(header, data_tail);
10735 return libbpf_err(ret);
10738 __attribute__((alias("perf_event_read_simple")))
10739 enum bpf_perf_event_ret
10740 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10741 void **copy_mem, size_t *copy_size,
10742 bpf_perf_event_print_t fn, void *private_data);
10744 struct perf_buffer;
10746 struct perf_buffer_params {
10747 struct perf_event_attr *attr;
10748 /* if event_cb is specified, it takes precendence */
10749 perf_buffer_event_fn event_cb;
10750 /* sample_cb and lost_cb are higher-level common-case callbacks */
10751 perf_buffer_sample_fn sample_cb;
10752 perf_buffer_lost_fn lost_cb;
10759 struct perf_cpu_buf {
10760 struct perf_buffer *pb;
10761 void *base; /* mmap()'ed memory */
10762 void *buf; /* for reconstructing segmented data */
10769 struct perf_buffer {
10770 perf_buffer_event_fn event_cb;
10771 perf_buffer_sample_fn sample_cb;
10772 perf_buffer_lost_fn lost_cb;
10773 void *ctx; /* passed into callbacks */
10777 struct perf_cpu_buf **cpu_bufs;
10778 struct epoll_event *events;
10779 int cpu_cnt; /* number of allocated CPU buffers */
10780 int epoll_fd; /* perf event FD */
10781 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10784 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10785 struct perf_cpu_buf *cpu_buf)
10789 if (cpu_buf->base &&
10790 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
10791 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
10792 if (cpu_buf->fd >= 0) {
10793 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10794 close(cpu_buf->fd);
10796 free(cpu_buf->buf);
10800 void perf_buffer__free(struct perf_buffer *pb)
10804 if (IS_ERR_OR_NULL(pb))
10806 if (pb->cpu_bufs) {
10807 for (i = 0; i < pb->cpu_cnt; i++) {
10808 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10813 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10814 perf_buffer__free_cpu_buf(pb, cpu_buf);
10816 free(pb->cpu_bufs);
10818 if (pb->epoll_fd >= 0)
10819 close(pb->epoll_fd);
10824 static struct perf_cpu_buf *
10825 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10826 int cpu, int map_key)
10828 struct perf_cpu_buf *cpu_buf;
10829 char msg[STRERR_BUFSIZE];
10832 cpu_buf = calloc(1, sizeof(*cpu_buf));
10834 return ERR_PTR(-ENOMEM);
10837 cpu_buf->cpu = cpu;
10838 cpu_buf->map_key = map_key;
10840 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10841 -1, PERF_FLAG_FD_CLOEXEC);
10842 if (cpu_buf->fd < 0) {
10844 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10845 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10849 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10850 PROT_READ | PROT_WRITE, MAP_SHARED,
10852 if (cpu_buf->base == MAP_FAILED) {
10853 cpu_buf->base = NULL;
10855 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
10856 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10860 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10862 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
10863 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10870 perf_buffer__free_cpu_buf(pb, cpu_buf);
10871 return (struct perf_cpu_buf *)ERR_PTR(err);
10874 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10875 struct perf_buffer_params *p);
10877 DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
10878 struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
10879 perf_buffer_sample_fn sample_cb,
10880 perf_buffer_lost_fn lost_cb,
10882 const struct perf_buffer_opts *opts)
10884 struct perf_buffer_params p = {};
10885 struct perf_event_attr attr = {};
10887 if (!OPTS_VALID(opts, perf_buffer_opts))
10888 return libbpf_err_ptr(-EINVAL);
10890 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
10891 attr.type = PERF_TYPE_SOFTWARE;
10892 attr.sample_type = PERF_SAMPLE_RAW;
10893 attr.sample_period = 1;
10894 attr.wakeup_events = 1;
10897 p.sample_cb = sample_cb;
10898 p.lost_cb = lost_cb;
10901 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10904 COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
10905 struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
10906 const struct perf_buffer_opts *opts)
10908 return perf_buffer__new_v0_6_0(map_fd, page_cnt,
10909 opts ? opts->sample_cb : NULL,
10910 opts ? opts->lost_cb : NULL,
10911 opts ? opts->ctx : NULL,
10915 DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
10916 struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
10917 struct perf_event_attr *attr,
10918 perf_buffer_event_fn event_cb, void *ctx,
10919 const struct perf_buffer_raw_opts *opts)
10921 struct perf_buffer_params p = {};
10923 if (page_cnt == 0 || !attr)
10924 return libbpf_err_ptr(-EINVAL);
10926 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
10927 return libbpf_err_ptr(-EINVAL);
10930 p.event_cb = event_cb;
10932 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
10933 p.cpus = OPTS_GET(opts, cpus, NULL);
10934 p.map_keys = OPTS_GET(opts, map_keys, NULL);
10936 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10939 COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
10940 struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
10941 const struct perf_buffer_raw_opts *opts)
10943 LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
10944 .cpu_cnt = opts->cpu_cnt,
10945 .cpus = opts->cpus,
10946 .map_keys = opts->map_keys,
10949 return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
10950 opts->event_cb, opts->ctx, &inner_opts);
10953 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10954 struct perf_buffer_params *p)
10956 const char *online_cpus_file = "/sys/devices/system/cpu/online";
10957 struct bpf_map_info map;
10958 char msg[STRERR_BUFSIZE];
10959 struct perf_buffer *pb;
10960 bool *online = NULL;
10961 __u32 map_info_len;
10964 if (page_cnt & (page_cnt - 1)) {
10965 pr_warn("page count should be power of two, but is %zu\n",
10967 return ERR_PTR(-EINVAL);
10970 /* best-effort sanity checks */
10971 memset(&map, 0, sizeof(map));
10972 map_info_len = sizeof(map);
10973 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
10976 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
10977 * -EBADFD, -EFAULT, or -E2BIG on real error
10979 if (err != -EINVAL) {
10980 pr_warn("failed to get map info for map FD %d: %s\n",
10981 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
10982 return ERR_PTR(err);
10984 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
10987 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
10988 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
10990 return ERR_PTR(-EINVAL);
10994 pb = calloc(1, sizeof(*pb));
10996 return ERR_PTR(-ENOMEM);
10998 pb->event_cb = p->event_cb;
10999 pb->sample_cb = p->sample_cb;
11000 pb->lost_cb = p->lost_cb;
11003 pb->page_size = getpagesize();
11004 pb->mmap_size = pb->page_size * page_cnt;
11005 pb->map_fd = map_fd;
11007 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11008 if (pb->epoll_fd < 0) {
11010 pr_warn("failed to create epoll instance: %s\n",
11011 libbpf_strerror_r(err, msg, sizeof(msg)));
11015 if (p->cpu_cnt > 0) {
11016 pb->cpu_cnt = p->cpu_cnt;
11018 pb->cpu_cnt = libbpf_num_possible_cpus();
11019 if (pb->cpu_cnt < 0) {
11023 if (map.max_entries && map.max_entries < pb->cpu_cnt)
11024 pb->cpu_cnt = map.max_entries;
11027 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11030 pr_warn("failed to allocate events: out of memory\n");
11033 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11034 if (!pb->cpu_bufs) {
11036 pr_warn("failed to allocate buffers: out of memory\n");
11040 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11042 pr_warn("failed to get online CPU mask: %d\n", err);
11046 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11047 struct perf_cpu_buf *cpu_buf;
11050 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11051 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11053 /* in case user didn't explicitly requested particular CPUs to
11054 * be attached to, skip offline/not present CPUs
11056 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11059 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11060 if (IS_ERR(cpu_buf)) {
11061 err = PTR_ERR(cpu_buf);
11065 pb->cpu_bufs[j] = cpu_buf;
11067 err = bpf_map_update_elem(pb->map_fd, &map_key,
11071 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11072 cpu, map_key, cpu_buf->fd,
11073 libbpf_strerror_r(err, msg, sizeof(msg)));
11077 pb->events[j].events = EPOLLIN;
11078 pb->events[j].data.ptr = cpu_buf;
11079 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11080 &pb->events[j]) < 0) {
11082 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11084 libbpf_strerror_r(err, msg, sizeof(msg)));
11097 perf_buffer__free(pb);
11098 return ERR_PTR(err);
11101 struct perf_sample_raw {
11102 struct perf_event_header header;
11107 struct perf_sample_lost {
11108 struct perf_event_header header;
11111 uint64_t sample_id;
11114 static enum bpf_perf_event_ret
11115 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11117 struct perf_cpu_buf *cpu_buf = ctx;
11118 struct perf_buffer *pb = cpu_buf->pb;
11121 /* user wants full control over parsing perf event */
11123 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11126 case PERF_RECORD_SAMPLE: {
11127 struct perf_sample_raw *s = data;
11130 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11133 case PERF_RECORD_LOST: {
11134 struct perf_sample_lost *s = data;
11137 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11141 pr_warn("unknown perf sample type %d\n", e->type);
11142 return LIBBPF_PERF_EVENT_ERROR;
11144 return LIBBPF_PERF_EVENT_CONT;
11147 static int perf_buffer__process_records(struct perf_buffer *pb,
11148 struct perf_cpu_buf *cpu_buf)
11150 enum bpf_perf_event_ret ret;
11152 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11153 pb->page_size, &cpu_buf->buf,
11154 &cpu_buf->buf_size,
11155 perf_buffer__process_record, cpu_buf);
11156 if (ret != LIBBPF_PERF_EVENT_CONT)
11161 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11163 return pb->epoll_fd;
11166 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11170 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11174 for (i = 0; i < cnt; i++) {
11175 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11177 err = perf_buffer__process_records(pb, cpu_buf);
11179 pr_warn("error while processing records: %d\n", err);
11180 return libbpf_err(err);
11186 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11189 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11191 return pb->cpu_cnt;
11195 * Return perf_event FD of a ring buffer in *buf_idx* slot of
11196 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11197 * select()/poll()/epoll() Linux syscalls.
11199 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11201 struct perf_cpu_buf *cpu_buf;
11203 if (buf_idx >= pb->cpu_cnt)
11204 return libbpf_err(-EINVAL);
11206 cpu_buf = pb->cpu_bufs[buf_idx];
11208 return libbpf_err(-ENOENT);
11210 return cpu_buf->fd;
11214 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11215 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11216 * consume, do nothing and return success.
11221 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11223 struct perf_cpu_buf *cpu_buf;
11225 if (buf_idx >= pb->cpu_cnt)
11226 return libbpf_err(-EINVAL);
11228 cpu_buf = pb->cpu_bufs[buf_idx];
11230 return libbpf_err(-ENOENT);
11232 return perf_buffer__process_records(pb, cpu_buf);
11235 int perf_buffer__consume(struct perf_buffer *pb)
11239 for (i = 0; i < pb->cpu_cnt; i++) {
11240 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11245 err = perf_buffer__process_records(pb, cpu_buf);
11247 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
11248 return libbpf_err(err);
11254 struct bpf_prog_info_array_desc {
11255 int array_offset; /* e.g. offset of jited_prog_insns */
11256 int count_offset; /* e.g. offset of jited_prog_len */
11257 int size_offset; /* > 0: offset of rec size,
11258 * < 0: fix size of -size_offset
11262 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
11263 [BPF_PROG_INFO_JITED_INSNS] = {
11264 offsetof(struct bpf_prog_info, jited_prog_insns),
11265 offsetof(struct bpf_prog_info, jited_prog_len),
11268 [BPF_PROG_INFO_XLATED_INSNS] = {
11269 offsetof(struct bpf_prog_info, xlated_prog_insns),
11270 offsetof(struct bpf_prog_info, xlated_prog_len),
11273 [BPF_PROG_INFO_MAP_IDS] = {
11274 offsetof(struct bpf_prog_info, map_ids),
11275 offsetof(struct bpf_prog_info, nr_map_ids),
11276 -(int)sizeof(__u32),
11278 [BPF_PROG_INFO_JITED_KSYMS] = {
11279 offsetof(struct bpf_prog_info, jited_ksyms),
11280 offsetof(struct bpf_prog_info, nr_jited_ksyms),
11281 -(int)sizeof(__u64),
11283 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
11284 offsetof(struct bpf_prog_info, jited_func_lens),
11285 offsetof(struct bpf_prog_info, nr_jited_func_lens),
11286 -(int)sizeof(__u32),
11288 [BPF_PROG_INFO_FUNC_INFO] = {
11289 offsetof(struct bpf_prog_info, func_info),
11290 offsetof(struct bpf_prog_info, nr_func_info),
11291 offsetof(struct bpf_prog_info, func_info_rec_size),
11293 [BPF_PROG_INFO_LINE_INFO] = {
11294 offsetof(struct bpf_prog_info, line_info),
11295 offsetof(struct bpf_prog_info, nr_line_info),
11296 offsetof(struct bpf_prog_info, line_info_rec_size),
11298 [BPF_PROG_INFO_JITED_LINE_INFO] = {
11299 offsetof(struct bpf_prog_info, jited_line_info),
11300 offsetof(struct bpf_prog_info, nr_jited_line_info),
11301 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
11303 [BPF_PROG_INFO_PROG_TAGS] = {
11304 offsetof(struct bpf_prog_info, prog_tags),
11305 offsetof(struct bpf_prog_info, nr_prog_tags),
11306 -(int)sizeof(__u8) * BPF_TAG_SIZE,
11311 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
11314 __u32 *array = (__u32 *)info;
11317 return array[offset / sizeof(__u32)];
11318 return -(int)offset;
11321 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
11324 __u64 *array = (__u64 *)info;
11327 return array[offset / sizeof(__u64)];
11328 return -(int)offset;
11331 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
11334 __u32 *array = (__u32 *)info;
11337 array[offset / sizeof(__u32)] = val;
11340 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
11343 __u64 *array = (__u64 *)info;
11346 array[offset / sizeof(__u64)] = val;
11349 struct bpf_prog_info_linear *
11350 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
11352 struct bpf_prog_info_linear *info_linear;
11353 struct bpf_prog_info info = {};
11354 __u32 info_len = sizeof(info);
11355 __u32 data_len = 0;
11359 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
11360 return libbpf_err_ptr(-EINVAL);
11362 /* step 1: get array dimensions */
11363 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
11365 pr_debug("can't get prog info: %s", strerror(errno));
11366 return libbpf_err_ptr(-EFAULT);
11369 /* step 2: calculate total size of all arrays */
11370 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11371 bool include_array = (arrays & (1UL << i)) > 0;
11372 struct bpf_prog_info_array_desc *desc;
11375 desc = bpf_prog_info_array_desc + i;
11377 /* kernel is too old to support this field */
11378 if (info_len < desc->array_offset + sizeof(__u32) ||
11379 info_len < desc->count_offset + sizeof(__u32) ||
11380 (desc->size_offset > 0 && info_len < desc->size_offset))
11381 include_array = false;
11383 if (!include_array) {
11384 arrays &= ~(1UL << i); /* clear the bit */
11388 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11389 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11391 data_len += count * size;
11394 /* step 3: allocate continuous memory */
11395 data_len = roundup(data_len, sizeof(__u64));
11396 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
11398 return libbpf_err_ptr(-ENOMEM);
11400 /* step 4: fill data to info_linear->info */
11401 info_linear->arrays = arrays;
11402 memset(&info_linear->info, 0, sizeof(info));
11403 ptr = info_linear->data;
11405 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11406 struct bpf_prog_info_array_desc *desc;
11409 if ((arrays & (1UL << i)) == 0)
11412 desc = bpf_prog_info_array_desc + i;
11413 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11414 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11415 bpf_prog_info_set_offset_u32(&info_linear->info,
11416 desc->count_offset, count);
11417 bpf_prog_info_set_offset_u32(&info_linear->info,
11418 desc->size_offset, size);
11419 bpf_prog_info_set_offset_u64(&info_linear->info,
11420 desc->array_offset,
11422 ptr += count * size;
11425 /* step 5: call syscall again to get required arrays */
11426 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
11428 pr_debug("can't get prog info: %s", strerror(errno));
11430 return libbpf_err_ptr(-EFAULT);
11433 /* step 6: verify the data */
11434 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11435 struct bpf_prog_info_array_desc *desc;
11438 if ((arrays & (1UL << i)) == 0)
11441 desc = bpf_prog_info_array_desc + i;
11442 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11443 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11444 desc->count_offset);
11446 pr_warn("%s: mismatch in element count\n", __func__);
11448 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11449 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11450 desc->size_offset);
11452 pr_warn("%s: mismatch in rec size\n", __func__);
11455 /* step 7: update info_len and data_len */
11456 info_linear->info_len = sizeof(struct bpf_prog_info);
11457 info_linear->data_len = data_len;
11459 return info_linear;
11462 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
11466 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11467 struct bpf_prog_info_array_desc *desc;
11470 if ((info_linear->arrays & (1UL << i)) == 0)
11473 desc = bpf_prog_info_array_desc + i;
11474 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
11475 desc->array_offset);
11476 offs = addr - ptr_to_u64(info_linear->data);
11477 bpf_prog_info_set_offset_u64(&info_linear->info,
11478 desc->array_offset, offs);
11482 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
11486 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11487 struct bpf_prog_info_array_desc *desc;
11490 if ((info_linear->arrays & (1UL << i)) == 0)
11493 desc = bpf_prog_info_array_desc + i;
11494 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
11495 desc->array_offset);
11496 addr = offs + ptr_to_u64(info_linear->data);
11497 bpf_prog_info_set_offset_u64(&info_linear->info,
11498 desc->array_offset, addr);
11502 int bpf_program__set_attach_target(struct bpf_program *prog,
11503 int attach_prog_fd,
11504 const char *attach_func_name)
11506 int btf_obj_fd = 0, btf_id = 0, err;
11508 if (!prog || attach_prog_fd < 0)
11509 return libbpf_err(-EINVAL);
11511 if (prog->obj->loaded)
11512 return libbpf_err(-EINVAL);
11514 if (attach_prog_fd && !attach_func_name) {
11515 /* remember attach_prog_fd and let bpf_program__load() find
11516 * BTF ID during the program load
11518 prog->attach_prog_fd = attach_prog_fd;
11522 if (attach_prog_fd) {
11523 btf_id = libbpf_find_prog_btf_id(attach_func_name,
11526 return libbpf_err(btf_id);
11528 if (!attach_func_name)
11529 return libbpf_err(-EINVAL);
11531 /* load btf_vmlinux, if not yet */
11532 err = bpf_object__load_vmlinux_btf(prog->obj, true);
11534 return libbpf_err(err);
11535 err = find_kernel_btf_id(prog->obj, attach_func_name,
11536 prog->expected_attach_type,
11537 &btf_obj_fd, &btf_id);
11539 return libbpf_err(err);
11542 prog->attach_btf_id = btf_id;
11543 prog->attach_btf_obj_fd = btf_obj_fd;
11544 prog->attach_prog_fd = attach_prog_fd;
11548 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
11550 int err = 0, n, len, start, end = -1;
11556 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
11558 if (*s == ',' || *s == '\n') {
11562 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
11563 if (n <= 0 || n > 2) {
11564 pr_warn("Failed to get CPU range %s: %d\n", s, n);
11567 } else if (n == 1) {
11570 if (start < 0 || start > end) {
11571 pr_warn("Invalid CPU range [%d,%d] in %s\n",
11576 tmp = realloc(*mask, end + 1);
11582 memset(tmp + *mask_sz, 0, start - *mask_sz);
11583 memset(tmp + start, 1, end - start + 1);
11584 *mask_sz = end + 1;
11588 pr_warn("Empty CPU range\n");
11598 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
11600 int fd, err = 0, len;
11603 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
11606 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
11609 len = read(fd, buf, sizeof(buf));
11612 err = len ? -errno : -EINVAL;
11613 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
11616 if (len >= sizeof(buf)) {
11617 pr_warn("CPU mask is too big in file %s\n", fcpu);
11622 return parse_cpu_mask_str(buf, mask, mask_sz);
11625 int libbpf_num_possible_cpus(void)
11627 static const char *fcpu = "/sys/devices/system/cpu/possible";
11629 int err, n, i, tmp_cpus;
11632 tmp_cpus = READ_ONCE(cpus);
11636 err = parse_cpu_mask_file(fcpu, &mask, &n);
11638 return libbpf_err(err);
11641 for (i = 0; i < n; i++) {
11647 WRITE_ONCE(cpus, tmp_cpus);
11651 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
11652 const struct bpf_object_open_opts *opts)
11654 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
11655 .object_name = s->name,
11657 struct bpf_object *obj;
11660 /* Attempt to preserve opts->object_name, unless overriden by user
11661 * explicitly. Overwriting object name for skeletons is discouraged,
11662 * as it breaks global data maps, because they contain object name
11663 * prefix as their own map name prefix. When skeleton is generated,
11664 * bpftool is making an assumption that this name will stay the same.
11667 memcpy(&skel_opts, opts, sizeof(*opts));
11668 if (!opts->object_name)
11669 skel_opts.object_name = s->name;
11672 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
11673 err = libbpf_get_error(obj);
11675 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
11677 return libbpf_err(err);
11682 for (i = 0; i < s->map_cnt; i++) {
11683 struct bpf_map **map = s->maps[i].map;
11684 const char *name = s->maps[i].name;
11685 void **mmaped = s->maps[i].mmaped;
11687 *map = bpf_object__find_map_by_name(obj, name);
11689 pr_warn("failed to find skeleton map '%s'\n", name);
11690 return libbpf_err(-ESRCH);
11693 /* externs shouldn't be pre-setup from user code */
11694 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
11695 *mmaped = (*map)->mmaped;
11698 for (i = 0; i < s->prog_cnt; i++) {
11699 struct bpf_program **prog = s->progs[i].prog;
11700 const char *name = s->progs[i].name;
11702 *prog = bpf_object__find_program_by_name(obj, name);
11704 pr_warn("failed to find skeleton program '%s'\n", name);
11705 return libbpf_err(-ESRCH);
11712 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11716 err = bpf_object__load(*s->obj);
11718 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
11719 return libbpf_err(err);
11722 for (i = 0; i < s->map_cnt; i++) {
11723 struct bpf_map *map = *s->maps[i].map;
11724 size_t mmap_sz = bpf_map_mmap_sz(map);
11725 int prot, map_fd = bpf_map__fd(map);
11726 void **mmaped = s->maps[i].mmaped;
11731 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11736 if (map->def.map_flags & BPF_F_RDONLY_PROG)
11739 prot = PROT_READ | PROT_WRITE;
11741 /* Remap anonymous mmap()-ed "map initialization image" as
11742 * a BPF map-backed mmap()-ed memory, but preserving the same
11743 * memory address. This will cause kernel to change process'
11744 * page table to point to a different piece of kernel memory,
11745 * but from userspace point of view memory address (and its
11746 * contents, being identical at this point) will stay the
11747 * same. This mapping will be released by bpf_object__close()
11748 * as per normal clean up procedure, so we don't need to worry
11749 * about it from skeleton's clean up perspective.
11751 *mmaped = mmap(map->mmaped, mmap_sz, prot,
11752 MAP_SHARED | MAP_FIXED, map_fd, 0);
11753 if (*mmaped == MAP_FAILED) {
11756 pr_warn("failed to re-mmap() map '%s': %d\n",
11757 bpf_map__name(map), err);
11758 return libbpf_err(err);
11765 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11769 for (i = 0; i < s->prog_cnt; i++) {
11770 struct bpf_program *prog = *s->progs[i].prog;
11771 struct bpf_link **link = s->progs[i].link;
11776 /* auto-attaching not supported for this program */
11777 if (!prog->sec_def || !prog->sec_def->attach_fn)
11780 *link = bpf_program__attach(prog);
11781 err = libbpf_get_error(*link);
11783 pr_warn("failed to auto-attach program '%s': %d\n",
11784 bpf_program__name(prog), err);
11785 return libbpf_err(err);
11792 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11796 for (i = 0; i < s->prog_cnt; i++) {
11797 struct bpf_link **link = s->progs[i].link;
11799 bpf_link__destroy(*link);
11804 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11810 bpf_object__detach_skeleton(s);
11812 bpf_object__close(*s->obj);