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);
190 enum kern_feature_id {
191 /* v4.14: kernel support for program & map names. */
193 /* v5.2: kernel support for global data sections. */
197 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
199 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
201 /* BTF_FUNC_GLOBAL is supported */
202 FEAT_BTF_GLOBAL_FUNC,
203 /* BPF_F_MMAPABLE is supported for arrays */
205 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
206 FEAT_EXP_ATTACH_TYPE,
207 /* bpf_probe_read_{kernel,user}[_str] helpers */
208 FEAT_PROBE_READ_KERN,
209 /* BPF_PROG_BIND_MAP is supported */
211 /* Kernel support for module BTFs */
213 /* BTF_KIND_FLOAT support */
215 /* BPF perf link support */
217 /* BTF_KIND_DECL_TAG support */
219 /* BTF_KIND_TYPE_TAG support */
224 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
237 enum reloc_type type;
240 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
250 typedef int (*init_fn_t)(struct bpf_program *prog, long cookie);
251 typedef int (*preload_fn_t)(struct bpf_program *prog, struct bpf_prog_load_opts *opts, long cookie);
252 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_program *prog, long cookie);
254 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
257 /* expected_attach_type is optional, if kernel doesn't support that */
258 SEC_EXP_ATTACH_OPT = 1,
259 /* legacy, only used by libbpf_get_type_names() and
260 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
261 * This used to be associated with cgroup (and few other) BPF programs
262 * that were attachable through BPF_PROG_ATTACH command. Pretty
263 * meaningless nowadays, though.
266 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
267 /* attachment target is specified through BTF ID in either kernel or
268 * other BPF program's BTF object */
270 /* BPF program type allows sleeping/blocking in kernel */
272 /* allow non-strict prefix matching */
278 enum bpf_prog_type prog_type;
279 enum bpf_attach_type expected_attach_type;
283 preload_fn_t preload_fn;
284 attach_fn_t attach_fn;
288 * bpf_prog should be a better name but it has been used in
292 const struct bpf_sec_def *sec_def;
295 /* this program's instruction offset (in number of instructions)
296 * within its containing ELF section
299 /* number of original instructions in ELF section belonging to this
300 * program, not taking into account subprogram instructions possible
301 * appended later during relocation
304 /* Offset (in number of instructions) of the start of instruction
305 * belonging to this BPF program within its containing main BPF
306 * program. For the entry-point (main) BPF program, this is always
307 * zero. For a sub-program, this gets reset before each of main BPF
308 * programs are processed and relocated and is used to determined
309 * whether sub-program was already appended to the main program, and
310 * if yes, at which instruction offset.
315 /* name with / replaced by _; makes recursive pinning
316 * in bpf_object__pin_programs easier
320 /* instructions that belong to BPF program; insns[0] is located at
321 * sec_insn_off instruction within its ELF section in ELF file, so
322 * when mapping ELF file instruction index to the local instruction,
323 * one needs to subtract sec_insn_off; and vice versa.
325 struct bpf_insn *insns;
326 /* actual number of instruction in this BPF program's image; for
327 * entry-point BPF programs this includes the size of main program
328 * itself plus all the used sub-programs, appended at the end
332 struct reloc_desc *reloc_desc;
335 /* BPF verifier log settings */
344 bpf_program_prep_t preprocessor;
346 struct bpf_object *obj;
348 bpf_program_clear_priv_t clear_priv;
351 bool mark_btf_static;
352 enum bpf_prog_type type;
353 enum bpf_attach_type expected_attach_type;
355 __u32 attach_btf_obj_fd;
357 __u32 attach_prog_fd;
359 __u32 func_info_rec_size;
363 __u32 line_info_rec_size;
368 struct bpf_struct_ops {
370 const struct btf_type *type;
371 struct bpf_program **progs;
372 __u32 *kern_func_off;
373 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
375 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
376 * btf_vmlinux's format.
377 * struct bpf_struct_ops_tcp_congestion_ops {
378 * [... some other kernel fields ...]
379 * struct tcp_congestion_ops data;
381 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
382 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
389 #define DATA_SEC ".data"
390 #define BSS_SEC ".bss"
391 #define RODATA_SEC ".rodata"
392 #define KCONFIG_SEC ".kconfig"
393 #define KSYMS_SEC ".ksyms"
394 #define STRUCT_OPS_SEC ".struct_ops"
396 enum libbpf_map_type {
406 /* real_name is defined for special internal maps (.rodata*,
407 * .data*, .bss, .kconfig) and preserves their original ELF section
408 * name. This is important to be be able to find corresponding BTF
409 * DATASEC information.
417 struct bpf_map_def def;
420 __u32 btf_key_type_id;
421 __u32 btf_value_type_id;
422 __u32 btf_vmlinux_value_type_id;
424 bpf_map_clear_priv_t clear_priv;
425 enum libbpf_map_type libbpf_type;
427 struct bpf_struct_ops *st_ops;
428 struct bpf_map *inner_map;
454 enum extern_type type;
470 unsigned long long addr;
472 /* target btf_id of the corresponding kernel var. */
473 int kernel_btf_obj_fd;
476 /* local btf_id of the ksym extern's type. */
478 /* BTF fd index to be patched in for insn->off, this is
479 * 0 for vmlinux BTF, index in obj->fd_array for module
487 static LIST_HEAD(bpf_objects_list);
505 struct elf_sec_desc {
506 enum sec_type sec_type;
518 Elf_Data *st_ops_data;
519 size_t shstrndx; /* section index for section name strings */
521 struct elf_sec_desc *secs;
525 __u32 btf_maps_sec_btf_id;
532 char name[BPF_OBJ_NAME_LEN];
536 struct bpf_program *programs;
538 struct bpf_map *maps;
543 struct extern_desc *externs;
551 struct bpf_gen *gen_loader;
553 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
554 struct elf_state efile;
556 * All loaded bpf_object are linked in a list, which is
557 * hidden to caller. bpf_objects__<func> handlers deal with
560 struct list_head list;
563 struct btf_ext *btf_ext;
565 /* Parse and load BTF vmlinux if any of the programs in the object need
568 struct btf *btf_vmlinux;
569 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
570 * override for vmlinux BTF.
572 char *btf_custom_path;
573 /* vmlinux BTF override for CO-RE relocations */
574 struct btf *btf_vmlinux_override;
575 /* Lazily initialized kernel module BTFs */
576 struct module_btf *btf_modules;
577 bool btf_modules_loaded;
578 size_t btf_module_cnt;
579 size_t btf_module_cap;
581 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
587 bpf_object_clear_priv_t clear_priv;
596 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
597 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
598 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
599 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
600 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
601 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
602 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
603 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
604 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
606 void bpf_program__unload(struct bpf_program *prog)
614 * If the object is opened but the program was never loaded,
615 * it is possible that prog->instances.nr == -1.
617 if (prog->instances.nr > 0) {
618 for (i = 0; i < prog->instances.nr; i++)
619 zclose(prog->instances.fds[i]);
620 } else if (prog->instances.nr != -1) {
621 pr_warn("Internal error: instances.nr is %d\n",
625 prog->instances.nr = -1;
626 zfree(&prog->instances.fds);
628 zfree(&prog->func_info);
629 zfree(&prog->line_info);
632 static void bpf_program__exit(struct bpf_program *prog)
637 if (prog->clear_priv)
638 prog->clear_priv(prog, prog->priv);
641 prog->clear_priv = NULL;
643 bpf_program__unload(prog);
645 zfree(&prog->sec_name);
646 zfree(&prog->pin_name);
648 zfree(&prog->reloc_desc);
655 static char *__bpf_program__pin_name(struct bpf_program *prog)
659 if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
660 name = strdup(prog->name);
662 name = strdup(prog->sec_name);
669 while ((p = strchr(p, '/')))
675 static bool insn_is_subprog_call(const struct bpf_insn *insn)
677 return BPF_CLASS(insn->code) == BPF_JMP &&
678 BPF_OP(insn->code) == BPF_CALL &&
679 BPF_SRC(insn->code) == BPF_K &&
680 insn->src_reg == BPF_PSEUDO_CALL &&
681 insn->dst_reg == 0 &&
685 static bool is_call_insn(const struct bpf_insn *insn)
687 return insn->code == (BPF_JMP | BPF_CALL);
690 static bool insn_is_pseudo_func(struct bpf_insn *insn)
692 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
696 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
697 const char *name, size_t sec_idx, const char *sec_name,
698 size_t sec_off, void *insn_data, size_t insn_data_sz)
700 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
701 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
702 sec_name, name, sec_off, insn_data_sz);
706 memset(prog, 0, sizeof(*prog));
709 prog->sec_idx = sec_idx;
710 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
711 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
712 /* insns_cnt can later be increased by appending used subprograms */
713 prog->insns_cnt = prog->sec_insn_cnt;
715 prog->type = BPF_PROG_TYPE_UNSPEC;
718 prog->instances.fds = NULL;
719 prog->instances.nr = -1;
721 /* inherit object's log_level */
722 prog->log_level = obj->log_level;
724 prog->sec_name = strdup(sec_name);
728 prog->name = strdup(name);
732 prog->pin_name = __bpf_program__pin_name(prog);
736 prog->insns = malloc(insn_data_sz);
739 memcpy(prog->insns, insn_data, insn_data_sz);
743 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
744 bpf_program__exit(prog);
749 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
750 const char *sec_name, int sec_idx)
752 Elf_Data *symbols = obj->efile.symbols;
753 struct bpf_program *prog, *progs;
754 void *data = sec_data->d_buf;
755 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
756 int nr_progs, err, i;
760 progs = obj->programs;
761 nr_progs = obj->nr_programs;
762 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
765 for (i = 0; i < nr_syms; i++) {
766 sym = elf_sym_by_idx(obj, i);
768 if (sym->st_shndx != sec_idx)
770 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
773 prog_sz = sym->st_size;
774 sec_off = sym->st_value;
776 name = elf_sym_str(obj, sym->st_name);
778 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
780 return -LIBBPF_ERRNO__FORMAT;
783 if (sec_off + prog_sz > sec_sz) {
784 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
786 return -LIBBPF_ERRNO__FORMAT;
789 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
790 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
794 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
795 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
797 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
800 * In this case the original obj->programs
801 * is still valid, so don't need special treat for
802 * bpf_close_object().
804 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
808 obj->programs = progs;
810 prog = &progs[nr_progs];
812 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
813 sec_off, data + sec_off, prog_sz);
817 /* if function is a global/weak symbol, but has restricted
818 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
819 * as static to enable more permissive BPF verification mode
820 * with more outside context available to BPF verifier
822 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
823 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
824 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
825 prog->mark_btf_static = true;
828 obj->nr_programs = nr_progs;
834 static __u32 get_kernel_version(void)
836 __u32 major, minor, patch;
840 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
842 return KERNEL_VERSION(major, minor, patch);
845 static const struct btf_member *
846 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
848 struct btf_member *m;
851 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
852 if (btf_member_bit_offset(t, i) == bit_offset)
859 static const struct btf_member *
860 find_member_by_name(const struct btf *btf, const struct btf_type *t,
863 struct btf_member *m;
866 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
867 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
874 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
875 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
876 const char *name, __u32 kind);
879 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
880 const struct btf_type **type, __u32 *type_id,
881 const struct btf_type **vtype, __u32 *vtype_id,
882 const struct btf_member **data_member)
884 const struct btf_type *kern_type, *kern_vtype;
885 const struct btf_member *kern_data_member;
886 __s32 kern_vtype_id, kern_type_id;
889 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
890 if (kern_type_id < 0) {
891 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
895 kern_type = btf__type_by_id(btf, kern_type_id);
897 /* Find the corresponding "map_value" type that will be used
898 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
899 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
902 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
903 tname, BTF_KIND_STRUCT);
904 if (kern_vtype_id < 0) {
905 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
906 STRUCT_OPS_VALUE_PREFIX, tname);
907 return kern_vtype_id;
909 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
911 /* Find "struct tcp_congestion_ops" from
912 * struct bpf_struct_ops_tcp_congestion_ops {
914 * struct tcp_congestion_ops data;
917 kern_data_member = btf_members(kern_vtype);
918 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
919 if (kern_data_member->type == kern_type_id)
922 if (i == btf_vlen(kern_vtype)) {
923 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
924 tname, STRUCT_OPS_VALUE_PREFIX, tname);
929 *type_id = kern_type_id;
931 *vtype_id = kern_vtype_id;
932 *data_member = kern_data_member;
937 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
939 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
942 /* Init the map's fields that depend on kern_btf */
943 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
944 const struct btf *btf,
945 const struct btf *kern_btf)
947 const struct btf_member *member, *kern_member, *kern_data_member;
948 const struct btf_type *type, *kern_type, *kern_vtype;
949 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
950 struct bpf_struct_ops *st_ops;
951 void *data, *kern_data;
955 st_ops = map->st_ops;
957 tname = st_ops->tname;
958 err = find_struct_ops_kern_types(kern_btf, tname,
959 &kern_type, &kern_type_id,
960 &kern_vtype, &kern_vtype_id,
965 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
966 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
968 map->def.value_size = kern_vtype->size;
969 map->btf_vmlinux_value_type_id = kern_vtype_id;
971 st_ops->kern_vdata = calloc(1, kern_vtype->size);
972 if (!st_ops->kern_vdata)
976 kern_data_off = kern_data_member->offset / 8;
977 kern_data = st_ops->kern_vdata + kern_data_off;
979 member = btf_members(type);
980 for (i = 0; i < btf_vlen(type); i++, member++) {
981 const struct btf_type *mtype, *kern_mtype;
982 __u32 mtype_id, kern_mtype_id;
983 void *mdata, *kern_mdata;
984 __s64 msize, kern_msize;
985 __u32 moff, kern_moff;
986 __u32 kern_member_idx;
989 mname = btf__name_by_offset(btf, member->name_off);
990 kern_member = find_member_by_name(kern_btf, kern_type, mname);
992 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
997 kern_member_idx = kern_member - btf_members(kern_type);
998 if (btf_member_bitfield_size(type, i) ||
999 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1000 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1005 moff = member->offset / 8;
1006 kern_moff = kern_member->offset / 8;
1008 mdata = data + moff;
1009 kern_mdata = kern_data + kern_moff;
1011 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1012 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1014 if (BTF_INFO_KIND(mtype->info) !=
1015 BTF_INFO_KIND(kern_mtype->info)) {
1016 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1017 map->name, mname, BTF_INFO_KIND(mtype->info),
1018 BTF_INFO_KIND(kern_mtype->info));
1022 if (btf_is_ptr(mtype)) {
1023 struct bpf_program *prog;
1025 prog = st_ops->progs[i];
1029 kern_mtype = skip_mods_and_typedefs(kern_btf,
1033 /* mtype->type must be a func_proto which was
1034 * guaranteed in bpf_object__collect_st_ops_relos(),
1035 * so only check kern_mtype for func_proto here.
1037 if (!btf_is_func_proto(kern_mtype)) {
1038 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1043 prog->attach_btf_id = kern_type_id;
1044 prog->expected_attach_type = kern_member_idx;
1046 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1048 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1049 map->name, mname, prog->name, moff,
1055 msize = btf__resolve_size(btf, mtype_id);
1056 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1057 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1058 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1059 map->name, mname, (ssize_t)msize,
1060 (ssize_t)kern_msize);
1064 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1065 map->name, mname, (unsigned int)msize,
1067 memcpy(kern_mdata, mdata, msize);
1073 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1075 struct bpf_map *map;
1079 for (i = 0; i < obj->nr_maps; i++) {
1080 map = &obj->maps[i];
1082 if (!bpf_map__is_struct_ops(map))
1085 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1094 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1096 const struct btf_type *type, *datasec;
1097 const struct btf_var_secinfo *vsi;
1098 struct bpf_struct_ops *st_ops;
1099 const char *tname, *var_name;
1100 __s32 type_id, datasec_id;
1101 const struct btf *btf;
1102 struct bpf_map *map;
1105 if (obj->efile.st_ops_shndx == -1)
1109 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1111 if (datasec_id < 0) {
1112 pr_warn("struct_ops init: DATASEC %s not found\n",
1117 datasec = btf__type_by_id(btf, datasec_id);
1118 vsi = btf_var_secinfos(datasec);
1119 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1120 type = btf__type_by_id(obj->btf, vsi->type);
1121 var_name = btf__name_by_offset(obj->btf, type->name_off);
1123 type_id = btf__resolve_type(obj->btf, vsi->type);
1125 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1126 vsi->type, STRUCT_OPS_SEC);
1130 type = btf__type_by_id(obj->btf, type_id);
1131 tname = btf__name_by_offset(obj->btf, type->name_off);
1133 pr_warn("struct_ops init: anonymous type is not supported\n");
1136 if (!btf_is_struct(type)) {
1137 pr_warn("struct_ops init: %s is not a struct\n", tname);
1141 map = bpf_object__add_map(obj);
1143 return PTR_ERR(map);
1145 map->sec_idx = obj->efile.st_ops_shndx;
1146 map->sec_offset = vsi->offset;
1147 map->name = strdup(var_name);
1151 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1152 map->def.key_size = sizeof(int);
1153 map->def.value_size = type->size;
1154 map->def.max_entries = 1;
1156 map->st_ops = calloc(1, sizeof(*map->st_ops));
1159 st_ops = map->st_ops;
1160 st_ops->data = malloc(type->size);
1161 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1162 st_ops->kern_func_off = malloc(btf_vlen(type) *
1163 sizeof(*st_ops->kern_func_off));
1164 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1167 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1168 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1169 var_name, STRUCT_OPS_SEC);
1173 memcpy(st_ops->data,
1174 obj->efile.st_ops_data->d_buf + vsi->offset,
1176 st_ops->tname = tname;
1177 st_ops->type = type;
1178 st_ops->type_id = type_id;
1180 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1181 tname, type_id, var_name, vsi->offset);
1187 static struct bpf_object *bpf_object__new(const char *path,
1188 const void *obj_buf,
1190 const char *obj_name)
1192 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1193 struct bpf_object *obj;
1196 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1198 pr_warn("alloc memory failed for %s\n", path);
1199 return ERR_PTR(-ENOMEM);
1202 strcpy(obj->path, path);
1204 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1205 obj->name[sizeof(obj->name) - 1] = 0;
1207 /* Using basename() GNU version which doesn't modify arg. */
1208 strncpy(obj->name, basename((void *)path),
1209 sizeof(obj->name) - 1);
1210 end = strchr(obj->name, '.');
1217 * Caller of this function should also call
1218 * bpf_object__elf_finish() after data collection to return
1219 * obj_buf to user. If not, we should duplicate the buffer to
1220 * avoid user freeing them before elf finish.
1222 obj->efile.obj_buf = obj_buf;
1223 obj->efile.obj_buf_sz = obj_buf_sz;
1224 obj->efile.maps_shndx = -1;
1225 obj->efile.btf_maps_shndx = -1;
1226 obj->efile.st_ops_shndx = -1;
1227 obj->kconfig_map_idx = -1;
1229 obj->kern_version = get_kernel_version();
1230 obj->loaded = false;
1232 INIT_LIST_HEAD(&obj->list);
1234 list_add(&obj->list, &bpf_objects_list);
1238 static void bpf_object__elf_finish(struct bpf_object *obj)
1240 if (!obj->efile.elf)
1243 if (obj->efile.elf) {
1244 elf_end(obj->efile.elf);
1245 obj->efile.elf = NULL;
1247 obj->efile.symbols = NULL;
1248 obj->efile.st_ops_data = NULL;
1250 zfree(&obj->efile.secs);
1251 obj->efile.sec_cnt = 0;
1252 zclose(obj->efile.fd);
1253 obj->efile.obj_buf = NULL;
1254 obj->efile.obj_buf_sz = 0;
1257 static int bpf_object__elf_init(struct bpf_object *obj)
1263 if (obj->efile.elf) {
1264 pr_warn("elf: init internal error\n");
1265 return -LIBBPF_ERRNO__LIBELF;
1268 if (obj->efile.obj_buf_sz > 0) {
1270 * obj_buf should have been validated by
1271 * bpf_object__open_buffer().
1273 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1275 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1276 if (obj->efile.fd < 0) {
1277 char errmsg[STRERR_BUFSIZE], *cp;
1280 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1281 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1285 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1289 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1290 err = -LIBBPF_ERRNO__LIBELF;
1294 obj->efile.elf = elf;
1296 if (elf_kind(elf) != ELF_K_ELF) {
1297 err = -LIBBPF_ERRNO__FORMAT;
1298 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1302 if (gelf_getclass(elf) != ELFCLASS64) {
1303 err = -LIBBPF_ERRNO__FORMAT;
1304 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1308 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1309 if (!obj->efile.ehdr) {
1310 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1311 err = -LIBBPF_ERRNO__FORMAT;
1315 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1316 pr_warn("elf: failed to get section names section index for %s: %s\n",
1317 obj->path, elf_errmsg(-1));
1318 err = -LIBBPF_ERRNO__FORMAT;
1322 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1323 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1324 pr_warn("elf: failed to get section names strings from %s: %s\n",
1325 obj->path, elf_errmsg(-1));
1326 err = -LIBBPF_ERRNO__FORMAT;
1330 /* Old LLVM set e_machine to EM_NONE */
1331 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1332 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1333 err = -LIBBPF_ERRNO__FORMAT;
1339 bpf_object__elf_finish(obj);
1343 static int bpf_object__check_endianness(struct bpf_object *obj)
1345 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1346 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1348 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1349 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1352 # error "Unrecognized __BYTE_ORDER__"
1354 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1355 return -LIBBPF_ERRNO__ENDIAN;
1359 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1361 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1362 pr_debug("license of %s is %s\n", obj->path, obj->license);
1367 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1371 if (size != sizeof(kver)) {
1372 pr_warn("invalid kver section in %s\n", obj->path);
1373 return -LIBBPF_ERRNO__FORMAT;
1375 memcpy(&kver, data, sizeof(kver));
1376 obj->kern_version = kver;
1377 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1381 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1383 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1384 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1389 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1399 scn = elf_sec_by_name(obj, name);
1400 data = elf_sec_data(obj, scn);
1402 ret = 0; /* found it */
1403 *size = data->d_size;
1406 return *size ? 0 : ret;
1409 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1411 Elf_Data *symbols = obj->efile.symbols;
1418 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1419 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1421 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL ||
1422 ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1425 sname = elf_sym_str(obj, sym->st_name);
1427 pr_warn("failed to get sym name string for var %s\n", name);
1430 if (strcmp(name, sname) == 0) {
1431 *off = sym->st_value;
1439 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1441 struct bpf_map *new_maps;
1445 if (obj->nr_maps < obj->maps_cap)
1446 return &obj->maps[obj->nr_maps++];
1448 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1449 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1451 pr_warn("alloc maps for object failed\n");
1452 return ERR_PTR(-ENOMEM);
1455 obj->maps_cap = new_cap;
1456 obj->maps = new_maps;
1458 /* zero out new maps */
1459 memset(obj->maps + obj->nr_maps, 0,
1460 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1462 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1463 * when failure (zclose won't close negative fd)).
1465 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1466 obj->maps[i].fd = -1;
1467 obj->maps[i].inner_map_fd = -1;
1470 return &obj->maps[obj->nr_maps++];
1473 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1475 long page_sz = sysconf(_SC_PAGE_SIZE);
1478 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1479 map_sz = roundup(map_sz, page_sz);
1483 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1485 char map_name[BPF_OBJ_NAME_LEN], *p;
1486 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1488 /* This is one of the more confusing parts of libbpf for various
1489 * reasons, some of which are historical. The original idea for naming
1490 * internal names was to include as much of BPF object name prefix as
1491 * possible, so that it can be distinguished from similar internal
1492 * maps of a different BPF object.
1493 * As an example, let's say we have bpf_object named 'my_object_name'
1494 * and internal map corresponding to '.rodata' ELF section. The final
1495 * map name advertised to user and to the kernel will be
1496 * 'my_objec.rodata', taking first 8 characters of object name and
1497 * entire 7 characters of '.rodata'.
1498 * Somewhat confusingly, if internal map ELF section name is shorter
1499 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1500 * for the suffix, even though we only have 4 actual characters, and
1501 * resulting map will be called 'my_objec.bss', not even using all 15
1502 * characters allowed by the kernel. Oh well, at least the truncated
1503 * object name is somewhat consistent in this case. But if the map
1504 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1505 * (8 chars) and thus will be left with only first 7 characters of the
1506 * object name ('my_obje'). Happy guessing, user, that the final map
1507 * name will be "my_obje.kconfig".
1508 * Now, with libbpf starting to support arbitrarily named .rodata.*
1509 * and .data.* data sections, it's possible that ELF section name is
1510 * longer than allowed 15 chars, so we now need to be careful to take
1511 * only up to 15 first characters of ELF name, taking no BPF object
1512 * name characters at all. So '.rodata.abracadabra' will result in
1513 * '.rodata.abracad' kernel and user-visible name.
1514 * We need to keep this convoluted logic intact for .data, .bss and
1515 * .rodata maps, but for new custom .data.custom and .rodata.custom
1516 * maps we use their ELF names as is, not prepending bpf_object name
1517 * in front. We still need to truncate them to 15 characters for the
1518 * kernel. Full name can be recovered for such maps by using DATASEC
1519 * BTF type associated with such map's value type, though.
1521 if (sfx_len >= BPF_OBJ_NAME_LEN)
1522 sfx_len = BPF_OBJ_NAME_LEN - 1;
1524 /* if there are two or more dots in map name, it's a custom dot map */
1525 if (strchr(real_name + 1, '.') != NULL)
1528 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1530 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1531 sfx_len, real_name);
1533 /* sanitise map name to characters allowed by kernel */
1534 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1535 if (!isalnum(*p) && *p != '_' && *p != '.')
1538 return strdup(map_name);
1542 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1543 const char *real_name, int sec_idx, void *data, size_t data_sz)
1545 struct bpf_map_def *def;
1546 struct bpf_map *map;
1549 map = bpf_object__add_map(obj);
1551 return PTR_ERR(map);
1553 map->libbpf_type = type;
1554 map->sec_idx = sec_idx;
1555 map->sec_offset = 0;
1556 map->real_name = strdup(real_name);
1557 map->name = internal_map_name(obj, real_name);
1558 if (!map->real_name || !map->name) {
1559 zfree(&map->real_name);
1565 def->type = BPF_MAP_TYPE_ARRAY;
1566 def->key_size = sizeof(int);
1567 def->value_size = data_sz;
1568 def->max_entries = 1;
1569 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1570 ? BPF_F_RDONLY_PROG : 0;
1571 def->map_flags |= BPF_F_MMAPABLE;
1573 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1574 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1576 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1577 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1578 if (map->mmaped == MAP_FAILED) {
1581 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1583 zfree(&map->real_name);
1589 memcpy(map->mmaped, data, data_sz);
1591 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1595 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1597 struct elf_sec_desc *sec_desc;
1598 const char *sec_name;
1599 int err = 0, sec_idx;
1602 * Populate obj->maps with libbpf internal maps.
1604 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1605 sec_desc = &obj->efile.secs[sec_idx];
1607 switch (sec_desc->sec_type) {
1609 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1610 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1612 sec_desc->data->d_buf,
1613 sec_desc->data->d_size);
1616 obj->has_rodata = true;
1617 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1618 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1620 sec_desc->data->d_buf,
1621 sec_desc->data->d_size);
1624 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1625 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1628 sec_desc->data->d_size);
1641 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1646 for (i = 0; i < obj->nr_extern; i++) {
1647 if (strcmp(obj->externs[i].name, name) == 0)
1648 return &obj->externs[i];
1653 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1656 switch (ext->kcfg.type) {
1659 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1663 *(bool *)ext_val = value == 'y' ? true : false;
1667 *(enum libbpf_tristate *)ext_val = TRI_YES;
1668 else if (value == 'm')
1669 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1670 else /* value == 'n' */
1671 *(enum libbpf_tristate *)ext_val = TRI_NO;
1674 *(char *)ext_val = value;
1680 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1688 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1693 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1694 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1698 len = strlen(value);
1699 if (value[len - 1] != '"') {
1700 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1707 if (len >= ext->kcfg.sz) {
1708 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1709 ext->name, value, len, ext->kcfg.sz - 1);
1710 len = ext->kcfg.sz - 1;
1712 memcpy(ext_val, value + 1, len);
1713 ext_val[len] = '\0';
1718 static int parse_u64(const char *value, __u64 *res)
1724 *res = strtoull(value, &value_end, 0);
1727 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1731 pr_warn("failed to parse '%s' as integer completely\n", value);
1737 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1739 int bit_sz = ext->kcfg.sz * 8;
1741 if (ext->kcfg.sz == 8)
1744 /* Validate that value stored in u64 fits in integer of `ext->sz`
1745 * bytes size without any loss of information. If the target integer
1746 * is signed, we rely on the following limits of integer type of
1747 * Y bits and subsequent transformation:
1749 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1750 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1751 * 0 <= X + 2^(Y-1) < 2^Y
1753 * For unsigned target integer, check that all the (64 - Y) bits are
1756 if (ext->kcfg.is_signed)
1757 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1759 return (v >> bit_sz) == 0;
1762 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1765 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1766 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1767 ext->name, (unsigned long long)value);
1770 if (!is_kcfg_value_in_range(ext, value)) {
1771 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1772 ext->name, (unsigned long long)value, ext->kcfg.sz);
1775 switch (ext->kcfg.sz) {
1776 case 1: *(__u8 *)ext_val = value; break;
1777 case 2: *(__u16 *)ext_val = value; break;
1778 case 4: *(__u32 *)ext_val = value; break;
1779 case 8: *(__u64 *)ext_val = value; break;
1787 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1788 char *buf, void *data)
1790 struct extern_desc *ext;
1796 if (!str_has_pfx(buf, "CONFIG_"))
1799 sep = strchr(buf, '=');
1801 pr_warn("failed to parse '%s': no separator\n", buf);
1805 /* Trim ending '\n' */
1807 if (buf[len - 1] == '\n')
1808 buf[len - 1] = '\0';
1809 /* Split on '=' and ensure that a value is present. */
1813 pr_warn("failed to parse '%s': no value\n", buf);
1817 ext = find_extern_by_name(obj, buf);
1818 if (!ext || ext->is_set)
1821 ext_val = data + ext->kcfg.data_off;
1825 case 'y': case 'n': case 'm':
1826 err = set_kcfg_value_tri(ext, ext_val, *value);
1829 err = set_kcfg_value_str(ext, ext_val, value);
1832 /* assume integer */
1833 err = parse_u64(value, &num);
1835 pr_warn("extern (kcfg) %s=%s should be integer\n",
1839 err = set_kcfg_value_num(ext, ext_val, num);
1844 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1848 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1856 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1859 else if (len >= PATH_MAX)
1860 return -ENAMETOOLONG;
1862 /* gzopen also accepts uncompressed files. */
1863 file = gzopen(buf, "r");
1865 file = gzopen("/proc/config.gz", "r");
1868 pr_warn("failed to open system Kconfig\n");
1872 while (gzgets(file, buf, sizeof(buf))) {
1873 err = bpf_object__process_kconfig_line(obj, buf, data);
1875 pr_warn("error parsing system Kconfig line '%s': %d\n",
1886 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1887 const char *config, void *data)
1893 file = fmemopen((void *)config, strlen(config), "r");
1896 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1900 while (fgets(buf, sizeof(buf), file)) {
1901 err = bpf_object__process_kconfig_line(obj, buf, data);
1903 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1913 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1915 struct extern_desc *last_ext = NULL, *ext;
1919 for (i = 0; i < obj->nr_extern; i++) {
1920 ext = &obj->externs[i];
1921 if (ext->type == EXT_KCFG)
1928 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1929 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1930 ".kconfig", obj->efile.symbols_shndx,
1935 obj->kconfig_map_idx = obj->nr_maps - 1;
1940 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1942 Elf_Data *symbols = obj->efile.symbols;
1943 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1944 Elf_Data *data = NULL;
1947 if (obj->efile.maps_shndx < 0)
1953 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1954 data = elf_sec_data(obj, scn);
1955 if (!scn || !data) {
1956 pr_warn("elf: failed to get legacy map definitions for %s\n",
1962 * Count number of maps. Each map has a name.
1963 * Array of maps is not supported: only the first element is
1966 * TODO: Detect array of map and report error.
1968 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
1969 for (i = 0; i < nr_syms; i++) {
1970 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
1972 if (sym->st_shndx != obj->efile.maps_shndx)
1974 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
1978 /* Assume equally sized map definitions */
1979 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1980 nr_maps, data->d_size, obj->path);
1982 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1983 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1987 map_def_sz = data->d_size / nr_maps;
1989 /* Fill obj->maps using data in "maps" section. */
1990 for (i = 0; i < nr_syms; i++) {
1991 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
1992 const char *map_name;
1993 struct bpf_map_def *def;
1994 struct bpf_map *map;
1996 if (sym->st_shndx != obj->efile.maps_shndx)
1998 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
2001 map = bpf_object__add_map(obj);
2003 return PTR_ERR(map);
2005 map_name = elf_sym_str(obj, sym->st_name);
2007 pr_warn("failed to get map #%d name sym string for obj %s\n",
2009 return -LIBBPF_ERRNO__FORMAT;
2012 if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
2013 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2017 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2018 map->sec_idx = sym->st_shndx;
2019 map->sec_offset = sym->st_value;
2020 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2021 map_name, map->sec_idx, map->sec_offset);
2022 if (sym->st_value + map_def_sz > data->d_size) {
2023 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2024 obj->path, map_name);
2028 map->name = strdup(map_name);
2030 pr_warn("map '%s': failed to alloc map name\n", map_name);
2033 pr_debug("map %d is \"%s\"\n", i, map->name);
2034 def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
2036 * If the definition of the map in the object file fits in
2037 * bpf_map_def, copy it. Any extra fields in our version
2038 * of bpf_map_def will default to zero as a result of the
2041 if (map_def_sz <= sizeof(struct bpf_map_def)) {
2042 memcpy(&map->def, def, map_def_sz);
2045 * Here the map structure being read is bigger than what
2046 * we expect, truncate if the excess bits are all zero.
2047 * If they are not zero, reject this map as
2052 for (b = ((char *)def) + sizeof(struct bpf_map_def);
2053 b < ((char *)def) + map_def_sz; b++) {
2055 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
2056 obj->path, map_name);
2061 memcpy(&map->def, def, sizeof(struct bpf_map_def));
2067 const struct btf_type *
2068 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2070 const struct btf_type *t = btf__type_by_id(btf, id);
2075 while (btf_is_mod(t) || btf_is_typedef(t)) {
2078 t = btf__type_by_id(btf, t->type);
2084 static const struct btf_type *
2085 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2087 const struct btf_type *t;
2089 t = skip_mods_and_typedefs(btf, id, NULL);
2093 t = skip_mods_and_typedefs(btf, t->type, res_id);
2095 return btf_is_func_proto(t) ? t : NULL;
2098 static const char *__btf_kind_str(__u16 kind)
2101 case BTF_KIND_UNKN: return "void";
2102 case BTF_KIND_INT: return "int";
2103 case BTF_KIND_PTR: return "ptr";
2104 case BTF_KIND_ARRAY: return "array";
2105 case BTF_KIND_STRUCT: return "struct";
2106 case BTF_KIND_UNION: return "union";
2107 case BTF_KIND_ENUM: return "enum";
2108 case BTF_KIND_FWD: return "fwd";
2109 case BTF_KIND_TYPEDEF: return "typedef";
2110 case BTF_KIND_VOLATILE: return "volatile";
2111 case BTF_KIND_CONST: return "const";
2112 case BTF_KIND_RESTRICT: return "restrict";
2113 case BTF_KIND_FUNC: return "func";
2114 case BTF_KIND_FUNC_PROTO: return "func_proto";
2115 case BTF_KIND_VAR: return "var";
2116 case BTF_KIND_DATASEC: return "datasec";
2117 case BTF_KIND_FLOAT: return "float";
2118 case BTF_KIND_DECL_TAG: return "decl_tag";
2119 case BTF_KIND_TYPE_TAG: return "type_tag";
2120 default: return "unknown";
2124 const char *btf_kind_str(const struct btf_type *t)
2126 return __btf_kind_str(btf_kind(t));
2130 * Fetch integer attribute of BTF map definition. Such attributes are
2131 * represented using a pointer to an array, in which dimensionality of array
2132 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2133 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2134 * type definition, while using only sizeof(void *) space in ELF data section.
2136 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2137 const struct btf_member *m, __u32 *res)
2139 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2140 const char *name = btf__name_by_offset(btf, m->name_off);
2141 const struct btf_array *arr_info;
2142 const struct btf_type *arr_t;
2144 if (!btf_is_ptr(t)) {
2145 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2146 map_name, name, btf_kind_str(t));
2150 arr_t = btf__type_by_id(btf, t->type);
2152 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2153 map_name, name, t->type);
2156 if (!btf_is_array(arr_t)) {
2157 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2158 map_name, name, btf_kind_str(arr_t));
2161 arr_info = btf_array(arr_t);
2162 *res = arr_info->nelems;
2166 static int build_map_pin_path(struct bpf_map *map, const char *path)
2172 path = "/sys/fs/bpf";
2174 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2177 else if (len >= PATH_MAX)
2178 return -ENAMETOOLONG;
2180 return bpf_map__set_pin_path(map, buf);
2183 int parse_btf_map_def(const char *map_name, struct btf *btf,
2184 const struct btf_type *def_t, bool strict,
2185 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2187 const struct btf_type *t;
2188 const struct btf_member *m;
2189 bool is_inner = inner_def == NULL;
2192 vlen = btf_vlen(def_t);
2193 m = btf_members(def_t);
2194 for (i = 0; i < vlen; i++, m++) {
2195 const char *name = btf__name_by_offset(btf, m->name_off);
2198 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2201 if (strcmp(name, "type") == 0) {
2202 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2204 map_def->parts |= MAP_DEF_MAP_TYPE;
2205 } else if (strcmp(name, "max_entries") == 0) {
2206 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2208 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2209 } else if (strcmp(name, "map_flags") == 0) {
2210 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2212 map_def->parts |= MAP_DEF_MAP_FLAGS;
2213 } else if (strcmp(name, "numa_node") == 0) {
2214 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2216 map_def->parts |= MAP_DEF_NUMA_NODE;
2217 } else if (strcmp(name, "key_size") == 0) {
2220 if (!get_map_field_int(map_name, btf, m, &sz))
2222 if (map_def->key_size && map_def->key_size != sz) {
2223 pr_warn("map '%s': conflicting key size %u != %u.\n",
2224 map_name, map_def->key_size, sz);
2227 map_def->key_size = sz;
2228 map_def->parts |= MAP_DEF_KEY_SIZE;
2229 } else if (strcmp(name, "key") == 0) {
2232 t = btf__type_by_id(btf, m->type);
2234 pr_warn("map '%s': key type [%d] not found.\n",
2238 if (!btf_is_ptr(t)) {
2239 pr_warn("map '%s': key spec is not PTR: %s.\n",
2240 map_name, btf_kind_str(t));
2243 sz = btf__resolve_size(btf, t->type);
2245 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2246 map_name, t->type, (ssize_t)sz);
2249 if (map_def->key_size && map_def->key_size != sz) {
2250 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2251 map_name, map_def->key_size, (ssize_t)sz);
2254 map_def->key_size = sz;
2255 map_def->key_type_id = t->type;
2256 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2257 } else if (strcmp(name, "value_size") == 0) {
2260 if (!get_map_field_int(map_name, btf, m, &sz))
2262 if (map_def->value_size && map_def->value_size != sz) {
2263 pr_warn("map '%s': conflicting value size %u != %u.\n",
2264 map_name, map_def->value_size, sz);
2267 map_def->value_size = sz;
2268 map_def->parts |= MAP_DEF_VALUE_SIZE;
2269 } else if (strcmp(name, "value") == 0) {
2272 t = btf__type_by_id(btf, m->type);
2274 pr_warn("map '%s': value type [%d] not found.\n",
2278 if (!btf_is_ptr(t)) {
2279 pr_warn("map '%s': value spec is not PTR: %s.\n",
2280 map_name, btf_kind_str(t));
2283 sz = btf__resolve_size(btf, t->type);
2285 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2286 map_name, t->type, (ssize_t)sz);
2289 if (map_def->value_size && map_def->value_size != sz) {
2290 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2291 map_name, map_def->value_size, (ssize_t)sz);
2294 map_def->value_size = sz;
2295 map_def->value_type_id = t->type;
2296 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2298 else if (strcmp(name, "values") == 0) {
2299 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2300 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2301 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2302 char inner_map_name[128];
2306 pr_warn("map '%s': multi-level inner maps not supported.\n",
2310 if (i != vlen - 1) {
2311 pr_warn("map '%s': '%s' member should be last.\n",
2315 if (!is_map_in_map && !is_prog_array) {
2316 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2320 if (map_def->value_size && map_def->value_size != 4) {
2321 pr_warn("map '%s': conflicting value size %u != 4.\n",
2322 map_name, map_def->value_size);
2325 map_def->value_size = 4;
2326 t = btf__type_by_id(btf, m->type);
2328 pr_warn("map '%s': %s type [%d] not found.\n",
2329 map_name, desc, m->type);
2332 if (!btf_is_array(t) || btf_array(t)->nelems) {
2333 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2337 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2338 if (!btf_is_ptr(t)) {
2339 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2340 map_name, desc, btf_kind_str(t));
2343 t = skip_mods_and_typedefs(btf, t->type, NULL);
2344 if (is_prog_array) {
2345 if (!btf_is_func_proto(t)) {
2346 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2347 map_name, btf_kind_str(t));
2352 if (!btf_is_struct(t)) {
2353 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2354 map_name, btf_kind_str(t));
2358 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2359 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2363 map_def->parts |= MAP_DEF_INNER_MAP;
2364 } else if (strcmp(name, "pinning") == 0) {
2368 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2371 if (!get_map_field_int(map_name, btf, m, &val))
2373 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2374 pr_warn("map '%s': invalid pinning value %u.\n",
2378 map_def->pinning = val;
2379 map_def->parts |= MAP_DEF_PINNING;
2380 } else if (strcmp(name, "map_extra") == 0) {
2383 if (!get_map_field_int(map_name, btf, m, &map_extra))
2385 map_def->map_extra = map_extra;
2386 map_def->parts |= MAP_DEF_MAP_EXTRA;
2389 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2392 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2396 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2397 pr_warn("map '%s': map type isn't specified.\n", map_name);
2404 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2406 map->def.type = def->map_type;
2407 map->def.key_size = def->key_size;
2408 map->def.value_size = def->value_size;
2409 map->def.max_entries = def->max_entries;
2410 map->def.map_flags = def->map_flags;
2411 map->map_extra = def->map_extra;
2413 map->numa_node = def->numa_node;
2414 map->btf_key_type_id = def->key_type_id;
2415 map->btf_value_type_id = def->value_type_id;
2417 if (def->parts & MAP_DEF_MAP_TYPE)
2418 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2420 if (def->parts & MAP_DEF_KEY_TYPE)
2421 pr_debug("map '%s': found key [%u], sz = %u.\n",
2422 map->name, def->key_type_id, def->key_size);
2423 else if (def->parts & MAP_DEF_KEY_SIZE)
2424 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2426 if (def->parts & MAP_DEF_VALUE_TYPE)
2427 pr_debug("map '%s': found value [%u], sz = %u.\n",
2428 map->name, def->value_type_id, def->value_size);
2429 else if (def->parts & MAP_DEF_VALUE_SIZE)
2430 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2432 if (def->parts & MAP_DEF_MAX_ENTRIES)
2433 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2434 if (def->parts & MAP_DEF_MAP_FLAGS)
2435 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2436 if (def->parts & MAP_DEF_MAP_EXTRA)
2437 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2438 (unsigned long long)def->map_extra);
2439 if (def->parts & MAP_DEF_PINNING)
2440 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2441 if (def->parts & MAP_DEF_NUMA_NODE)
2442 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2444 if (def->parts & MAP_DEF_INNER_MAP)
2445 pr_debug("map '%s': found inner map definition.\n", map->name);
2448 static const char *btf_var_linkage_str(__u32 linkage)
2451 case BTF_VAR_STATIC: return "static";
2452 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2453 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2454 default: return "unknown";
2458 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2459 const struct btf_type *sec,
2460 int var_idx, int sec_idx,
2461 const Elf_Data *data, bool strict,
2462 const char *pin_root_path)
2464 struct btf_map_def map_def = {}, inner_def = {};
2465 const struct btf_type *var, *def;
2466 const struct btf_var_secinfo *vi;
2467 const struct btf_var *var_extra;
2468 const char *map_name;
2469 struct bpf_map *map;
2472 vi = btf_var_secinfos(sec) + var_idx;
2473 var = btf__type_by_id(obj->btf, vi->type);
2474 var_extra = btf_var(var);
2475 map_name = btf__name_by_offset(obj->btf, var->name_off);
2477 if (map_name == NULL || map_name[0] == '\0') {
2478 pr_warn("map #%d: empty name.\n", var_idx);
2481 if ((__u64)vi->offset + vi->size > data->d_size) {
2482 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2485 if (!btf_is_var(var)) {
2486 pr_warn("map '%s': unexpected var kind %s.\n",
2487 map_name, btf_kind_str(var));
2490 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2491 pr_warn("map '%s': unsupported map linkage %s.\n",
2492 map_name, btf_var_linkage_str(var_extra->linkage));
2496 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2497 if (!btf_is_struct(def)) {
2498 pr_warn("map '%s': unexpected def kind %s.\n",
2499 map_name, btf_kind_str(var));
2502 if (def->size > vi->size) {
2503 pr_warn("map '%s': invalid def size.\n", map_name);
2507 map = bpf_object__add_map(obj);
2509 return PTR_ERR(map);
2510 map->name = strdup(map_name);
2512 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2515 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2516 map->def.type = BPF_MAP_TYPE_UNSPEC;
2517 map->sec_idx = sec_idx;
2518 map->sec_offset = vi->offset;
2519 map->btf_var_idx = var_idx;
2520 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2521 map_name, map->sec_idx, map->sec_offset);
2523 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2527 fill_map_from_def(map, &map_def);
2529 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2530 err = build_map_pin_path(map, pin_root_path);
2532 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2537 if (map_def.parts & MAP_DEF_INNER_MAP) {
2538 map->inner_map = calloc(1, sizeof(*map->inner_map));
2539 if (!map->inner_map)
2541 map->inner_map->fd = -1;
2542 map->inner_map->sec_idx = sec_idx;
2543 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2544 if (!map->inner_map->name)
2546 sprintf(map->inner_map->name, "%s.inner", map_name);
2548 fill_map_from_def(map->inner_map, &inner_def);
2554 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2555 const char *pin_root_path)
2557 const struct btf_type *sec = NULL;
2558 int nr_types, i, vlen, err;
2559 const struct btf_type *t;
2564 if (obj->efile.btf_maps_shndx < 0)
2567 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2568 data = elf_sec_data(obj, scn);
2569 if (!scn || !data) {
2570 pr_warn("elf: failed to get %s map definitions for %s\n",
2571 MAPS_ELF_SEC, obj->path);
2575 nr_types = btf__type_cnt(obj->btf);
2576 for (i = 1; i < nr_types; i++) {
2577 t = btf__type_by_id(obj->btf, i);
2578 if (!btf_is_datasec(t))
2580 name = btf__name_by_offset(obj->btf, t->name_off);
2581 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2583 obj->efile.btf_maps_sec_btf_id = i;
2589 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2593 vlen = btf_vlen(sec);
2594 for (i = 0; i < vlen; i++) {
2595 err = bpf_object__init_user_btf_map(obj, sec, i,
2596 obj->efile.btf_maps_shndx,
2606 static int bpf_object__init_maps(struct bpf_object *obj,
2607 const struct bpf_object_open_opts *opts)
2609 const char *pin_root_path;
2613 strict = !OPTS_GET(opts, relaxed_maps, false);
2614 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2616 err = bpf_object__init_user_maps(obj, strict);
2617 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2618 err = err ?: bpf_object__init_global_data_maps(obj);
2619 err = err ?: bpf_object__init_kconfig_map(obj);
2620 err = err ?: bpf_object__init_struct_ops_maps(obj);
2625 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2629 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2633 return sh->sh_flags & SHF_EXECINSTR;
2636 static bool btf_needs_sanitization(struct bpf_object *obj)
2638 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2639 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2640 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2641 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2642 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2643 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2645 return !has_func || !has_datasec || !has_func_global || !has_float ||
2646 !has_decl_tag || !has_type_tag;
2649 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2651 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2652 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2653 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2654 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2655 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2656 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2660 for (i = 1; i < btf__type_cnt(btf); i++) {
2661 t = (struct btf_type *)btf__type_by_id(btf, i);
2663 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2664 /* replace VAR/DECL_TAG with INT */
2665 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2667 * using size = 1 is the safest choice, 4 will be too
2668 * big and cause kernel BTF validation failure if
2669 * original variable took less than 4 bytes
2672 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2673 } else if (!has_datasec && btf_is_datasec(t)) {
2674 /* replace DATASEC with STRUCT */
2675 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2676 struct btf_member *m = btf_members(t);
2677 struct btf_type *vt;
2680 name = (char *)btf__name_by_offset(btf, t->name_off);
2688 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2689 for (j = 0; j < vlen; j++, v++, m++) {
2690 /* order of field assignments is important */
2691 m->offset = v->offset * 8;
2693 /* preserve variable name as member name */
2694 vt = (void *)btf__type_by_id(btf, v->type);
2695 m->name_off = vt->name_off;
2697 } else if (!has_func && btf_is_func_proto(t)) {
2698 /* replace FUNC_PROTO with ENUM */
2700 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2701 t->size = sizeof(__u32); /* kernel enforced */
2702 } else if (!has_func && btf_is_func(t)) {
2703 /* replace FUNC with TYPEDEF */
2704 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2705 } else if (!has_func_global && btf_is_func(t)) {
2706 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2707 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2708 } else if (!has_float && btf_is_float(t)) {
2709 /* replace FLOAT with an equally-sized empty STRUCT;
2710 * since C compilers do not accept e.g. "float" as a
2711 * valid struct name, make it anonymous
2714 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2715 } else if (!has_type_tag && btf_is_type_tag(t)) {
2716 /* replace TYPE_TAG with a CONST */
2718 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2723 static bool libbpf_needs_btf(const struct bpf_object *obj)
2725 return obj->efile.btf_maps_shndx >= 0 ||
2726 obj->efile.st_ops_shndx >= 0 ||
2730 static bool kernel_needs_btf(const struct bpf_object *obj)
2732 return obj->efile.st_ops_shndx >= 0;
2735 static int bpf_object__init_btf(struct bpf_object *obj,
2737 Elf_Data *btf_ext_data)
2742 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2743 err = libbpf_get_error(obj->btf);
2746 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2749 /* enforce 8-byte pointers for BPF-targeted BTFs */
2750 btf__set_pointer_size(obj->btf, 8);
2754 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2755 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2758 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2759 err = libbpf_get_error(obj->btf_ext);
2761 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2762 BTF_EXT_ELF_SEC, err);
2763 obj->btf_ext = NULL;
2768 if (err && libbpf_needs_btf(obj)) {
2769 pr_warn("BTF is required, but is missing or corrupted.\n");
2775 static int compare_vsi_off(const void *_a, const void *_b)
2777 const struct btf_var_secinfo *a = _a;
2778 const struct btf_var_secinfo *b = _b;
2780 return a->offset - b->offset;
2783 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2786 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
2787 const char *name = btf__name_by_offset(btf, t->name_off);
2788 const struct btf_type *t_var;
2789 struct btf_var_secinfo *vsi;
2790 const struct btf_var *var;
2794 pr_debug("No name found in string section for DATASEC kind.\n");
2798 /* .extern datasec size and var offsets were set correctly during
2799 * extern collection step, so just skip straight to sorting variables
2804 ret = find_elf_sec_sz(obj, name, &size);
2805 if (ret || !size || (t->size && t->size != size)) {
2806 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2812 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2813 t_var = btf__type_by_id(btf, vsi->type);
2814 if (!t_var || !btf_is_var(t_var)) {
2815 pr_debug("Non-VAR type seen in section %s\n", name);
2819 var = btf_var(t_var);
2820 if (var->linkage == BTF_VAR_STATIC)
2823 name = btf__name_by_offset(btf, t_var->name_off);
2825 pr_debug("No name found in string section for VAR kind\n");
2829 ret = find_elf_var_offset(obj, name, &off);
2831 pr_debug("No offset found in symbol table for VAR %s\n",
2840 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2844 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2847 __u32 i, n = btf__type_cnt(btf);
2849 for (i = 1; i < n; i++) {
2850 struct btf_type *t = btf_type_by_id(btf, i);
2852 /* Loader needs to fix up some of the things compiler
2853 * couldn't get its hands on while emitting BTF. This
2854 * is section size and global variable offset. We use
2855 * the info from the ELF itself for this purpose.
2857 if (btf_is_datasec(t)) {
2858 err = btf_fixup_datasec(obj, btf, t);
2864 return libbpf_err(err);
2867 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
2869 return btf_finalize_data(obj, btf);
2872 static int bpf_object__finalize_btf(struct bpf_object *obj)
2879 err = btf_finalize_data(obj, obj->btf);
2881 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2888 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2890 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2891 prog->type == BPF_PROG_TYPE_LSM)
2894 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2895 * also need vmlinux BTF
2897 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2903 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2905 struct bpf_program *prog;
2908 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2911 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2914 /* Support for typed ksyms needs kernel BTF */
2915 for (i = 0; i < obj->nr_extern; i++) {
2916 const struct extern_desc *ext;
2918 ext = &obj->externs[i];
2919 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2923 bpf_object__for_each_program(prog, obj) {
2926 if (prog_needs_vmlinux_btf(prog))
2933 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2937 /* btf_vmlinux could be loaded earlier */
2938 if (obj->btf_vmlinux || obj->gen_loader)
2941 if (!force && !obj_needs_vmlinux_btf(obj))
2944 obj->btf_vmlinux = btf__load_vmlinux_btf();
2945 err = libbpf_get_error(obj->btf_vmlinux);
2947 pr_warn("Error loading vmlinux BTF: %d\n", err);
2948 obj->btf_vmlinux = NULL;
2954 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2956 struct btf *kern_btf = obj->btf;
2957 bool btf_mandatory, sanitize;
2963 if (!kernel_supports(obj, FEAT_BTF)) {
2964 if (kernel_needs_btf(obj)) {
2968 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2972 /* Even though some subprogs are global/weak, user might prefer more
2973 * permissive BPF verification process that BPF verifier performs for
2974 * static functions, taking into account more context from the caller
2975 * functions. In such case, they need to mark such subprogs with
2976 * __attribute__((visibility("hidden"))) and libbpf will adjust
2977 * corresponding FUNC BTF type to be marked as static and trigger more
2978 * involved BPF verification process.
2980 for (i = 0; i < obj->nr_programs; i++) {
2981 struct bpf_program *prog = &obj->programs[i];
2986 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2989 n = btf__type_cnt(obj->btf);
2990 for (j = 1; j < n; j++) {
2991 t = btf_type_by_id(obj->btf, j);
2992 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2995 name = btf__str_by_offset(obj->btf, t->name_off);
2996 if (strcmp(name, prog->name) != 0)
2999 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3004 sanitize = btf_needs_sanitization(obj);
3006 const void *raw_data;
3009 /* clone BTF to sanitize a copy and leave the original intact */
3010 raw_data = btf__raw_data(obj->btf, &sz);
3011 kern_btf = btf__new(raw_data, sz);
3012 err = libbpf_get_error(kern_btf);
3016 /* enforce 8-byte pointers for BPF-targeted BTFs */
3017 btf__set_pointer_size(obj->btf, 8);
3018 bpf_object__sanitize_btf(obj, kern_btf);
3021 if (obj->gen_loader) {
3023 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3027 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3028 /* Pretend to have valid FD to pass various fd >= 0 checks.
3029 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3031 btf__set_fd(kern_btf, 0);
3033 /* currently BPF_BTF_LOAD only supports log_level 1 */
3034 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3035 obj->log_level ? 1 : 0);
3039 /* move fd to libbpf's BTF */
3040 btf__set_fd(obj->btf, btf__fd(kern_btf));
3041 btf__set_fd(kern_btf, -1);
3043 btf__free(kern_btf);
3047 btf_mandatory = kernel_needs_btf(obj);
3048 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3049 btf_mandatory ? "BTF is mandatory, can't proceed."
3050 : "BTF is optional, ignoring.");
3057 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3061 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3063 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3064 off, obj->path, elf_errmsg(-1));
3071 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3075 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3077 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3078 off, obj->path, elf_errmsg(-1));
3085 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3089 scn = elf_getscn(obj->efile.elf, idx);
3091 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3092 idx, obj->path, elf_errmsg(-1));
3098 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3100 Elf_Scn *scn = NULL;
3101 Elf *elf = obj->efile.elf;
3102 const char *sec_name;
3104 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3105 sec_name = elf_sec_name(obj, scn);
3109 if (strcmp(sec_name, name) != 0)
3117 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3124 shdr = elf64_getshdr(scn);
3126 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3127 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3134 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3142 sh = elf_sec_hdr(obj, scn);
3146 name = elf_sec_str(obj, sh->sh_name);
3148 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3149 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3156 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3163 data = elf_getdata(scn, 0);
3165 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3166 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3167 obj->path, elf_errmsg(-1));
3174 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3176 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3179 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3182 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3184 if (idx >= data->d_size / sizeof(Elf64_Rel))
3187 return (Elf64_Rel *)data->d_buf + idx;
3190 static bool is_sec_name_dwarf(const char *name)
3192 /* approximation, but the actual list is too long */
3193 return str_has_pfx(name, ".debug_");
3196 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3198 /* no special handling of .strtab */
3199 if (hdr->sh_type == SHT_STRTAB)
3202 /* ignore .llvm_addrsig section as well */
3203 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3206 /* no subprograms will lead to an empty .text section, ignore it */
3207 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3208 strcmp(name, ".text") == 0)
3211 /* DWARF sections */
3212 if (is_sec_name_dwarf(name))
3215 if (str_has_pfx(name, ".rel")) {
3216 name += sizeof(".rel") - 1;
3217 /* DWARF section relocations */
3218 if (is_sec_name_dwarf(name))
3221 /* .BTF and .BTF.ext don't need relocations */
3222 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3223 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3230 static int cmp_progs(const void *_a, const void *_b)
3232 const struct bpf_program *a = _a;
3233 const struct bpf_program *b = _b;
3235 if (a->sec_idx != b->sec_idx)
3236 return a->sec_idx < b->sec_idx ? -1 : 1;
3238 /* sec_insn_off can't be the same within the section */
3239 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3242 static int bpf_object__elf_collect(struct bpf_object *obj)
3244 struct elf_sec_desc *sec_desc;
3245 Elf *elf = obj->efile.elf;
3246 Elf_Data *btf_ext_data = NULL;
3247 Elf_Data *btf_data = NULL;
3248 int idx = 0, err = 0;
3254 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3255 * section. e_shnum does include sec #0, so e_shnum is the necessary
3256 * size of an array to keep all the sections.
3258 obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3259 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3260 if (!obj->efile.secs)
3263 /* a bunch of ELF parsing functionality depends on processing symbols,
3264 * so do the first pass and find the symbol table
3267 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3268 sh = elf_sec_hdr(obj, scn);
3270 return -LIBBPF_ERRNO__FORMAT;
3272 if (sh->sh_type == SHT_SYMTAB) {
3273 if (obj->efile.symbols) {
3274 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3275 return -LIBBPF_ERRNO__FORMAT;
3278 data = elf_sec_data(obj, scn);
3280 return -LIBBPF_ERRNO__FORMAT;
3282 idx = elf_ndxscn(scn);
3284 obj->efile.symbols = data;
3285 obj->efile.symbols_shndx = idx;
3286 obj->efile.strtabidx = sh->sh_link;
3290 if (!obj->efile.symbols) {
3291 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3297 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3298 idx = elf_ndxscn(scn);
3299 sec_desc = &obj->efile.secs[idx];
3301 sh = elf_sec_hdr(obj, scn);
3303 return -LIBBPF_ERRNO__FORMAT;
3305 name = elf_sec_str(obj, sh->sh_name);
3307 return -LIBBPF_ERRNO__FORMAT;
3309 if (ignore_elf_section(sh, name))
3312 data = elf_sec_data(obj, scn);
3314 return -LIBBPF_ERRNO__FORMAT;
3316 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3317 idx, name, (unsigned long)data->d_size,
3318 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3321 if (strcmp(name, "license") == 0) {
3322 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3325 } else if (strcmp(name, "version") == 0) {
3326 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3329 } else if (strcmp(name, "maps") == 0) {
3330 obj->efile.maps_shndx = idx;
3331 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3332 obj->efile.btf_maps_shndx = idx;
3333 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3334 if (sh->sh_type != SHT_PROGBITS)
3335 return -LIBBPF_ERRNO__FORMAT;
3337 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3338 if (sh->sh_type != SHT_PROGBITS)
3339 return -LIBBPF_ERRNO__FORMAT;
3340 btf_ext_data = data;
3341 } else if (sh->sh_type == SHT_SYMTAB) {
3342 /* already processed during the first pass above */
3343 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3344 if (sh->sh_flags & SHF_EXECINSTR) {
3345 if (strcmp(name, ".text") == 0)
3346 obj->efile.text_shndx = idx;
3347 err = bpf_object__add_programs(obj, data, name, idx);
3350 } else if (strcmp(name, DATA_SEC) == 0 ||
3351 str_has_pfx(name, DATA_SEC ".")) {
3352 sec_desc->sec_type = SEC_DATA;
3353 sec_desc->shdr = sh;
3354 sec_desc->data = data;
3355 } else if (strcmp(name, RODATA_SEC) == 0 ||
3356 str_has_pfx(name, RODATA_SEC ".")) {
3357 sec_desc->sec_type = SEC_RODATA;
3358 sec_desc->shdr = sh;
3359 sec_desc->data = data;
3360 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3361 obj->efile.st_ops_data = data;
3362 obj->efile.st_ops_shndx = idx;
3364 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3367 } else if (sh->sh_type == SHT_REL) {
3368 int targ_sec_idx = sh->sh_info; /* points to other section */
3370 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3371 targ_sec_idx >= obj->efile.sec_cnt)
3372 return -LIBBPF_ERRNO__FORMAT;
3374 /* Only do relo for section with exec instructions */
3375 if (!section_have_execinstr(obj, targ_sec_idx) &&
3376 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3377 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3378 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3379 idx, name, targ_sec_idx,
3380 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3384 sec_desc->sec_type = SEC_RELO;
3385 sec_desc->shdr = sh;
3386 sec_desc->data = data;
3387 } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3388 sec_desc->sec_type = SEC_BSS;
3389 sec_desc->shdr = sh;
3390 sec_desc->data = data;
3392 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3393 (size_t)sh->sh_size);
3397 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3398 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3399 return -LIBBPF_ERRNO__FORMAT;
3402 /* sort BPF programs by section name and in-section instruction offset
3403 * for faster search */
3404 if (obj->nr_programs)
3405 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3407 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3410 static bool sym_is_extern(const Elf64_Sym *sym)
3412 int bind = ELF64_ST_BIND(sym->st_info);
3413 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3414 return sym->st_shndx == SHN_UNDEF &&
3415 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3416 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3419 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3421 int bind = ELF64_ST_BIND(sym->st_info);
3422 int type = ELF64_ST_TYPE(sym->st_info);
3424 /* in .text section */
3425 if (sym->st_shndx != text_shndx)
3428 /* local function */
3429 if (bind == STB_LOCAL && type == STT_SECTION)
3432 /* global function */
3433 return bind == STB_GLOBAL && type == STT_FUNC;
3436 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3438 const struct btf_type *t;
3445 n = btf__type_cnt(btf);
3446 for (i = 1; i < n; i++) {
3447 t = btf__type_by_id(btf, i);
3449 if (!btf_is_var(t) && !btf_is_func(t))
3452 tname = btf__name_by_offset(btf, t->name_off);
3453 if (strcmp(tname, ext_name))
3456 if (btf_is_var(t) &&
3457 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3460 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3469 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3470 const struct btf_var_secinfo *vs;
3471 const struct btf_type *t;
3477 n = btf__type_cnt(btf);
3478 for (i = 1; i < n; i++) {
3479 t = btf__type_by_id(btf, i);
3481 if (!btf_is_datasec(t))
3484 vs = btf_var_secinfos(t);
3485 for (j = 0; j < btf_vlen(t); j++, vs++) {
3486 if (vs->type == ext_btf_id)
3494 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3497 const struct btf_type *t;
3500 t = skip_mods_and_typedefs(btf, id, NULL);
3501 name = btf__name_by_offset(btf, t->name_off);
3505 switch (btf_kind(t)) {
3506 case BTF_KIND_INT: {
3507 int enc = btf_int_encoding(t);
3509 if (enc & BTF_INT_BOOL)
3510 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3512 *is_signed = enc & BTF_INT_SIGNED;
3515 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3516 return KCFG_UNKNOWN;
3521 return KCFG_UNKNOWN;
3522 if (strcmp(name, "libbpf_tristate"))
3523 return KCFG_UNKNOWN;
3524 return KCFG_TRISTATE;
3525 case BTF_KIND_ARRAY:
3526 if (btf_array(t)->nelems == 0)
3527 return KCFG_UNKNOWN;
3528 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3529 return KCFG_UNKNOWN;
3530 return KCFG_CHAR_ARR;
3532 return KCFG_UNKNOWN;
3536 static int cmp_externs(const void *_a, const void *_b)
3538 const struct extern_desc *a = _a;
3539 const struct extern_desc *b = _b;
3541 if (a->type != b->type)
3542 return a->type < b->type ? -1 : 1;
3544 if (a->type == EXT_KCFG) {
3545 /* descending order by alignment requirements */
3546 if (a->kcfg.align != b->kcfg.align)
3547 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3548 /* ascending order by size, within same alignment class */
3549 if (a->kcfg.sz != b->kcfg.sz)
3550 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3553 /* resolve ties by name */
3554 return strcmp(a->name, b->name);
3557 static int find_int_btf_id(const struct btf *btf)
3559 const struct btf_type *t;
3562 n = btf__type_cnt(btf);
3563 for (i = 1; i < n; i++) {
3564 t = btf__type_by_id(btf, i);
3566 if (btf_is_int(t) && btf_int_bits(t) == 32)
3573 static int add_dummy_ksym_var(struct btf *btf)
3575 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3576 const struct btf_var_secinfo *vs;
3577 const struct btf_type *sec;
3582 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3587 sec = btf__type_by_id(btf, sec_btf_id);
3588 vs = btf_var_secinfos(sec);
3589 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3590 const struct btf_type *vt;
3592 vt = btf__type_by_id(btf, vs->type);
3593 if (btf_is_func(vt))
3597 /* No func in ksyms sec. No need to add dummy var. */
3598 if (i == btf_vlen(sec))
3601 int_btf_id = find_int_btf_id(btf);
3602 dummy_var_btf_id = btf__add_var(btf,
3604 BTF_VAR_GLOBAL_ALLOCATED,
3606 if (dummy_var_btf_id < 0)
3607 pr_warn("cannot create a dummy_ksym var\n");
3609 return dummy_var_btf_id;
3612 static int bpf_object__collect_externs(struct bpf_object *obj)
3614 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3615 const struct btf_type *t;
3616 struct extern_desc *ext;
3617 int i, n, off, dummy_var_btf_id;
3618 const char *ext_name, *sec_name;
3622 if (!obj->efile.symbols)
3625 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3626 sh = elf_sec_hdr(obj, scn);
3627 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3628 return -LIBBPF_ERRNO__FORMAT;
3630 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3631 if (dummy_var_btf_id < 0)
3632 return dummy_var_btf_id;
3634 n = sh->sh_size / sh->sh_entsize;
3635 pr_debug("looking for externs among %d symbols...\n", n);
3637 for (i = 0; i < n; i++) {
3638 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3641 return -LIBBPF_ERRNO__FORMAT;
3642 if (!sym_is_extern(sym))
3644 ext_name = elf_sym_str(obj, sym->st_name);
3645 if (!ext_name || !ext_name[0])
3649 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3653 ext = &ext[obj->nr_extern];
3654 memset(ext, 0, sizeof(*ext));
3657 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3658 if (ext->btf_id <= 0) {
3659 pr_warn("failed to find BTF for extern '%s': %d\n",
3660 ext_name, ext->btf_id);
3663 t = btf__type_by_id(obj->btf, ext->btf_id);
3664 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3666 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3668 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3669 if (ext->sec_btf_id <= 0) {
3670 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3671 ext_name, ext->btf_id, ext->sec_btf_id);
3672 return ext->sec_btf_id;
3674 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3675 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3677 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3678 if (btf_is_func(t)) {
3679 pr_warn("extern function %s is unsupported under %s section\n",
3680 ext->name, KCONFIG_SEC);
3684 ext->type = EXT_KCFG;
3685 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3686 if (ext->kcfg.sz <= 0) {
3687 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3688 ext_name, ext->kcfg.sz);
3689 return ext->kcfg.sz;
3691 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3692 if (ext->kcfg.align <= 0) {
3693 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3694 ext_name, ext->kcfg.align);
3697 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3698 &ext->kcfg.is_signed);
3699 if (ext->kcfg.type == KCFG_UNKNOWN) {
3700 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3703 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3705 ext->type = EXT_KSYM;
3706 skip_mods_and_typedefs(obj->btf, t->type,
3707 &ext->ksym.type_id);
3709 pr_warn("unrecognized extern section '%s'\n", sec_name);
3713 pr_debug("collected %d externs total\n", obj->nr_extern);
3715 if (!obj->nr_extern)
3718 /* sort externs by type, for kcfg ones also by (align, size, name) */
3719 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3721 /* for .ksyms section, we need to turn all externs into allocated
3722 * variables in BTF to pass kernel verification; we do this by
3723 * pretending that each extern is a 8-byte variable
3726 /* find existing 4-byte integer type in BTF to use for fake
3727 * extern variables in DATASEC
3729 int int_btf_id = find_int_btf_id(obj->btf);
3730 /* For extern function, a dummy_var added earlier
3731 * will be used to replace the vs->type and
3732 * its name string will be used to refill
3733 * the missing param's name.
3735 const struct btf_type *dummy_var;
3737 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3738 for (i = 0; i < obj->nr_extern; i++) {
3739 ext = &obj->externs[i];
3740 if (ext->type != EXT_KSYM)
3742 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3743 i, ext->sym_idx, ext->name);
3748 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3749 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3750 struct btf_type *vt;
3752 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3753 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3754 ext = find_extern_by_name(obj, ext_name);
3756 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3757 btf_kind_str(vt), ext_name);
3760 if (btf_is_func(vt)) {
3761 const struct btf_type *func_proto;
3762 struct btf_param *param;
3765 func_proto = btf__type_by_id(obj->btf,
3767 param = btf_params(func_proto);
3768 /* Reuse the dummy_var string if the
3769 * func proto does not have param name.
3771 for (j = 0; j < btf_vlen(func_proto); j++)
3772 if (param[j].type && !param[j].name_off)
3774 dummy_var->name_off;
3775 vs->type = dummy_var_btf_id;
3776 vt->info &= ~0xffff;
3777 vt->info |= BTF_FUNC_GLOBAL;
3779 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3780 vt->type = int_btf_id;
3783 vs->size = sizeof(int);
3790 /* for kcfg externs calculate their offsets within a .kconfig map */
3792 for (i = 0; i < obj->nr_extern; i++) {
3793 ext = &obj->externs[i];
3794 if (ext->type != EXT_KCFG)
3797 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3798 off = ext->kcfg.data_off + ext->kcfg.sz;
3799 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3800 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3804 for (i = 0; i < n; i++) {
3805 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3807 t = btf__type_by_id(obj->btf, vs->type);
3808 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3809 ext = find_extern_by_name(obj, ext_name);
3811 pr_warn("failed to find extern definition for BTF var '%s'\n",
3815 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3816 vs->offset = ext->kcfg.data_off;
3822 struct bpf_program *
3823 bpf_object__find_program_by_title(const struct bpf_object *obj,
3826 struct bpf_program *pos;
3828 bpf_object__for_each_program(pos, obj) {
3829 if (pos->sec_name && !strcmp(pos->sec_name, title))
3832 return errno = ENOENT, NULL;
3835 static bool prog_is_subprog(const struct bpf_object *obj,
3836 const struct bpf_program *prog)
3838 /* For legacy reasons, libbpf supports an entry-point BPF programs
3839 * without SEC() attribute, i.e., those in the .text section. But if
3840 * there are 2 or more such programs in the .text section, they all
3841 * must be subprograms called from entry-point BPF programs in
3842 * designated SEC()'tions, otherwise there is no way to distinguish
3843 * which of those programs should be loaded vs which are a subprogram.
3844 * Similarly, if there is a function/program in .text and at least one
3845 * other BPF program with custom SEC() attribute, then we just assume
3846 * .text programs are subprograms (even if they are not called from
3847 * other programs), because libbpf never explicitly supported mixing
3848 * SEC()-designated BPF programs and .text entry-point BPF programs.
3850 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3853 struct bpf_program *
3854 bpf_object__find_program_by_name(const struct bpf_object *obj,
3857 struct bpf_program *prog;
3859 bpf_object__for_each_program(prog, obj) {
3860 if (prog_is_subprog(obj, prog))
3862 if (!strcmp(prog->name, name))
3865 return errno = ENOENT, NULL;
3868 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3871 switch (obj->efile.secs[shndx].sec_type) {
3881 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3884 return shndx == obj->efile.maps_shndx ||
3885 shndx == obj->efile.btf_maps_shndx;
3888 static enum libbpf_map_type
3889 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3891 if (shndx == obj->efile.symbols_shndx)
3892 return LIBBPF_MAP_KCONFIG;
3894 switch (obj->efile.secs[shndx].sec_type) {
3896 return LIBBPF_MAP_BSS;
3898 return LIBBPF_MAP_DATA;
3900 return LIBBPF_MAP_RODATA;
3902 return LIBBPF_MAP_UNSPEC;
3906 static int bpf_program__record_reloc(struct bpf_program *prog,
3907 struct reloc_desc *reloc_desc,
3908 __u32 insn_idx, const char *sym_name,
3909 const Elf64_Sym *sym, const Elf64_Rel *rel)
3911 struct bpf_insn *insn = &prog->insns[insn_idx];
3912 size_t map_idx, nr_maps = prog->obj->nr_maps;
3913 struct bpf_object *obj = prog->obj;
3914 __u32 shdr_idx = sym->st_shndx;
3915 enum libbpf_map_type type;
3916 const char *sym_sec_name;
3917 struct bpf_map *map;
3919 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3920 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3921 prog->name, sym_name, insn_idx, insn->code);
3922 return -LIBBPF_ERRNO__RELOC;
3925 if (sym_is_extern(sym)) {
3926 int sym_idx = ELF64_R_SYM(rel->r_info);
3927 int i, n = obj->nr_extern;
3928 struct extern_desc *ext;
3930 for (i = 0; i < n; i++) {
3931 ext = &obj->externs[i];
3932 if (ext->sym_idx == sym_idx)
3936 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3937 prog->name, sym_name, sym_idx);
3938 return -LIBBPF_ERRNO__RELOC;
3940 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3941 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3942 if (insn->code == (BPF_JMP | BPF_CALL))
3943 reloc_desc->type = RELO_EXTERN_FUNC;
3945 reloc_desc->type = RELO_EXTERN_VAR;
3946 reloc_desc->insn_idx = insn_idx;
3947 reloc_desc->sym_off = i; /* sym_off stores extern index */
3951 /* sub-program call relocation */
3952 if (is_call_insn(insn)) {
3953 if (insn->src_reg != BPF_PSEUDO_CALL) {
3954 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3955 return -LIBBPF_ERRNO__RELOC;
3957 /* text_shndx can be 0, if no default "main" program exists */
3958 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3959 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3960 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3961 prog->name, sym_name, sym_sec_name);
3962 return -LIBBPF_ERRNO__RELOC;
3964 if (sym->st_value % BPF_INSN_SZ) {
3965 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3966 prog->name, sym_name, (size_t)sym->st_value);
3967 return -LIBBPF_ERRNO__RELOC;
3969 reloc_desc->type = RELO_CALL;
3970 reloc_desc->insn_idx = insn_idx;
3971 reloc_desc->sym_off = sym->st_value;
3975 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3976 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3977 prog->name, sym_name, shdr_idx);
3978 return -LIBBPF_ERRNO__RELOC;
3981 /* loading subprog addresses */
3982 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3983 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3984 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3986 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3987 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3988 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3989 return -LIBBPF_ERRNO__RELOC;
3992 reloc_desc->type = RELO_SUBPROG_ADDR;
3993 reloc_desc->insn_idx = insn_idx;
3994 reloc_desc->sym_off = sym->st_value;
3998 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3999 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4001 /* generic map reference relocation */
4002 if (type == LIBBPF_MAP_UNSPEC) {
4003 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4004 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4005 prog->name, sym_name, sym_sec_name);
4006 return -LIBBPF_ERRNO__RELOC;
4008 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4009 map = &obj->maps[map_idx];
4010 if (map->libbpf_type != type ||
4011 map->sec_idx != sym->st_shndx ||
4012 map->sec_offset != sym->st_value)
4014 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4015 prog->name, map_idx, map->name, map->sec_idx,
4016 map->sec_offset, insn_idx);
4019 if (map_idx >= nr_maps) {
4020 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4021 prog->name, sym_sec_name, (size_t)sym->st_value);
4022 return -LIBBPF_ERRNO__RELOC;
4024 reloc_desc->type = RELO_LD64;
4025 reloc_desc->insn_idx = insn_idx;
4026 reloc_desc->map_idx = map_idx;
4027 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4031 /* global data map relocation */
4032 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4033 pr_warn("prog '%s': bad data relo against section '%s'\n",
4034 prog->name, sym_sec_name);
4035 return -LIBBPF_ERRNO__RELOC;
4037 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4038 map = &obj->maps[map_idx];
4039 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4041 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4042 prog->name, map_idx, map->name, map->sec_idx,
4043 map->sec_offset, insn_idx);
4046 if (map_idx >= nr_maps) {
4047 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4048 prog->name, sym_sec_name);
4049 return -LIBBPF_ERRNO__RELOC;
4052 reloc_desc->type = RELO_DATA;
4053 reloc_desc->insn_idx = insn_idx;
4054 reloc_desc->map_idx = map_idx;
4055 reloc_desc->sym_off = sym->st_value;
4059 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4061 return insn_idx >= prog->sec_insn_off &&
4062 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4065 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4066 size_t sec_idx, size_t insn_idx)
4068 int l = 0, r = obj->nr_programs - 1, m;
4069 struct bpf_program *prog;
4072 m = l + (r - l + 1) / 2;
4073 prog = &obj->programs[m];
4075 if (prog->sec_idx < sec_idx ||
4076 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4081 /* matching program could be at index l, but it still might be the
4082 * wrong one, so we need to double check conditions for the last time
4084 prog = &obj->programs[l];
4085 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4091 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4093 const char *relo_sec_name, *sec_name;
4094 size_t sec_idx = shdr->sh_info, sym_idx;
4095 struct bpf_program *prog;
4096 struct reloc_desc *relos;
4098 const char *sym_name;
4105 if (sec_idx >= obj->efile.sec_cnt)
4108 scn = elf_sec_by_idx(obj, sec_idx);
4109 scn_data = elf_sec_data(obj, scn);
4111 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4112 sec_name = elf_sec_name(obj, scn);
4113 if (!relo_sec_name || !sec_name)
4116 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4117 relo_sec_name, sec_idx, sec_name);
4118 nrels = shdr->sh_size / shdr->sh_entsize;
4120 for (i = 0; i < nrels; i++) {
4121 rel = elf_rel_by_idx(data, i);
4123 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4124 return -LIBBPF_ERRNO__FORMAT;
4127 sym_idx = ELF64_R_SYM(rel->r_info);
4128 sym = elf_sym_by_idx(obj, sym_idx);
4130 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4131 relo_sec_name, sym_idx, i);
4132 return -LIBBPF_ERRNO__FORMAT;
4135 if (sym->st_shndx >= obj->efile.sec_cnt) {
4136 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4137 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4138 return -LIBBPF_ERRNO__FORMAT;
4141 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4142 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4143 relo_sec_name, (size_t)rel->r_offset, i);
4144 return -LIBBPF_ERRNO__FORMAT;
4147 insn_idx = rel->r_offset / BPF_INSN_SZ;
4148 /* relocations against static functions are recorded as
4149 * relocations against the section that contains a function;
4150 * in such case, symbol will be STT_SECTION and sym.st_name
4151 * will point to empty string (0), so fetch section name
4154 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4155 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4157 sym_name = elf_sym_str(obj, sym->st_name);
4158 sym_name = sym_name ?: "<?";
4160 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4161 relo_sec_name, i, insn_idx, sym_name);
4163 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4165 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4166 relo_sec_name, i, sec_name, insn_idx);
4170 relos = libbpf_reallocarray(prog->reloc_desc,
4171 prog->nr_reloc + 1, sizeof(*relos));
4174 prog->reloc_desc = relos;
4176 /* adjust insn_idx to local BPF program frame of reference */
4177 insn_idx -= prog->sec_insn_off;
4178 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4179 insn_idx, sym_name, sym, rel);
4188 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4190 struct bpf_map_def *def = &map->def;
4191 __u32 key_type_id = 0, value_type_id = 0;
4194 /* if it's BTF-defined map, we don't need to search for type IDs.
4195 * For struct_ops map, it does not need btf_key_type_id and
4196 * btf_value_type_id.
4198 if (map->sec_idx == obj->efile.btf_maps_shndx ||
4199 bpf_map__is_struct_ops(map))
4202 if (!bpf_map__is_internal(map)) {
4203 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
4204 def->value_size, &key_type_id,
4208 * LLVM annotates global data differently in BTF, that is,
4209 * only as '.data', '.bss' or '.rodata'.
4211 ret = btf__find_by_name(obj->btf, map->real_name);
4216 map->btf_key_type_id = key_type_id;
4217 map->btf_value_type_id = bpf_map__is_internal(map) ?
4218 ret : value_type_id;
4222 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4224 char file[PATH_MAX], buff[4096];
4229 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4230 memset(info, 0, sizeof(*info));
4232 fp = fopen(file, "r");
4235 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4240 while (fgets(buff, sizeof(buff), fp)) {
4241 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4243 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4244 info->key_size = val;
4245 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4246 info->value_size = val;
4247 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4248 info->max_entries = val;
4249 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4250 info->map_flags = val;
4258 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4260 struct bpf_map_info info = {};
4261 __u32 len = sizeof(info);
4265 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4266 if (err && errno == EINVAL)
4267 err = bpf_get_map_info_from_fdinfo(fd, &info);
4269 return libbpf_err(err);
4271 new_name = strdup(info.name);
4273 return libbpf_err(-errno);
4275 new_fd = open("/", O_RDONLY | O_CLOEXEC);
4278 goto err_free_new_name;
4281 new_fd = dup3(fd, new_fd, O_CLOEXEC);
4284 goto err_close_new_fd;
4287 err = zclose(map->fd);
4290 goto err_close_new_fd;
4295 map->name = new_name;
4296 map->def.type = info.type;
4297 map->def.key_size = info.key_size;
4298 map->def.value_size = info.value_size;
4299 map->def.max_entries = info.max_entries;
4300 map->def.map_flags = info.map_flags;
4301 map->btf_key_type_id = info.btf_key_type_id;
4302 map->btf_value_type_id = info.btf_value_type_id;
4304 map->map_extra = info.map_extra;
4312 return libbpf_err(err);
4315 __u32 bpf_map__max_entries(const struct bpf_map *map)
4317 return map->def.max_entries;
4320 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4322 if (!bpf_map_type__is_map_in_map(map->def.type))
4323 return errno = EINVAL, NULL;
4325 return map->inner_map;
4328 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4331 return libbpf_err(-EBUSY);
4332 map->def.max_entries = max_entries;
4336 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4338 if (!map || !max_entries)
4339 return libbpf_err(-EINVAL);
4341 return bpf_map__set_max_entries(map, max_entries);
4345 bpf_object__probe_loading(struct bpf_object *obj)
4347 char *cp, errmsg[STRERR_BUFSIZE];
4348 struct bpf_insn insns[] = {
4349 BPF_MOV64_IMM(BPF_REG_0, 0),
4352 int ret, insn_cnt = ARRAY_SIZE(insns);
4354 if (obj->gen_loader)
4357 /* make sure basic loading works */
4358 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4360 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4363 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4364 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4365 "program. Make sure your kernel supports BPF "
4366 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4367 "set to big enough value.\n", __func__, cp, ret);
4375 static int probe_fd(int fd)
4382 static int probe_kern_prog_name(void)
4384 struct bpf_insn insns[] = {
4385 BPF_MOV64_IMM(BPF_REG_0, 0),
4388 int ret, insn_cnt = ARRAY_SIZE(insns);
4390 /* make sure loading with name works */
4391 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
4392 return probe_fd(ret);
4395 static int probe_kern_global_data(void)
4397 char *cp, errmsg[STRERR_BUFSIZE];
4398 struct bpf_insn insns[] = {
4399 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4400 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4401 BPF_MOV64_IMM(BPF_REG_0, 0),
4404 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4406 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4409 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4410 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4411 __func__, cp, -ret);
4417 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4419 return probe_fd(ret);
4422 static int probe_kern_btf(void)
4424 static const char strs[] = "\0int";
4427 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4430 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4431 strs, sizeof(strs)));
4434 static int probe_kern_btf_func(void)
4436 static const char strs[] = "\0int\0x\0a";
4437 /* void x(int a) {} */
4440 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4441 /* FUNC_PROTO */ /* [2] */
4442 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4443 BTF_PARAM_ENC(7, 1),
4444 /* FUNC x */ /* [3] */
4445 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4448 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4449 strs, sizeof(strs)));
4452 static int probe_kern_btf_func_global(void)
4454 static const char strs[] = "\0int\0x\0a";
4455 /* static void x(int a) {} */
4458 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4459 /* FUNC_PROTO */ /* [2] */
4460 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4461 BTF_PARAM_ENC(7, 1),
4462 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4463 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4466 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4467 strs, sizeof(strs)));
4470 static int probe_kern_btf_datasec(void)
4472 static const char strs[] = "\0x\0.data";
4476 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4477 /* VAR x */ /* [2] */
4478 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4480 /* DATASEC val */ /* [3] */
4481 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4482 BTF_VAR_SECINFO_ENC(2, 0, 4),
4485 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4486 strs, sizeof(strs)));
4489 static int probe_kern_btf_float(void)
4491 static const char strs[] = "\0float";
4494 BTF_TYPE_FLOAT_ENC(1, 4),
4497 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4498 strs, sizeof(strs)));
4501 static int probe_kern_btf_decl_tag(void)
4503 static const char strs[] = "\0tag";
4506 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4507 /* VAR x */ /* [2] */
4508 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4511 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4514 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4515 strs, sizeof(strs)));
4518 static int probe_kern_btf_type_tag(void)
4520 static const char strs[] = "\0tag";
4523 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4525 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4527 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4530 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4531 strs, sizeof(strs)));
4534 static int probe_kern_array_mmap(void)
4536 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4539 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4540 return probe_fd(fd);
4543 static int probe_kern_exp_attach_type(void)
4545 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4546 struct bpf_insn insns[] = {
4547 BPF_MOV64_IMM(BPF_REG_0, 0),
4550 int fd, insn_cnt = ARRAY_SIZE(insns);
4552 /* use any valid combination of program type and (optional)
4553 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4554 * to see if kernel supports expected_attach_type field for
4555 * BPF_PROG_LOAD command
4557 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4558 return probe_fd(fd);
4561 static int probe_kern_probe_read_kernel(void)
4563 struct bpf_insn insns[] = {
4564 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4565 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4566 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4567 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4568 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4571 int fd, insn_cnt = ARRAY_SIZE(insns);
4573 fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4574 return probe_fd(fd);
4577 static int probe_prog_bind_map(void)
4579 char *cp, errmsg[STRERR_BUFSIZE];
4580 struct bpf_insn insns[] = {
4581 BPF_MOV64_IMM(BPF_REG_0, 0),
4584 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4586 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4589 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4590 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4591 __func__, cp, -ret);
4595 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4601 ret = bpf_prog_bind_map(prog, map, NULL);
4609 static int probe_module_btf(void)
4611 static const char strs[] = "\0int";
4614 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4616 struct bpf_btf_info info;
4617 __u32 len = sizeof(info);
4621 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4623 return 0; /* BTF not supported at all */
4625 memset(&info, 0, sizeof(info));
4626 info.name = ptr_to_u64(name);
4627 info.name_len = sizeof(name);
4629 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4630 * kernel's module BTF support coincides with support for
4631 * name/name_len fields in struct bpf_btf_info.
4633 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4638 static int probe_perf_link(void)
4640 struct bpf_insn insns[] = {
4641 BPF_MOV64_IMM(BPF_REG_0, 0),
4644 int prog_fd, link_fd, err;
4646 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4647 insns, ARRAY_SIZE(insns), NULL);
4651 /* use invalid perf_event FD to get EBADF, if link is supported;
4652 * otherwise EINVAL should be returned
4654 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4655 err = -errno; /* close() can clobber errno */
4661 return link_fd < 0 && err == -EBADF;
4664 enum kern_feature_result {
4670 typedef int (*feature_probe_fn)(void);
4672 static struct kern_feature_desc {
4674 feature_probe_fn probe;
4675 enum kern_feature_result res;
4676 } feature_probes[__FEAT_CNT] = {
4677 [FEAT_PROG_NAME] = {
4678 "BPF program name", probe_kern_prog_name,
4680 [FEAT_GLOBAL_DATA] = {
4681 "global variables", probe_kern_global_data,
4684 "minimal BTF", probe_kern_btf,
4687 "BTF functions", probe_kern_btf_func,
4689 [FEAT_BTF_GLOBAL_FUNC] = {
4690 "BTF global function", probe_kern_btf_func_global,
4692 [FEAT_BTF_DATASEC] = {
4693 "BTF data section and variable", probe_kern_btf_datasec,
4695 [FEAT_ARRAY_MMAP] = {
4696 "ARRAY map mmap()", probe_kern_array_mmap,
4698 [FEAT_EXP_ATTACH_TYPE] = {
4699 "BPF_PROG_LOAD expected_attach_type attribute",
4700 probe_kern_exp_attach_type,
4702 [FEAT_PROBE_READ_KERN] = {
4703 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4705 [FEAT_PROG_BIND_MAP] = {
4706 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4708 [FEAT_MODULE_BTF] = {
4709 "module BTF support", probe_module_btf,
4711 [FEAT_BTF_FLOAT] = {
4712 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4714 [FEAT_PERF_LINK] = {
4715 "BPF perf link support", probe_perf_link,
4717 [FEAT_BTF_DECL_TAG] = {
4718 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4720 [FEAT_BTF_TYPE_TAG] = {
4721 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4725 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4727 struct kern_feature_desc *feat = &feature_probes[feat_id];
4730 if (obj->gen_loader)
4731 /* To generate loader program assume the latest kernel
4732 * to avoid doing extra prog_load, map_create syscalls.
4736 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4737 ret = feat->probe();
4739 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4740 } else if (ret == 0) {
4741 WRITE_ONCE(feat->res, FEAT_MISSING);
4743 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4744 WRITE_ONCE(feat->res, FEAT_MISSING);
4748 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4751 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4753 struct bpf_map_info map_info = {};
4754 char msg[STRERR_BUFSIZE];
4758 map_info_len = sizeof(map_info);
4760 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4761 if (err && errno == EINVAL)
4762 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4764 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4765 libbpf_strerror_r(errno, msg, sizeof(msg)));
4769 return (map_info.type == map->def.type &&
4770 map_info.key_size == map->def.key_size &&
4771 map_info.value_size == map->def.value_size &&
4772 map_info.max_entries == map->def.max_entries &&
4773 map_info.map_flags == map->def.map_flags &&
4774 map_info.map_extra == map->map_extra);
4778 bpf_object__reuse_map(struct bpf_map *map)
4780 char *cp, errmsg[STRERR_BUFSIZE];
4783 pin_fd = bpf_obj_get(map->pin_path);
4786 if (err == -ENOENT) {
4787 pr_debug("found no pinned map to reuse at '%s'\n",
4792 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4793 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4798 if (!map_is_reuse_compat(map, pin_fd)) {
4799 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4805 err = bpf_map__reuse_fd(map, pin_fd);
4811 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4817 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4819 enum libbpf_map_type map_type = map->libbpf_type;
4820 char *cp, errmsg[STRERR_BUFSIZE];
4823 if (obj->gen_loader) {
4824 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4825 map->mmaped, map->def.value_size);
4826 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4827 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4830 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4833 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4834 pr_warn("Error setting initial map(%s) contents: %s\n",
4839 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4840 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4841 err = bpf_map_freeze(map->fd);
4844 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4845 pr_warn("Error freezing map(%s) as read-only: %s\n",
4853 static void bpf_map__destroy(struct bpf_map *map);
4855 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4857 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4858 struct bpf_map_def *def = &map->def;
4859 const char *map_name = NULL;
4863 if (kernel_supports(obj, FEAT_PROG_NAME))
4864 map_name = map->name;
4865 create_attr.map_ifindex = map->map_ifindex;
4866 create_attr.map_flags = def->map_flags;
4867 create_attr.numa_node = map->numa_node;
4868 create_attr.map_extra = map->map_extra;
4870 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4873 nr_cpus = libbpf_num_possible_cpus();
4875 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4876 map->name, nr_cpus);
4879 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4880 max_entries = nr_cpus;
4882 max_entries = def->max_entries;
4885 if (bpf_map__is_struct_ops(map))
4886 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4888 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4889 create_attr.btf_fd = btf__fd(obj->btf);
4890 create_attr.btf_key_type_id = map->btf_key_type_id;
4891 create_attr.btf_value_type_id = map->btf_value_type_id;
4894 if (bpf_map_type__is_map_in_map(def->type)) {
4895 if (map->inner_map) {
4896 err = bpf_object__create_map(obj, map->inner_map, true);
4898 pr_warn("map '%s': failed to create inner map: %d\n",
4902 map->inner_map_fd = bpf_map__fd(map->inner_map);
4904 if (map->inner_map_fd >= 0)
4905 create_attr.inner_map_fd = map->inner_map_fd;
4908 switch (def->type) {
4909 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4910 case BPF_MAP_TYPE_CGROUP_ARRAY:
4911 case BPF_MAP_TYPE_STACK_TRACE:
4912 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4913 case BPF_MAP_TYPE_HASH_OF_MAPS:
4914 case BPF_MAP_TYPE_DEVMAP:
4915 case BPF_MAP_TYPE_DEVMAP_HASH:
4916 case BPF_MAP_TYPE_CPUMAP:
4917 case BPF_MAP_TYPE_XSKMAP:
4918 case BPF_MAP_TYPE_SOCKMAP:
4919 case BPF_MAP_TYPE_SOCKHASH:
4920 case BPF_MAP_TYPE_QUEUE:
4921 case BPF_MAP_TYPE_STACK:
4922 case BPF_MAP_TYPE_RINGBUF:
4923 create_attr.btf_fd = 0;
4924 create_attr.btf_key_type_id = 0;
4925 create_attr.btf_value_type_id = 0;
4926 map->btf_key_type_id = 0;
4927 map->btf_value_type_id = 0;
4932 if (obj->gen_loader) {
4933 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
4934 def->key_size, def->value_size, max_entries,
4935 &create_attr, is_inner ? -1 : map - obj->maps);
4936 /* Pretend to have valid FD to pass various fd >= 0 checks.
4937 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4941 map->fd = bpf_map_create(def->type, map_name,
4942 def->key_size, def->value_size,
4943 max_entries, &create_attr);
4945 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4946 create_attr.btf_value_type_id)) {
4947 char *cp, errmsg[STRERR_BUFSIZE];
4950 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4951 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4952 map->name, cp, err);
4953 create_attr.btf_fd = 0;
4954 create_attr.btf_key_type_id = 0;
4955 create_attr.btf_value_type_id = 0;
4956 map->btf_key_type_id = 0;
4957 map->btf_value_type_id = 0;
4958 map->fd = bpf_map_create(def->type, map_name,
4959 def->key_size, def->value_size,
4960 max_entries, &create_attr);
4963 err = map->fd < 0 ? -errno : 0;
4965 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4966 if (obj->gen_loader)
4967 map->inner_map->fd = -1;
4968 bpf_map__destroy(map->inner_map);
4969 zfree(&map->inner_map);
4975 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
4977 const struct bpf_map *targ_map;
4981 for (i = 0; i < map->init_slots_sz; i++) {
4982 if (!map->init_slots[i])
4985 targ_map = map->init_slots[i];
4986 fd = bpf_map__fd(targ_map);
4988 if (obj->gen_loader) {
4989 bpf_gen__populate_outer_map(obj->gen_loader,
4991 targ_map - obj->maps);
4993 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4997 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4998 map->name, i, targ_map->name, fd, err);
5001 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5002 map->name, i, targ_map->name, fd);
5005 zfree(&map->init_slots);
5006 map->init_slots_sz = 0;
5011 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5013 const struct bpf_program *targ_prog;
5017 if (obj->gen_loader)
5020 for (i = 0; i < map->init_slots_sz; i++) {
5021 if (!map->init_slots[i])
5024 targ_prog = map->init_slots[i];
5025 fd = bpf_program__fd(targ_prog);
5027 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5030 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5031 map->name, i, targ_prog->name, fd, err);
5034 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5035 map->name, i, targ_prog->name, fd);
5038 zfree(&map->init_slots);
5039 map->init_slots_sz = 0;
5044 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5046 struct bpf_map *map;
5049 for (i = 0; i < obj->nr_maps; i++) {
5050 map = &obj->maps[i];
5052 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5055 err = init_prog_array_slots(obj, map);
5065 bpf_object__create_maps(struct bpf_object *obj)
5067 struct bpf_map *map;
5068 char *cp, errmsg[STRERR_BUFSIZE];
5073 for (i = 0; i < obj->nr_maps; i++) {
5074 map = &obj->maps[i];
5076 /* To support old kernels, we skip creating global data maps
5077 * (.rodata, .data, .kconfig, etc); later on, during program
5078 * loading, if we detect that at least one of the to-be-loaded
5079 * programs is referencing any global data map, we'll error
5080 * out with program name and relocation index logged.
5081 * This approach allows to accommodate Clang emitting
5082 * unnecessary .rodata.str1.1 sections for string literals,
5083 * but also it allows to have CO-RE applications that use
5084 * global variables in some of BPF programs, but not others.
5085 * If those global variable-using programs are not loaded at
5086 * runtime due to bpf_program__set_autoload(prog, false),
5087 * bpf_object loading will succeed just fine even on old
5090 if (bpf_map__is_internal(map) &&
5091 !kernel_supports(obj, FEAT_GLOBAL_DATA)) {
5092 map->skipped = true;
5098 if (map->pin_path) {
5099 err = bpf_object__reuse_map(map);
5101 pr_warn("map '%s': error reusing pinned map\n",
5105 if (retried && map->fd < 0) {
5106 pr_warn("map '%s': cannot find pinned map\n",
5114 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5115 map->name, map->fd);
5117 err = bpf_object__create_map(obj, map, false);
5121 pr_debug("map '%s': created successfully, fd=%d\n",
5122 map->name, map->fd);
5124 if (bpf_map__is_internal(map)) {
5125 err = bpf_object__populate_internal_map(obj, map);
5132 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5133 err = init_map_in_map_slots(obj, map);
5141 if (map->pin_path && !map->pinned) {
5142 err = bpf_map__pin(map, NULL);
5145 if (!retried && err == -EEXIST) {
5149 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5150 map->name, map->pin_path, err);
5159 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5160 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5162 for (j = 0; j < i; j++)
5163 zclose(obj->maps[j].fd);
5167 static bool bpf_core_is_flavor_sep(const char *s)
5169 /* check X___Y name pattern, where X and Y are not underscores */
5170 return s[0] != '_' && /* X */
5171 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5172 s[4] != '_'; /* Y */
5175 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5176 * before last triple underscore. Struct name part after last triple
5177 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5179 size_t bpf_core_essential_name_len(const char *name)
5181 size_t n = strlen(name);
5184 for (i = n - 5; i >= 0; i--) {
5185 if (bpf_core_is_flavor_sep(name + i))
5191 static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5197 static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5198 size_t local_essent_len,
5199 const struct btf *targ_btf,
5200 const char *targ_btf_name,
5202 struct bpf_core_cand_list *cands)
5204 struct bpf_core_cand *new_cands, *cand;
5205 const struct btf_type *t, *local_t;
5206 const char *targ_name, *local_name;
5207 size_t targ_essent_len;
5210 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5211 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5213 n = btf__type_cnt(targ_btf);
5214 for (i = targ_start_id; i < n; i++) {
5215 t = btf__type_by_id(targ_btf, i);
5216 if (btf_kind(t) != btf_kind(local_t))
5219 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5220 if (str_is_empty(targ_name))
5223 targ_essent_len = bpf_core_essential_name_len(targ_name);
5224 if (targ_essent_len != local_essent_len)
5227 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5230 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5231 local_cand->id, btf_kind_str(local_t),
5232 local_name, i, btf_kind_str(t), targ_name,
5234 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5235 sizeof(*cands->cands));
5239 cand = &new_cands[cands->len];
5240 cand->btf = targ_btf;
5243 cands->cands = new_cands;
5249 static int load_module_btfs(struct bpf_object *obj)
5251 struct bpf_btf_info info;
5252 struct module_btf *mod_btf;
5258 if (obj->btf_modules_loaded)
5261 if (obj->gen_loader)
5264 /* don't do this again, even if we find no module BTFs */
5265 obj->btf_modules_loaded = true;
5267 /* kernel too old to support module BTFs */
5268 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5272 err = bpf_btf_get_next_id(id, &id);
5273 if (err && errno == ENOENT)
5277 pr_warn("failed to iterate BTF objects: %d\n", err);
5281 fd = bpf_btf_get_fd_by_id(id);
5283 if (errno == ENOENT)
5284 continue; /* expected race: BTF was unloaded */
5286 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5291 memset(&info, 0, sizeof(info));
5292 info.name = ptr_to_u64(name);
5293 info.name_len = sizeof(name);
5295 err = bpf_obj_get_info_by_fd(fd, &info, &len);
5298 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5302 /* ignore non-module BTFs */
5303 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5308 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5309 err = libbpf_get_error(btf);
5311 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5316 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5317 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5321 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5326 mod_btf->name = strdup(name);
5327 if (!mod_btf->name) {
5341 static struct bpf_core_cand_list *
5342 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5344 struct bpf_core_cand local_cand = {};
5345 struct bpf_core_cand_list *cands;
5346 const struct btf *main_btf;
5347 const struct btf_type *local_t;
5348 const char *local_name;
5349 size_t local_essent_len;
5352 local_cand.btf = local_btf;
5353 local_cand.id = local_type_id;
5354 local_t = btf__type_by_id(local_btf, local_type_id);
5356 return ERR_PTR(-EINVAL);
5358 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5359 if (str_is_empty(local_name))
5360 return ERR_PTR(-EINVAL);
5361 local_essent_len = bpf_core_essential_name_len(local_name);
5363 cands = calloc(1, sizeof(*cands));
5365 return ERR_PTR(-ENOMEM);
5367 /* Attempt to find target candidates in vmlinux BTF first */
5368 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5369 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5373 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5377 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5378 if (obj->btf_vmlinux_override)
5381 /* now look through module BTFs, trying to still find candidates */
5382 err = load_module_btfs(obj);
5386 for (i = 0; i < obj->btf_module_cnt; i++) {
5387 err = bpf_core_add_cands(&local_cand, local_essent_len,
5388 obj->btf_modules[i].btf,
5389 obj->btf_modules[i].name,
5390 btf__type_cnt(obj->btf_vmlinux),
5398 bpf_core_free_cands(cands);
5399 return ERR_PTR(err);
5402 /* Check local and target types for compatibility. This check is used for
5403 * type-based CO-RE relocations and follow slightly different rules than
5404 * field-based relocations. This function assumes that root types were already
5405 * checked for name match. Beyond that initial root-level name check, names
5406 * are completely ignored. Compatibility rules are as follows:
5407 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5408 * kind should match for local and target types (i.e., STRUCT is not
5409 * compatible with UNION);
5410 * - for ENUMs, the size is ignored;
5411 * - for INT, size and signedness are ignored;
5412 * - for ARRAY, dimensionality is ignored, element types are checked for
5413 * compatibility recursively;
5414 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5415 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5416 * - FUNC_PROTOs are compatible if they have compatible signature: same
5417 * number of input args and compatible return and argument types.
5418 * These rules are not set in stone and probably will be adjusted as we get
5419 * more experience with using BPF CO-RE relocations.
5421 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5422 const struct btf *targ_btf, __u32 targ_id)
5424 const struct btf_type *local_type, *targ_type;
5425 int depth = 32; /* max recursion depth */
5427 /* caller made sure that names match (ignoring flavor suffix) */
5428 local_type = btf__type_by_id(local_btf, local_id);
5429 targ_type = btf__type_by_id(targ_btf, targ_id);
5430 if (btf_kind(local_type) != btf_kind(targ_type))
5438 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5439 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5440 if (!local_type || !targ_type)
5443 if (btf_kind(local_type) != btf_kind(targ_type))
5446 switch (btf_kind(local_type)) {
5448 case BTF_KIND_STRUCT:
5449 case BTF_KIND_UNION:
5454 /* just reject deprecated bitfield-like integers; all other
5455 * integers are by default compatible between each other
5457 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5459 local_id = local_type->type;
5460 targ_id = targ_type->type;
5462 case BTF_KIND_ARRAY:
5463 local_id = btf_array(local_type)->type;
5464 targ_id = btf_array(targ_type)->type;
5466 case BTF_KIND_FUNC_PROTO: {
5467 struct btf_param *local_p = btf_params(local_type);
5468 struct btf_param *targ_p = btf_params(targ_type);
5469 __u16 local_vlen = btf_vlen(local_type);
5470 __u16 targ_vlen = btf_vlen(targ_type);
5473 if (local_vlen != targ_vlen)
5476 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5477 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5478 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5479 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5484 /* tail recurse for return type check */
5485 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5486 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5490 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5491 btf_kind_str(local_type), local_id, targ_id);
5496 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5501 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5506 static void *u32_as_hash_key(__u32 x)
5508 return (void *)(uintptr_t)x;
5511 static int record_relo_core(struct bpf_program *prog,
5512 const struct bpf_core_relo *core_relo, int insn_idx)
5514 struct reloc_desc *relos, *relo;
5516 relos = libbpf_reallocarray(prog->reloc_desc,
5517 prog->nr_reloc + 1, sizeof(*relos));
5520 relo = &relos[prog->nr_reloc];
5521 relo->type = RELO_CORE;
5522 relo->insn_idx = insn_idx;
5523 relo->core_relo = core_relo;
5524 prog->reloc_desc = relos;
5529 static int bpf_core_apply_relo(struct bpf_program *prog,
5530 const struct bpf_core_relo *relo,
5532 const struct btf *local_btf,
5533 struct hashmap *cand_cache)
5535 struct bpf_core_spec specs_scratch[3] = {};
5536 const void *type_key = u32_as_hash_key(relo->type_id);
5537 struct bpf_core_cand_list *cands = NULL;
5538 const char *prog_name = prog->name;
5539 const struct btf_type *local_type;
5540 const char *local_name;
5541 __u32 local_id = relo->type_id;
5542 struct bpf_insn *insn;
5545 if (relo->insn_off % BPF_INSN_SZ)
5547 insn_idx = relo->insn_off / BPF_INSN_SZ;
5548 /* adjust insn_idx from section frame of reference to the local
5549 * program's frame of reference; (sub-)program code is not yet
5550 * relocated, so it's enough to just subtract in-section offset
5552 insn_idx = insn_idx - prog->sec_insn_off;
5553 if (insn_idx >= prog->insns_cnt)
5555 insn = &prog->insns[insn_idx];
5557 local_type = btf__type_by_id(local_btf, local_id);
5561 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5565 if (prog->obj->gen_loader) {
5566 const char *spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
5568 pr_debug("record_relo_core: prog %td insn[%d] %s %s %s final insn_idx %d\n",
5569 prog - prog->obj->programs, relo->insn_off / 8,
5570 btf_kind_str(local_type), local_name, spec_str, insn_idx);
5571 return record_relo_core(prog, relo, insn_idx);
5574 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5575 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5576 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5577 if (IS_ERR(cands)) {
5578 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5579 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5580 local_name, PTR_ERR(cands));
5581 return PTR_ERR(cands);
5583 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5585 bpf_core_free_cands(cands);
5590 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo,
5591 relo_idx, local_btf, cands, specs_scratch);
5595 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5597 const struct btf_ext_info_sec *sec;
5598 const struct bpf_core_relo *rec;
5599 const struct btf_ext_info *seg;
5600 struct hashmap_entry *entry;
5601 struct hashmap *cand_cache = NULL;
5602 struct bpf_program *prog;
5603 const char *sec_name;
5604 int i, err = 0, insn_idx, sec_idx;
5606 if (obj->btf_ext->core_relo_info.len == 0)
5609 if (targ_btf_path) {
5610 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5611 err = libbpf_get_error(obj->btf_vmlinux_override);
5613 pr_warn("failed to parse target BTF: %d\n", err);
5618 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5619 if (IS_ERR(cand_cache)) {
5620 err = PTR_ERR(cand_cache);
5624 seg = &obj->btf_ext->core_relo_info;
5625 for_each_btf_ext_sec(seg, sec) {
5626 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5627 if (str_is_empty(sec_name)) {
5631 /* bpf_object's ELF is gone by now so it's not easy to find
5632 * section index by section name, but we can find *any*
5633 * bpf_program within desired section name and use it's
5634 * prog->sec_idx to do a proper search by section index and
5635 * instruction offset
5638 for (i = 0; i < obj->nr_programs; i++) {
5639 prog = &obj->programs[i];
5640 if (strcmp(prog->sec_name, sec_name) == 0)
5644 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5647 sec_idx = prog->sec_idx;
5649 pr_debug("sec '%s': found %d CO-RE relocations\n",
5650 sec_name, sec->num_info);
5652 for_each_btf_ext_rec(seg, sec, i, rec) {
5653 insn_idx = rec->insn_off / BPF_INSN_SZ;
5654 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5656 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5657 sec_name, insn_idx, i);
5661 /* no need to apply CO-RE relocation if the program is
5662 * not going to be loaded
5667 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
5669 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5670 prog->name, i, err);
5677 /* obj->btf_vmlinux and module BTFs are freed after object load */
5678 btf__free(obj->btf_vmlinux_override);
5679 obj->btf_vmlinux_override = NULL;
5681 if (!IS_ERR_OR_NULL(cand_cache)) {
5682 hashmap__for_each_entry(cand_cache, entry, i) {
5683 bpf_core_free_cands(entry->value);
5685 hashmap__free(cand_cache);
5690 /* Relocate data references within program code:
5692 * - global variable references;
5693 * - extern references.
5696 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5700 for (i = 0; i < prog->nr_reloc; i++) {
5701 struct reloc_desc *relo = &prog->reloc_desc[i];
5702 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5703 struct extern_desc *ext;
5705 switch (relo->type) {
5707 if (obj->gen_loader) {
5708 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5709 insn[0].imm = relo->map_idx;
5711 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5712 insn[0].imm = obj->maps[relo->map_idx].fd;
5716 insn[1].imm = insn[0].imm + relo->sym_off;
5717 if (obj->gen_loader) {
5718 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5719 insn[0].imm = relo->map_idx;
5721 const struct bpf_map *map = &obj->maps[relo->map_idx];
5724 pr_warn("prog '%s': relo #%d: kernel doesn't support global data\n",
5728 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5729 insn[0].imm = obj->maps[relo->map_idx].fd;
5732 case RELO_EXTERN_VAR:
5733 ext = &obj->externs[relo->sym_off];
5734 if (ext->type == EXT_KCFG) {
5735 if (obj->gen_loader) {
5736 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5737 insn[0].imm = obj->kconfig_map_idx;
5739 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5740 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5742 insn[1].imm = ext->kcfg.data_off;
5743 } else /* EXT_KSYM */ {
5744 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5745 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5746 insn[0].imm = ext->ksym.kernel_btf_id;
5747 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5748 } else { /* typeless ksyms or unresolved typed ksyms */
5749 insn[0].imm = (__u32)ext->ksym.addr;
5750 insn[1].imm = ext->ksym.addr >> 32;
5754 case RELO_EXTERN_FUNC:
5755 ext = &obj->externs[relo->sym_off];
5756 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5758 insn[0].imm = ext->ksym.kernel_btf_id;
5759 insn[0].off = ext->ksym.btf_fd_idx;
5760 } else { /* unresolved weak kfunc */
5765 case RELO_SUBPROG_ADDR:
5766 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5767 pr_warn("prog '%s': relo #%d: bad insn\n",
5771 /* handled already */
5774 /* handled already */
5777 /* will be handled by bpf_program_record_relos() */
5780 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5781 prog->name, i, relo->type);
5789 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5790 const struct bpf_program *prog,
5791 const struct btf_ext_info *ext_info,
5792 void **prog_info, __u32 *prog_rec_cnt,
5795 void *copy_start = NULL, *copy_end = NULL;
5796 void *rec, *rec_end, *new_prog_info;
5797 const struct btf_ext_info_sec *sec;
5798 size_t old_sz, new_sz;
5799 const char *sec_name;
5802 for_each_btf_ext_sec(ext_info, sec) {
5803 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5806 if (strcmp(sec_name, prog->sec_name) != 0)
5809 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5810 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5812 if (insn_off < prog->sec_insn_off)
5814 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5819 copy_end = rec + ext_info->rec_size;
5825 /* append func/line info of a given (sub-)program to the main
5826 * program func/line info
5828 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5829 new_sz = old_sz + (copy_end - copy_start);
5830 new_prog_info = realloc(*prog_info, new_sz);
5833 *prog_info = new_prog_info;
5834 *prog_rec_cnt = new_sz / ext_info->rec_size;
5835 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5837 /* Kernel instruction offsets are in units of 8-byte
5838 * instructions, while .BTF.ext instruction offsets generated
5839 * by Clang are in units of bytes. So convert Clang offsets
5840 * into kernel offsets and adjust offset according to program
5841 * relocated position.
5843 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5844 rec = new_prog_info + old_sz;
5845 rec_end = new_prog_info + new_sz;
5846 for (; rec < rec_end; rec += ext_info->rec_size) {
5847 __u32 *insn_off = rec;
5849 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5851 *prog_rec_sz = ext_info->rec_size;
5859 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5860 struct bpf_program *main_prog,
5861 const struct bpf_program *prog)
5865 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5866 * supprot func/line info
5868 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5871 /* only attempt func info relocation if main program's func_info
5872 * relocation was successful
5874 if (main_prog != prog && !main_prog->func_info)
5877 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5878 &main_prog->func_info,
5879 &main_prog->func_info_cnt,
5880 &main_prog->func_info_rec_size);
5882 if (err != -ENOENT) {
5883 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5887 if (main_prog->func_info) {
5889 * Some info has already been found but has problem
5890 * in the last btf_ext reloc. Must have to error out.
5892 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5895 /* Have problem loading the very first info. Ignore the rest. */
5896 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5901 /* don't relocate line info if main program's relocation failed */
5902 if (main_prog != prog && !main_prog->line_info)
5905 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5906 &main_prog->line_info,
5907 &main_prog->line_info_cnt,
5908 &main_prog->line_info_rec_size);
5910 if (err != -ENOENT) {
5911 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5915 if (main_prog->line_info) {
5917 * Some info has already been found but has problem
5918 * in the last btf_ext reloc. Must have to error out.
5920 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5923 /* Have problem loading the very first info. Ignore the rest. */
5924 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5930 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5932 size_t insn_idx = *(const size_t *)key;
5933 const struct reloc_desc *relo = elem;
5935 if (insn_idx == relo->insn_idx)
5937 return insn_idx < relo->insn_idx ? -1 : 1;
5940 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5942 if (!prog->nr_reloc)
5944 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5945 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5948 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5950 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5951 struct reloc_desc *relos;
5954 if (main_prog == subprog)
5956 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5959 if (subprog->nr_reloc)
5960 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5961 sizeof(*relos) * subprog->nr_reloc);
5963 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5964 relos[i].insn_idx += subprog->sub_insn_off;
5965 /* After insn_idx adjustment the 'relos' array is still sorted
5966 * by insn_idx and doesn't break bsearch.
5968 main_prog->reloc_desc = relos;
5969 main_prog->nr_reloc = new_cnt;
5974 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5975 struct bpf_program *prog)
5977 size_t sub_insn_idx, insn_idx, new_cnt;
5978 struct bpf_program *subprog;
5979 struct bpf_insn *insns, *insn;
5980 struct reloc_desc *relo;
5983 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5987 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5988 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5989 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
5992 relo = find_prog_insn_relo(prog, insn_idx);
5993 if (relo && relo->type == RELO_EXTERN_FUNC)
5994 /* kfunc relocations will be handled later
5995 * in bpf_object__relocate_data()
5998 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
5999 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6000 prog->name, insn_idx, relo->type);
6001 return -LIBBPF_ERRNO__RELOC;
6004 /* sub-program instruction index is a combination of
6005 * an offset of a symbol pointed to by relocation and
6006 * call instruction's imm field; for global functions,
6007 * call always has imm = -1, but for static functions
6008 * relocation is against STT_SECTION and insn->imm
6009 * points to a start of a static function
6011 * for subprog addr relocation, the relo->sym_off + insn->imm is
6012 * the byte offset in the corresponding section.
6014 if (relo->type == RELO_CALL)
6015 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6017 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6018 } else if (insn_is_pseudo_func(insn)) {
6020 * RELO_SUBPROG_ADDR relo is always emitted even if both
6021 * functions are in the same section, so it shouldn't reach here.
6023 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6024 prog->name, insn_idx);
6025 return -LIBBPF_ERRNO__RELOC;
6027 /* if subprogram call is to a static function within
6028 * the same ELF section, there won't be any relocation
6029 * emitted, but it also means there is no additional
6030 * offset necessary, insns->imm is relative to
6031 * instruction's original position within the section
6033 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6036 /* we enforce that sub-programs should be in .text section */
6037 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6039 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6041 return -LIBBPF_ERRNO__RELOC;
6044 /* if it's the first call instruction calling into this
6045 * subprogram (meaning this subprog hasn't been processed
6046 * yet) within the context of current main program:
6047 * - append it at the end of main program's instructions blog;
6048 * - process is recursively, while current program is put on hold;
6049 * - if that subprogram calls some other not yet processes
6050 * subprogram, same thing will happen recursively until
6051 * there are no more unprocesses subprograms left to append
6054 if (subprog->sub_insn_off == 0) {
6055 subprog->sub_insn_off = main_prog->insns_cnt;
6057 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6058 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6060 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6063 main_prog->insns = insns;
6064 main_prog->insns_cnt = new_cnt;
6066 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6067 subprog->insns_cnt * sizeof(*insns));
6069 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6070 main_prog->name, subprog->insns_cnt, subprog->name);
6072 /* The subprog insns are now appended. Append its relos too. */
6073 err = append_subprog_relos(main_prog, subprog);
6076 err = bpf_object__reloc_code(obj, main_prog, subprog);
6081 /* main_prog->insns memory could have been re-allocated, so
6082 * calculate pointer again
6084 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6085 /* calculate correct instruction position within current main
6086 * prog; each main prog can have a different set of
6087 * subprograms appended (potentially in different order as
6088 * well), so position of any subprog can be different for
6089 * different main programs */
6090 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6092 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6093 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6100 * Relocate sub-program calls.
6102 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6103 * main prog) is processed separately. For each subprog (non-entry functions,
6104 * that can be called from either entry progs or other subprogs) gets their
6105 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6106 * hasn't been yet appended and relocated within current main prog. Once its
6107 * relocated, sub_insn_off will point at the position within current main prog
6108 * where given subprog was appended. This will further be used to relocate all
6109 * the call instructions jumping into this subprog.
6111 * We start with main program and process all call instructions. If the call
6112 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6113 * is zero), subprog instructions are appended at the end of main program's
6114 * instruction array. Then main program is "put on hold" while we recursively
6115 * process newly appended subprogram. If that subprogram calls into another
6116 * subprogram that hasn't been appended, new subprogram is appended again to
6117 * the *main* prog's instructions (subprog's instructions are always left
6118 * untouched, as they need to be in unmodified state for subsequent main progs
6119 * and subprog instructions are always sent only as part of a main prog) and
6120 * the process continues recursively. Once all the subprogs called from a main
6121 * prog or any of its subprogs are appended (and relocated), all their
6122 * positions within finalized instructions array are known, so it's easy to
6123 * rewrite call instructions with correct relative offsets, corresponding to
6124 * desired target subprog.
6126 * Its important to realize that some subprogs might not be called from some
6127 * main prog and any of its called/used subprogs. Those will keep their
6128 * subprog->sub_insn_off as zero at all times and won't be appended to current
6129 * main prog and won't be relocated within the context of current main prog.
6130 * They might still be used from other main progs later.
6132 * Visually this process can be shown as below. Suppose we have two main
6133 * programs mainA and mainB and BPF object contains three subprogs: subA,
6134 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6135 * subC both call subB:
6137 * +--------+ +-------+
6139 * +--+---+ +--+-+-+ +---+--+
6140 * | subA | | subB | | subC |
6141 * +--+---+ +------+ +---+--+
6144 * +---+-------+ +------+----+
6145 * | mainA | | mainB |
6146 * +-----------+ +-----------+
6148 * We'll start relocating mainA, will find subA, append it and start
6149 * processing sub A recursively:
6151 * +-----------+------+
6153 * +-----------+------+
6155 * At this point we notice that subB is used from subA, so we append it and
6156 * relocate (there are no further subcalls from subB):
6158 * +-----------+------+------+
6159 * | mainA | subA | subB |
6160 * +-----------+------+------+
6162 * At this point, we relocate subA calls, then go one level up and finish with
6163 * relocatin mainA calls. mainA is done.
6165 * For mainB process is similar but results in different order. We start with
6166 * mainB and skip subA and subB, as mainB never calls them (at least
6167 * directly), but we see subC is needed, so we append and start processing it:
6169 * +-----------+------+
6171 * +-----------+------+
6172 * Now we see subC needs subB, so we go back to it, append and relocate it:
6174 * +-----------+------+------+
6175 * | mainB | subC | subB |
6176 * +-----------+------+------+
6178 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6181 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6183 struct bpf_program *subprog;
6186 /* mark all subprogs as not relocated (yet) within the context of
6187 * current main program
6189 for (i = 0; i < obj->nr_programs; i++) {
6190 subprog = &obj->programs[i];
6191 if (!prog_is_subprog(obj, subprog))
6194 subprog->sub_insn_off = 0;
6197 err = bpf_object__reloc_code(obj, prog, prog);
6206 bpf_object__free_relocs(struct bpf_object *obj)
6208 struct bpf_program *prog;
6211 /* free up relocation descriptors */
6212 for (i = 0; i < obj->nr_programs; i++) {
6213 prog = &obj->programs[i];
6214 zfree(&prog->reloc_desc);
6219 static int cmp_relocs(const void *_a, const void *_b)
6221 const struct reloc_desc *a = _a;
6222 const struct reloc_desc *b = _b;
6224 if (a->insn_idx != b->insn_idx)
6225 return a->insn_idx < b->insn_idx ? -1 : 1;
6227 /* no two relocations should have the same insn_idx, but ... */
6228 if (a->type != b->type)
6229 return a->type < b->type ? -1 : 1;
6234 static void bpf_object__sort_relos(struct bpf_object *obj)
6238 for (i = 0; i < obj->nr_programs; i++) {
6239 struct bpf_program *p = &obj->programs[i];
6244 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6249 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6251 struct bpf_program *prog;
6256 err = bpf_object__relocate_core(obj, targ_btf_path);
6258 pr_warn("failed to perform CO-RE relocations: %d\n",
6262 if (obj->gen_loader)
6263 bpf_object__sort_relos(obj);
6266 /* Before relocating calls pre-process relocations and mark
6267 * few ld_imm64 instructions that points to subprogs.
6268 * Otherwise bpf_object__reloc_code() later would have to consider
6269 * all ld_imm64 insns as relocation candidates. That would
6270 * reduce relocation speed, since amount of find_prog_insn_relo()
6271 * would increase and most of them will fail to find a relo.
6273 for (i = 0; i < obj->nr_programs; i++) {
6274 prog = &obj->programs[i];
6275 for (j = 0; j < prog->nr_reloc; j++) {
6276 struct reloc_desc *relo = &prog->reloc_desc[j];
6277 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6279 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6280 if (relo->type == RELO_SUBPROG_ADDR)
6281 insn[0].src_reg = BPF_PSEUDO_FUNC;
6285 /* relocate subprogram calls and append used subprograms to main
6286 * programs; each copy of subprogram code needs to be relocated
6287 * differently for each main program, because its code location might
6289 * Append subprog relos to main programs to allow data relos to be
6290 * processed after text is completely relocated.
6292 for (i = 0; i < obj->nr_programs; i++) {
6293 prog = &obj->programs[i];
6294 /* sub-program's sub-calls are relocated within the context of
6295 * its main program only
6297 if (prog_is_subprog(obj, prog))
6302 err = bpf_object__relocate_calls(obj, prog);
6304 pr_warn("prog '%s': failed to relocate calls: %d\n",
6309 /* Process data relos for main programs */
6310 for (i = 0; i < obj->nr_programs; i++) {
6311 prog = &obj->programs[i];
6312 if (prog_is_subprog(obj, prog))
6316 err = bpf_object__relocate_data(obj, prog);
6318 pr_warn("prog '%s': failed to relocate data references: %d\n",
6323 if (!obj->gen_loader)
6324 bpf_object__free_relocs(obj);
6328 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6329 Elf64_Shdr *shdr, Elf_Data *data);
6331 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6332 Elf64_Shdr *shdr, Elf_Data *data)
6334 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6335 int i, j, nrels, new_sz;
6336 const struct btf_var_secinfo *vi = NULL;
6337 const struct btf_type *sec, *var, *def;
6338 struct bpf_map *map = NULL, *targ_map = NULL;
6339 struct bpf_program *targ_prog = NULL;
6340 bool is_prog_array, is_map_in_map;
6341 const struct btf_member *member;
6342 const char *name, *mname, *type;
6348 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6350 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6354 nrels = shdr->sh_size / shdr->sh_entsize;
6355 for (i = 0; i < nrels; i++) {
6356 rel = elf_rel_by_idx(data, i);
6358 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6359 return -LIBBPF_ERRNO__FORMAT;
6362 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6364 pr_warn(".maps relo #%d: symbol %zx not found\n",
6365 i, (size_t)ELF64_R_SYM(rel->r_info));
6366 return -LIBBPF_ERRNO__FORMAT;
6368 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6370 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6371 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6372 (size_t)rel->r_offset, sym->st_name, name);
6374 for (j = 0; j < obj->nr_maps; j++) {
6375 map = &obj->maps[j];
6376 if (map->sec_idx != obj->efile.btf_maps_shndx)
6379 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6380 if (vi->offset <= rel->r_offset &&
6381 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6384 if (j == obj->nr_maps) {
6385 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6386 i, name, (size_t)rel->r_offset);
6390 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6391 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6392 type = is_map_in_map ? "map" : "prog";
6393 if (is_map_in_map) {
6394 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6395 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6397 return -LIBBPF_ERRNO__RELOC;
6399 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6400 map->def.key_size != sizeof(int)) {
6401 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6402 i, map->name, sizeof(int));
6405 targ_map = bpf_object__find_map_by_name(obj, name);
6407 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6411 } else if (is_prog_array) {
6412 targ_prog = bpf_object__find_program_by_name(obj, name);
6414 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6418 if (targ_prog->sec_idx != sym->st_shndx ||
6419 targ_prog->sec_insn_off * 8 != sym->st_value ||
6420 prog_is_subprog(obj, targ_prog)) {
6421 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6423 return -LIBBPF_ERRNO__RELOC;
6429 var = btf__type_by_id(obj->btf, vi->type);
6430 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6431 if (btf_vlen(def) == 0)
6433 member = btf_members(def) + btf_vlen(def) - 1;
6434 mname = btf__name_by_offset(obj->btf, member->name_off);
6435 if (strcmp(mname, "values"))
6438 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6439 if (rel->r_offset - vi->offset < moff)
6442 moff = rel->r_offset - vi->offset - moff;
6443 /* here we use BPF pointer size, which is always 64 bit, as we
6444 * are parsing ELF that was built for BPF target
6446 if (moff % bpf_ptr_sz)
6449 if (moff >= map->init_slots_sz) {
6451 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6454 map->init_slots = tmp;
6455 memset(map->init_slots + map->init_slots_sz, 0,
6456 (new_sz - map->init_slots_sz) * host_ptr_sz);
6457 map->init_slots_sz = new_sz;
6459 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6461 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6462 i, map->name, moff, type, name);
6468 static int bpf_object__collect_relos(struct bpf_object *obj)
6472 for (i = 0; i < obj->efile.sec_cnt; i++) {
6473 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6478 if (sec_desc->sec_type != SEC_RELO)
6481 shdr = sec_desc->shdr;
6482 data = sec_desc->data;
6483 idx = shdr->sh_info;
6485 if (shdr->sh_type != SHT_REL) {
6486 pr_warn("internal error at %d\n", __LINE__);
6487 return -LIBBPF_ERRNO__INTERNAL;
6490 if (idx == obj->efile.st_ops_shndx)
6491 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6492 else if (idx == obj->efile.btf_maps_shndx)
6493 err = bpf_object__collect_map_relos(obj, shdr, data);
6495 err = bpf_object__collect_prog_relos(obj, shdr, data);
6500 bpf_object__sort_relos(obj);
6504 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6506 if (BPF_CLASS(insn->code) == BPF_JMP &&
6507 BPF_OP(insn->code) == BPF_CALL &&
6508 BPF_SRC(insn->code) == BPF_K &&
6509 insn->src_reg == 0 &&
6510 insn->dst_reg == 0) {
6511 *func_id = insn->imm;
6517 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6519 struct bpf_insn *insn = prog->insns;
6520 enum bpf_func_id func_id;
6523 if (obj->gen_loader)
6526 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6527 if (!insn_is_helper_call(insn, &func_id))
6530 /* on kernels that don't yet support
6531 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6532 * to bpf_probe_read() which works well for old kernels
6535 case BPF_FUNC_probe_read_kernel:
6536 case BPF_FUNC_probe_read_user:
6537 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6538 insn->imm = BPF_FUNC_probe_read;
6540 case BPF_FUNC_probe_read_kernel_str:
6541 case BPF_FUNC_probe_read_user_str:
6542 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6543 insn->imm = BPF_FUNC_probe_read_str;
6552 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6553 int *btf_obj_fd, int *btf_type_id);
6555 /* this is called as prog->sec_def->preload_fn for libbpf-supported sec_defs */
6556 static int libbpf_preload_prog(struct bpf_program *prog,
6557 struct bpf_prog_load_opts *opts, long cookie)
6559 enum sec_def_flags def = cookie;
6561 /* old kernels might not support specifying expected_attach_type */
6562 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6563 opts->expected_attach_type = 0;
6565 if (def & SEC_SLEEPABLE)
6566 opts->prog_flags |= BPF_F_SLEEPABLE;
6568 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6569 prog->type == BPF_PROG_TYPE_LSM ||
6570 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6571 int btf_obj_fd = 0, btf_type_id = 0, err;
6572 const char *attach_name;
6574 attach_name = strchr(prog->sec_name, '/') + 1;
6575 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6579 /* cache resolved BTF FD and BTF type ID in the prog */
6580 prog->attach_btf_obj_fd = btf_obj_fd;
6581 prog->attach_btf_id = btf_type_id;
6583 /* but by now libbpf common logic is not utilizing
6584 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6585 * this callback is called after opts were populated by
6586 * libbpf, so this callback has to update opts explicitly here
6588 opts->attach_btf_obj_fd = btf_obj_fd;
6589 opts->attach_btf_id = btf_type_id;
6594 static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6595 struct bpf_insn *insns, int insns_cnt,
6596 const char *license, __u32 kern_version,
6599 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6600 const char *prog_name = NULL;
6601 char *cp, errmsg[STRERR_BUFSIZE];
6602 size_t log_buf_size = 0;
6603 char *log_buf = NULL, *tmp;
6604 int btf_fd, ret, err;
6605 bool own_log_buf = true;
6606 __u32 log_level = prog->log_level;
6608 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6610 * The program type must be set. Most likely we couldn't find a proper
6611 * section definition at load time, and thus we didn't infer the type.
6613 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6614 prog->name, prog->sec_name);
6618 if (!insns || !insns_cnt)
6621 load_attr.expected_attach_type = prog->expected_attach_type;
6622 if (kernel_supports(obj, FEAT_PROG_NAME))
6623 prog_name = prog->name;
6624 load_attr.attach_prog_fd = prog->attach_prog_fd;
6625 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6626 load_attr.attach_btf_id = prog->attach_btf_id;
6627 load_attr.kern_version = kern_version;
6628 load_attr.prog_ifindex = prog->prog_ifindex;
6630 /* specify func_info/line_info only if kernel supports them */
6631 btf_fd = bpf_object__btf_fd(obj);
6632 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6633 load_attr.prog_btf_fd = btf_fd;
6634 load_attr.func_info = prog->func_info;
6635 load_attr.func_info_rec_size = prog->func_info_rec_size;
6636 load_attr.func_info_cnt = prog->func_info_cnt;
6637 load_attr.line_info = prog->line_info;
6638 load_attr.line_info_rec_size = prog->line_info_rec_size;
6639 load_attr.line_info_cnt = prog->line_info_cnt;
6641 load_attr.log_level = log_level;
6642 load_attr.prog_flags = prog->prog_flags;
6643 load_attr.fd_array = obj->fd_array;
6645 /* adjust load_attr if sec_def provides custom preload callback */
6646 if (prog->sec_def && prog->sec_def->preload_fn) {
6647 err = prog->sec_def->preload_fn(prog, &load_attr, prog->sec_def->cookie);
6649 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6655 if (obj->gen_loader) {
6656 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6657 license, insns, insns_cnt, &load_attr,
6658 prog - obj->programs);
6664 /* if log_level is zero, we don't request logs initiallly even if
6665 * custom log_buf is specified; if the program load fails, then we'll
6666 * bump log_level to 1 and use either custom log_buf or we'll allocate
6667 * our own and retry the load to get details on what failed
6670 if (prog->log_buf) {
6671 log_buf = prog->log_buf;
6672 log_buf_size = prog->log_size;
6673 own_log_buf = false;
6674 } else if (obj->log_buf) {
6675 log_buf = obj->log_buf;
6676 log_buf_size = obj->log_size;
6677 own_log_buf = false;
6679 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6680 tmp = realloc(log_buf, log_buf_size);
6691 load_attr.log_buf = log_buf;
6692 load_attr.log_size = log_buf_size;
6693 load_attr.log_level = log_level;
6695 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6697 if (log_level && own_log_buf) {
6698 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6699 prog->name, log_buf);
6702 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6703 struct bpf_map *map;
6706 for (i = 0; i < obj->nr_maps; i++) {
6707 map = &prog->obj->maps[i];
6708 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6711 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6712 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6713 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6714 prog->name, map->real_name, cp);
6715 /* Don't fail hard if can't bind rodata. */
6725 if (log_level == 0) {
6729 /* On ENOSPC, increase log buffer size and retry, unless custom
6730 * log_buf is specified.
6731 * Be careful to not overflow u32, though. Kernel's log buf size limit
6732 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6733 * multiply by 2 unless we are sure we'll fit within 32 bits.
6734 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6736 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6740 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6741 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6744 if (own_log_buf && log_buf && log_buf[0] != '\0') {
6745 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6746 prog->name, log_buf);
6748 if (insns_cnt >= BPF_MAXINSNS) {
6749 pr_warn("prog '%s': program too large (%d insns), at most %d insns\n",
6750 prog->name, insns_cnt, BPF_MAXINSNS);
6759 static int bpf_program_record_relos(struct bpf_program *prog)
6761 struct bpf_object *obj = prog->obj;
6764 for (i = 0; i < prog->nr_reloc; i++) {
6765 struct reloc_desc *relo = &prog->reloc_desc[i];
6766 struct extern_desc *ext = &obj->externs[relo->sym_off];
6768 switch (relo->type) {
6769 case RELO_EXTERN_VAR:
6770 if (ext->type != EXT_KSYM)
6772 bpf_gen__record_extern(obj->gen_loader, ext->name,
6773 ext->is_weak, !ext->ksym.type_id,
6774 BTF_KIND_VAR, relo->insn_idx);
6776 case RELO_EXTERN_FUNC:
6777 bpf_gen__record_extern(obj->gen_loader, ext->name,
6778 ext->is_weak, false, BTF_KIND_FUNC,
6782 struct bpf_core_relo cr = {
6783 .insn_off = relo->insn_idx * 8,
6784 .type_id = relo->core_relo->type_id,
6785 .access_str_off = relo->core_relo->access_str_off,
6786 .kind = relo->core_relo->kind,
6789 bpf_gen__record_relo_core(obj->gen_loader, &cr);
6799 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6800 const char *license, __u32 kern_ver)
6805 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6806 return libbpf_err(-EINVAL);
6809 if (prog->instances.nr < 0 || !prog->instances.fds) {
6810 if (prog->preprocessor) {
6811 pr_warn("Internal error: can't load program '%s'\n",
6813 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
6816 prog->instances.fds = malloc(sizeof(int));
6817 if (!prog->instances.fds) {
6818 pr_warn("Not enough memory for BPF fds\n");
6819 return libbpf_err(-ENOMEM);
6821 prog->instances.nr = 1;
6822 prog->instances.fds[0] = -1;
6825 if (!prog->preprocessor) {
6826 if (prog->instances.nr != 1) {
6827 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6828 prog->name, prog->instances.nr);
6830 if (obj->gen_loader)
6831 bpf_program_record_relos(prog);
6832 err = bpf_object_load_prog_instance(obj, prog,
6833 prog->insns, prog->insns_cnt,
6834 license, kern_ver, &fd);
6836 prog->instances.fds[0] = fd;
6840 for (i = 0; i < prog->instances.nr; i++) {
6841 struct bpf_prog_prep_result result;
6842 bpf_program_prep_t preprocessor = prog->preprocessor;
6844 memset(&result, 0, sizeof(result));
6845 err = preprocessor(prog, i, prog->insns,
6846 prog->insns_cnt, &result);
6848 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6853 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6854 pr_debug("Skip loading the %dth instance of program '%s'\n",
6856 prog->instances.fds[i] = -1;
6862 err = bpf_object_load_prog_instance(obj, prog,
6863 result.new_insn_ptr, result.new_insn_cnt,
6864 license, kern_ver, &fd);
6866 pr_warn("Loading the %dth instance of program '%s' failed\n",
6873 prog->instances.fds[i] = fd;
6877 pr_warn("failed to load program '%s'\n", prog->name);
6878 return libbpf_err(err);
6881 int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
6883 return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
6887 bpf_object__load_progs(struct bpf_object *obj, int log_level)
6889 struct bpf_program *prog;
6893 for (i = 0; i < obj->nr_programs; i++) {
6894 prog = &obj->programs[i];
6895 err = bpf_object__sanitize_prog(obj, prog);
6900 for (i = 0; i < obj->nr_programs; i++) {
6901 prog = &obj->programs[i];
6902 if (prog_is_subprog(obj, prog))
6905 pr_debug("prog '%s': skipped loading\n", prog->name);
6908 prog->log_level |= log_level;
6909 err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
6913 if (obj->gen_loader)
6914 bpf_object__free_relocs(obj);
6918 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6920 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
6922 struct bpf_program *prog;
6925 bpf_object__for_each_program(prog, obj) {
6926 prog->sec_def = find_sec_def(prog->sec_name);
6927 if (!prog->sec_def) {
6928 /* couldn't guess, but user might manually specify */
6929 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6930 prog->name, prog->sec_name);
6934 bpf_program__set_type(prog, prog->sec_def->prog_type);
6935 bpf_program__set_expected_attach_type(prog, prog->sec_def->expected_attach_type);
6937 #pragma GCC diagnostic push
6938 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
6939 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6940 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6941 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6942 #pragma GCC diagnostic pop
6944 /* sec_def can have custom callback which should be called
6945 * after bpf_program is initialized to adjust its properties
6947 if (prog->sec_def->init_fn) {
6948 err = prog->sec_def->init_fn(prog, prog->sec_def->cookie);
6950 pr_warn("prog '%s': failed to initialize: %d\n",
6960 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6961 const struct bpf_object_open_opts *opts)
6963 const char *obj_name, *kconfig, *btf_tmp_path;
6964 struct bpf_object *obj;
6971 if (elf_version(EV_CURRENT) == EV_NONE) {
6972 pr_warn("failed to init libelf for %s\n",
6973 path ? : "(mem buf)");
6974 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6977 if (!OPTS_VALID(opts, bpf_object_open_opts))
6978 return ERR_PTR(-EINVAL);
6980 obj_name = OPTS_GET(opts, object_name, NULL);
6983 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6984 (unsigned long)obj_buf,
6985 (unsigned long)obj_buf_sz);
6986 obj_name = tmp_name;
6989 pr_debug("loading object '%s' from buffer\n", obj_name);
6992 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
6993 log_size = OPTS_GET(opts, kernel_log_size, 0);
6994 log_level = OPTS_GET(opts, kernel_log_level, 0);
6995 if (log_size > UINT_MAX)
6996 return ERR_PTR(-EINVAL);
6997 if (log_size && !log_buf)
6998 return ERR_PTR(-EINVAL);
7000 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7004 obj->log_buf = log_buf;
7005 obj->log_size = log_size;
7006 obj->log_level = log_level;
7008 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7010 if (strlen(btf_tmp_path) >= PATH_MAX) {
7011 err = -ENAMETOOLONG;
7014 obj->btf_custom_path = strdup(btf_tmp_path);
7015 if (!obj->btf_custom_path) {
7021 kconfig = OPTS_GET(opts, kconfig, NULL);
7023 obj->kconfig = strdup(kconfig);
7024 if (!obj->kconfig) {
7030 err = bpf_object__elf_init(obj);
7031 err = err ? : bpf_object__check_endianness(obj);
7032 err = err ? : bpf_object__elf_collect(obj);
7033 err = err ? : bpf_object__collect_externs(obj);
7034 err = err ? : bpf_object__finalize_btf(obj);
7035 err = err ? : bpf_object__init_maps(obj, opts);
7036 err = err ? : bpf_object_init_progs(obj, opts);
7037 err = err ? : bpf_object__collect_relos(obj);
7041 bpf_object__elf_finish(obj);
7045 bpf_object__close(obj);
7046 return ERR_PTR(err);
7049 static struct bpf_object *
7050 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
7052 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7053 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
7056 /* param validation */
7060 pr_debug("loading %s\n", attr->file);
7061 return bpf_object_open(attr->file, NULL, 0, &opts);
7064 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7066 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
7069 struct bpf_object *bpf_object__open(const char *path)
7071 struct bpf_object_open_attr attr = {
7073 .prog_type = BPF_PROG_TYPE_UNSPEC,
7076 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
7080 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7083 return libbpf_err_ptr(-EINVAL);
7085 pr_debug("loading %s\n", path);
7087 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7091 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7092 const struct bpf_object_open_opts *opts)
7094 if (!obj_buf || obj_buf_sz == 0)
7095 return libbpf_err_ptr(-EINVAL);
7097 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7101 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7104 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7105 .object_name = name,
7106 /* wrong default, but backwards-compatible */
7107 .relaxed_maps = true,
7110 /* returning NULL is wrong, but backwards-compatible */
7111 if (!obj_buf || obj_buf_sz == 0)
7112 return errno = EINVAL, NULL;
7114 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
7117 static int bpf_object_unload(struct bpf_object *obj)
7122 return libbpf_err(-EINVAL);
7124 for (i = 0; i < obj->nr_maps; i++) {
7125 zclose(obj->maps[i].fd);
7126 if (obj->maps[i].st_ops)
7127 zfree(&obj->maps[i].st_ops->kern_vdata);
7130 for (i = 0; i < obj->nr_programs; i++)
7131 bpf_program__unload(&obj->programs[i]);
7136 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7138 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7142 bpf_object__for_each_map(m, obj) {
7143 if (!bpf_map__is_internal(m))
7145 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7146 m->def.map_flags ^= BPF_F_MMAPABLE;
7152 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7154 char sym_type, sym_name[500];
7155 unsigned long long sym_addr;
7156 const struct btf_type *t;
7157 struct extern_desc *ext;
7161 f = fopen("/proc/kallsyms", "r");
7164 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7169 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7170 &sym_addr, &sym_type, sym_name);
7171 if (ret == EOF && feof(f))
7174 pr_warn("failed to read kallsyms entry: %d\n", ret);
7179 ext = find_extern_by_name(obj, sym_name);
7180 if (!ext || ext->type != EXT_KSYM)
7183 t = btf__type_by_id(obj->btf, ext->btf_id);
7187 if (ext->is_set && ext->ksym.addr != sym_addr) {
7188 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7189 sym_name, ext->ksym.addr, sym_addr);
7195 ext->ksym.addr = sym_addr;
7196 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7205 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7206 __u16 kind, struct btf **res_btf,
7207 struct module_btf **res_mod_btf)
7209 struct module_btf *mod_btf;
7213 btf = obj->btf_vmlinux;
7215 id = btf__find_by_name_kind(btf, ksym_name, kind);
7217 if (id == -ENOENT) {
7218 err = load_module_btfs(obj);
7222 for (i = 0; i < obj->btf_module_cnt; i++) {
7223 /* we assume module_btf's BTF FD is always >0 */
7224 mod_btf = &obj->btf_modules[i];
7226 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7235 *res_mod_btf = mod_btf;
7239 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7240 struct extern_desc *ext)
7242 const struct btf_type *targ_var, *targ_type;
7243 __u32 targ_type_id, local_type_id;
7244 struct module_btf *mod_btf = NULL;
7245 const char *targ_var_name;
7246 struct btf *btf = NULL;
7249 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7251 if (id == -ESRCH && ext->is_weak)
7253 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7258 /* find local type_id */
7259 local_type_id = ext->ksym.type_id;
7261 /* find target type_id */
7262 targ_var = btf__type_by_id(btf, id);
7263 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7264 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7266 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7269 const struct btf_type *local_type;
7270 const char *targ_name, *local_name;
7272 local_type = btf__type_by_id(obj->btf, local_type_id);
7273 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7274 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7276 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7277 ext->name, local_type_id,
7278 btf_kind_str(local_type), local_name, targ_type_id,
7279 btf_kind_str(targ_type), targ_name);
7284 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7285 ext->ksym.kernel_btf_id = id;
7286 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7287 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7292 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7293 struct extern_desc *ext)
7295 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7296 struct module_btf *mod_btf = NULL;
7297 const struct btf_type *kern_func;
7298 struct btf *kern_btf = NULL;
7301 local_func_proto_id = ext->ksym.type_id;
7303 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7305 if (kfunc_id == -ESRCH && ext->is_weak)
7307 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7312 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7313 kfunc_proto_id = kern_func->type;
7315 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7316 kern_btf, kfunc_proto_id);
7318 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7319 ext->name, local_func_proto_id, kfunc_proto_id);
7323 /* set index for module BTF fd in fd_array, if unset */
7324 if (mod_btf && !mod_btf->fd_array_idx) {
7325 /* insn->off is s16 */
7326 if (obj->fd_array_cnt == INT16_MAX) {
7327 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7328 ext->name, mod_btf->fd_array_idx);
7331 /* Cannot use index 0 for module BTF fd */
7332 if (!obj->fd_array_cnt)
7333 obj->fd_array_cnt = 1;
7335 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7336 obj->fd_array_cnt + 1);
7339 mod_btf->fd_array_idx = obj->fd_array_cnt;
7340 /* we assume module BTF FD is always >0 */
7341 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7345 ext->ksym.kernel_btf_id = kfunc_id;
7346 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7347 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7348 ext->name, kfunc_id);
7353 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7355 const struct btf_type *t;
7356 struct extern_desc *ext;
7359 for (i = 0; i < obj->nr_extern; i++) {
7360 ext = &obj->externs[i];
7361 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7364 if (obj->gen_loader) {
7366 ext->ksym.kernel_btf_obj_fd = 0;
7367 ext->ksym.kernel_btf_id = 0;
7370 t = btf__type_by_id(obj->btf, ext->btf_id);
7372 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7374 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7381 static int bpf_object__resolve_externs(struct bpf_object *obj,
7382 const char *extra_kconfig)
7384 bool need_config = false, need_kallsyms = false;
7385 bool need_vmlinux_btf = false;
7386 struct extern_desc *ext;
7387 void *kcfg_data = NULL;
7390 if (obj->nr_extern == 0)
7393 if (obj->kconfig_map_idx >= 0)
7394 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7396 for (i = 0; i < obj->nr_extern; i++) {
7397 ext = &obj->externs[i];
7399 if (ext->type == EXT_KCFG &&
7400 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7401 void *ext_val = kcfg_data + ext->kcfg.data_off;
7402 __u32 kver = get_kernel_version();
7405 pr_warn("failed to get kernel version\n");
7408 err = set_kcfg_value_num(ext, ext_val, kver);
7411 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
7412 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
7414 } else if (ext->type == EXT_KSYM) {
7415 if (ext->ksym.type_id)
7416 need_vmlinux_btf = true;
7418 need_kallsyms = true;
7420 pr_warn("unrecognized extern '%s'\n", ext->name);
7424 if (need_config && extra_kconfig) {
7425 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7428 need_config = false;
7429 for (i = 0; i < obj->nr_extern; i++) {
7430 ext = &obj->externs[i];
7431 if (ext->type == EXT_KCFG && !ext->is_set) {
7438 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7442 if (need_kallsyms) {
7443 err = bpf_object__read_kallsyms_file(obj);
7447 if (need_vmlinux_btf) {
7448 err = bpf_object__resolve_ksyms_btf_id(obj);
7452 for (i = 0; i < obj->nr_extern; i++) {
7453 ext = &obj->externs[i];
7455 if (!ext->is_set && !ext->is_weak) {
7456 pr_warn("extern %s (strong) not resolved\n", ext->name);
7458 } else if (!ext->is_set) {
7459 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7467 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7472 return libbpf_err(-EINVAL);
7475 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7476 return libbpf_err(-EINVAL);
7479 if (obj->gen_loader)
7480 bpf_gen__init(obj->gen_loader, extra_log_level);
7482 err = bpf_object__probe_loading(obj);
7483 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7484 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7485 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7486 err = err ? : bpf_object__sanitize_maps(obj);
7487 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7488 err = err ? : bpf_object__create_maps(obj);
7489 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7490 err = err ? : bpf_object__load_progs(obj, extra_log_level);
7491 err = err ? : bpf_object_init_prog_arrays(obj);
7493 if (obj->gen_loader) {
7496 btf__set_fd(obj->btf, -1);
7497 for (i = 0; i < obj->nr_maps; i++)
7498 obj->maps[i].fd = -1;
7500 err = bpf_gen__finish(obj->gen_loader);
7503 /* clean up fd_array */
7504 zfree(&obj->fd_array);
7506 /* clean up module BTFs */
7507 for (i = 0; i < obj->btf_module_cnt; i++) {
7508 close(obj->btf_modules[i].fd);
7509 btf__free(obj->btf_modules[i].btf);
7510 free(obj->btf_modules[i].name);
7512 free(obj->btf_modules);
7514 /* clean up vmlinux BTF */
7515 btf__free(obj->btf_vmlinux);
7516 obj->btf_vmlinux = NULL;
7518 obj->loaded = true; /* doesn't matter if successfully or not */
7525 /* unpin any maps that were auto-pinned during load */
7526 for (i = 0; i < obj->nr_maps; i++)
7527 if (obj->maps[i].pinned && !obj->maps[i].reused)
7528 bpf_map__unpin(&obj->maps[i], NULL);
7530 bpf_object_unload(obj);
7531 pr_warn("failed to load object '%s'\n", obj->path);
7532 return libbpf_err(err);
7535 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
7537 return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
7540 int bpf_object__load(struct bpf_object *obj)
7542 return bpf_object_load(obj, 0, NULL);
7545 static int make_parent_dir(const char *path)
7547 char *cp, errmsg[STRERR_BUFSIZE];
7551 dname = strdup(path);
7555 dir = dirname(dname);
7556 if (mkdir(dir, 0700) && errno != EEXIST)
7561 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7562 pr_warn("failed to mkdir %s: %s\n", path, cp);
7567 static int check_path(const char *path)
7569 char *cp, errmsg[STRERR_BUFSIZE];
7570 struct statfs st_fs;
7577 dname = strdup(path);
7581 dir = dirname(dname);
7582 if (statfs(dir, &st_fs)) {
7583 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7584 pr_warn("failed to statfs %s: %s\n", dir, cp);
7589 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7590 pr_warn("specified path %s is not on BPF FS\n", path);
7597 static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
7599 char *cp, errmsg[STRERR_BUFSIZE];
7602 err = make_parent_dir(path);
7604 return libbpf_err(err);
7606 err = check_path(path);
7608 return libbpf_err(err);
7611 pr_warn("invalid program pointer\n");
7612 return libbpf_err(-EINVAL);
7615 if (instance < 0 || instance >= prog->instances.nr) {
7616 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7617 instance, prog->name, prog->instances.nr);
7618 return libbpf_err(-EINVAL);
7621 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
7623 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7624 pr_warn("failed to pin program: %s\n", cp);
7625 return libbpf_err(err);
7627 pr_debug("pinned program '%s'\n", path);
7632 static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
7636 err = check_path(path);
7638 return libbpf_err(err);
7641 pr_warn("invalid program pointer\n");
7642 return libbpf_err(-EINVAL);
7645 if (instance < 0 || instance >= prog->instances.nr) {
7646 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7647 instance, prog->name, prog->instances.nr);
7648 return libbpf_err(-EINVAL);
7653 return libbpf_err(-errno);
7655 pr_debug("unpinned program '%s'\n", path);
7660 __attribute__((alias("bpf_program_pin_instance")))
7661 int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
7663 __attribute__((alias("bpf_program_unpin_instance")))
7664 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
7666 int bpf_program__pin(struct bpf_program *prog, const char *path)
7670 err = make_parent_dir(path);
7672 return libbpf_err(err);
7674 err = check_path(path);
7676 return libbpf_err(err);
7679 pr_warn("invalid program pointer\n");
7680 return libbpf_err(-EINVAL);
7683 if (prog->instances.nr <= 0) {
7684 pr_warn("no instances of prog %s to pin\n", prog->name);
7685 return libbpf_err(-EINVAL);
7688 if (prog->instances.nr == 1) {
7689 /* don't create subdirs when pinning single instance */
7690 return bpf_program_pin_instance(prog, path, 0);
7693 for (i = 0; i < prog->instances.nr; i++) {
7697 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7701 } else if (len >= PATH_MAX) {
7702 err = -ENAMETOOLONG;
7706 err = bpf_program_pin_instance(prog, buf, i);
7714 for (i = i - 1; i >= 0; i--) {
7718 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7721 else if (len >= PATH_MAX)
7724 bpf_program_unpin_instance(prog, buf, i);
7729 return libbpf_err(err);
7732 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7736 err = check_path(path);
7738 return libbpf_err(err);
7741 pr_warn("invalid program pointer\n");
7742 return libbpf_err(-EINVAL);
7745 if (prog->instances.nr <= 0) {
7746 pr_warn("no instances of prog %s to pin\n", prog->name);
7747 return libbpf_err(-EINVAL);
7750 if (prog->instances.nr == 1) {
7751 /* don't create subdirs when pinning single instance */
7752 return bpf_program_unpin_instance(prog, path, 0);
7755 for (i = 0; i < prog->instances.nr; i++) {
7759 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7761 return libbpf_err(-EINVAL);
7762 else if (len >= PATH_MAX)
7763 return libbpf_err(-ENAMETOOLONG);
7765 err = bpf_program_unpin_instance(prog, buf, i);
7772 return libbpf_err(-errno);
7777 int bpf_map__pin(struct bpf_map *map, const char *path)
7779 char *cp, errmsg[STRERR_BUFSIZE];
7783 pr_warn("invalid map pointer\n");
7784 return libbpf_err(-EINVAL);
7787 if (map->pin_path) {
7788 if (path && strcmp(path, map->pin_path)) {
7789 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7790 bpf_map__name(map), map->pin_path, path);
7791 return libbpf_err(-EINVAL);
7792 } else if (map->pinned) {
7793 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7794 bpf_map__name(map), map->pin_path);
7799 pr_warn("missing a path to pin map '%s' at\n",
7800 bpf_map__name(map));
7801 return libbpf_err(-EINVAL);
7802 } else if (map->pinned) {
7803 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7804 return libbpf_err(-EEXIST);
7807 map->pin_path = strdup(path);
7808 if (!map->pin_path) {
7814 err = make_parent_dir(map->pin_path);
7816 return libbpf_err(err);
7818 err = check_path(map->pin_path);
7820 return libbpf_err(err);
7822 if (bpf_obj_pin(map->fd, map->pin_path)) {
7828 pr_debug("pinned map '%s'\n", map->pin_path);
7833 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7834 pr_warn("failed to pin map: %s\n", cp);
7835 return libbpf_err(err);
7838 int bpf_map__unpin(struct bpf_map *map, const char *path)
7843 pr_warn("invalid map pointer\n");
7844 return libbpf_err(-EINVAL);
7847 if (map->pin_path) {
7848 if (path && strcmp(path, map->pin_path)) {
7849 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7850 bpf_map__name(map), map->pin_path, path);
7851 return libbpf_err(-EINVAL);
7853 path = map->pin_path;
7855 pr_warn("no path to unpin map '%s' from\n",
7856 bpf_map__name(map));
7857 return libbpf_err(-EINVAL);
7860 err = check_path(path);
7862 return libbpf_err(err);
7866 return libbpf_err(-errno);
7868 map->pinned = false;
7869 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7874 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7881 return libbpf_err(-errno);
7884 free(map->pin_path);
7885 map->pin_path = new;
7889 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7891 return map->pin_path;
7894 const char *bpf_map__pin_path(const struct bpf_map *map)
7896 return map->pin_path;
7899 bool bpf_map__is_pinned(const struct bpf_map *map)
7904 static void sanitize_pin_path(char *s)
7906 /* bpffs disallows periods in path names */
7914 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7916 struct bpf_map *map;
7920 return libbpf_err(-ENOENT);
7923 pr_warn("object not yet loaded; load it first\n");
7924 return libbpf_err(-ENOENT);
7927 bpf_object__for_each_map(map, obj) {
7928 char *pin_path = NULL;
7937 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7938 bpf_map__name(map));
7941 goto err_unpin_maps;
7942 } else if (len >= PATH_MAX) {
7943 err = -ENAMETOOLONG;
7944 goto err_unpin_maps;
7946 sanitize_pin_path(buf);
7948 } else if (!map->pin_path) {
7952 err = bpf_map__pin(map, pin_path);
7954 goto err_unpin_maps;
7960 while ((map = bpf_object__prev_map(obj, map))) {
7964 bpf_map__unpin(map, NULL);
7967 return libbpf_err(err);
7970 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7972 struct bpf_map *map;
7976 return libbpf_err(-ENOENT);
7978 bpf_object__for_each_map(map, obj) {
7979 char *pin_path = NULL;
7985 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7986 bpf_map__name(map));
7988 return libbpf_err(-EINVAL);
7989 else if (len >= PATH_MAX)
7990 return libbpf_err(-ENAMETOOLONG);
7991 sanitize_pin_path(buf);
7993 } else if (!map->pin_path) {
7997 err = bpf_map__unpin(map, pin_path);
7999 return libbpf_err(err);
8005 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8007 struct bpf_program *prog;
8011 return libbpf_err(-ENOENT);
8014 pr_warn("object not yet loaded; load it first\n");
8015 return libbpf_err(-ENOENT);
8018 bpf_object__for_each_program(prog, obj) {
8022 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8026 goto err_unpin_programs;
8027 } else if (len >= PATH_MAX) {
8028 err = -ENAMETOOLONG;
8029 goto err_unpin_programs;
8032 err = bpf_program__pin(prog, buf);
8034 goto err_unpin_programs;
8040 while ((prog = bpf_object__prev_program(obj, prog))) {
8044 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8048 else if (len >= PATH_MAX)
8051 bpf_program__unpin(prog, buf);
8054 return libbpf_err(err);
8057 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8059 struct bpf_program *prog;
8063 return libbpf_err(-ENOENT);
8065 bpf_object__for_each_program(prog, obj) {
8069 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8072 return libbpf_err(-EINVAL);
8073 else if (len >= PATH_MAX)
8074 return libbpf_err(-ENAMETOOLONG);
8076 err = bpf_program__unpin(prog, buf);
8078 return libbpf_err(err);
8084 int bpf_object__pin(struct bpf_object *obj, const char *path)
8088 err = bpf_object__pin_maps(obj, path);
8090 return libbpf_err(err);
8092 err = bpf_object__pin_programs(obj, path);
8094 bpf_object__unpin_maps(obj, path);
8095 return libbpf_err(err);
8101 static void bpf_map__destroy(struct bpf_map *map)
8103 if (map->clear_priv)
8104 map->clear_priv(map, map->priv);
8106 map->clear_priv = NULL;
8108 if (map->inner_map) {
8109 bpf_map__destroy(map->inner_map);
8110 zfree(&map->inner_map);
8113 zfree(&map->init_slots);
8114 map->init_slots_sz = 0;
8117 munmap(map->mmaped, bpf_map_mmap_sz(map));
8122 zfree(&map->st_ops->data);
8123 zfree(&map->st_ops->progs);
8124 zfree(&map->st_ops->kern_func_off);
8125 zfree(&map->st_ops);
8129 zfree(&map->real_name);
8130 zfree(&map->pin_path);
8136 void bpf_object__close(struct bpf_object *obj)
8140 if (IS_ERR_OR_NULL(obj))
8143 if (obj->clear_priv)
8144 obj->clear_priv(obj, obj->priv);
8146 bpf_gen__free(obj->gen_loader);
8147 bpf_object__elf_finish(obj);
8148 bpf_object_unload(obj);
8149 btf__free(obj->btf);
8150 btf_ext__free(obj->btf_ext);
8152 for (i = 0; i < obj->nr_maps; i++)
8153 bpf_map__destroy(&obj->maps[i]);
8155 zfree(&obj->btf_custom_path);
8156 zfree(&obj->kconfig);
8157 zfree(&obj->externs);
8163 if (obj->programs && obj->nr_programs) {
8164 for (i = 0; i < obj->nr_programs; i++)
8165 bpf_program__exit(&obj->programs[i]);
8167 zfree(&obj->programs);
8169 list_del(&obj->list);
8174 bpf_object__next(struct bpf_object *prev)
8176 struct bpf_object *next;
8177 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8183 next = list_first_entry(&bpf_objects_list,
8187 next = list_next_entry(prev, list);
8189 /* Empty list is noticed here so don't need checking on entry. */
8190 if (&next->list == &bpf_objects_list)
8196 const char *bpf_object__name(const struct bpf_object *obj)
8198 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8201 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8203 return obj ? obj->kern_version : 0;
8206 struct btf *bpf_object__btf(const struct bpf_object *obj)
8208 return obj ? obj->btf : NULL;
8211 int bpf_object__btf_fd(const struct bpf_object *obj)
8213 return obj->btf ? btf__fd(obj->btf) : -1;
8216 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8219 return libbpf_err(-EINVAL);
8221 obj->kern_version = kern_version;
8226 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8227 bpf_object_clear_priv_t clear_priv)
8229 if (obj->priv && obj->clear_priv)
8230 obj->clear_priv(obj, obj->priv);
8233 obj->clear_priv = clear_priv;
8237 void *bpf_object__priv(const struct bpf_object *obj)
8239 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
8242 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8244 struct bpf_gen *gen;
8248 if (!OPTS_VALID(opts, gen_loader_opts))
8250 gen = calloc(sizeof(*gen), 1);
8254 obj->gen_loader = gen;
8258 static struct bpf_program *
8259 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8262 size_t nr_programs = obj->nr_programs;
8269 /* Iter from the beginning */
8270 return forward ? &obj->programs[0] :
8271 &obj->programs[nr_programs - 1];
8273 if (p->obj != obj) {
8274 pr_warn("error: program handler doesn't match object\n");
8275 return errno = EINVAL, NULL;
8278 idx = (p - obj->programs) + (forward ? 1 : -1);
8279 if (idx >= obj->nr_programs || idx < 0)
8281 return &obj->programs[idx];
8284 struct bpf_program *
8285 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
8287 return bpf_object__next_program(obj, prev);
8290 struct bpf_program *
8291 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8293 struct bpf_program *prog = prev;
8296 prog = __bpf_program__iter(prog, obj, true);
8297 } while (prog && prog_is_subprog(obj, prog));
8302 struct bpf_program *
8303 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8305 return bpf_object__prev_program(obj, next);
8308 struct bpf_program *
8309 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8311 struct bpf_program *prog = next;
8314 prog = __bpf_program__iter(prog, obj, false);
8315 } while (prog && prog_is_subprog(obj, prog));
8320 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8321 bpf_program_clear_priv_t clear_priv)
8323 if (prog->priv && prog->clear_priv)
8324 prog->clear_priv(prog, prog->priv);
8327 prog->clear_priv = clear_priv;
8331 void *bpf_program__priv(const struct bpf_program *prog)
8333 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
8336 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8338 prog->prog_ifindex = ifindex;
8341 const char *bpf_program__name(const struct bpf_program *prog)
8346 const char *bpf_program__section_name(const struct bpf_program *prog)
8348 return prog->sec_name;
8351 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
8355 title = prog->sec_name;
8357 title = strdup(title);
8359 pr_warn("failed to strdup program title\n");
8360 return libbpf_err_ptr(-ENOMEM);
8367 bool bpf_program__autoload(const struct bpf_program *prog)
8372 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8374 if (prog->obj->loaded)
8375 return libbpf_err(-EINVAL);
8377 prog->load = autoload;
8381 static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8383 int bpf_program__fd(const struct bpf_program *prog)
8385 return bpf_program_nth_fd(prog, 0);
8388 size_t bpf_program__size(const struct bpf_program *prog)
8390 return prog->insns_cnt * BPF_INSN_SZ;
8393 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8398 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8400 return prog->insns_cnt;
8403 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8404 bpf_program_prep_t prep)
8408 if (nr_instances <= 0 || !prep)
8409 return libbpf_err(-EINVAL);
8411 if (prog->instances.nr > 0 || prog->instances.fds) {
8412 pr_warn("Can't set pre-processor after loading\n");
8413 return libbpf_err(-EINVAL);
8416 instances_fds = malloc(sizeof(int) * nr_instances);
8417 if (!instances_fds) {
8418 pr_warn("alloc memory failed for fds\n");
8419 return libbpf_err(-ENOMEM);
8422 /* fill all fd with -1 */
8423 memset(instances_fds, -1, sizeof(int) * nr_instances);
8425 prog->instances.nr = nr_instances;
8426 prog->instances.fds = instances_fds;
8427 prog->preprocessor = prep;
8431 __attribute__((alias("bpf_program_nth_fd")))
8432 int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8434 static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
8439 return libbpf_err(-EINVAL);
8441 if (n >= prog->instances.nr || n < 0) {
8442 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
8443 n, prog->name, prog->instances.nr);
8444 return libbpf_err(-EINVAL);
8447 fd = prog->instances.fds[n];
8449 pr_warn("%dth instance of program '%s' is invalid\n",
8451 return libbpf_err(-ENOENT);
8457 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
8462 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8467 static bool bpf_program__is_type(const struct bpf_program *prog,
8468 enum bpf_prog_type type)
8470 return prog ? (prog->type == type) : false;
8473 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
8474 int bpf_program__set_##NAME(struct bpf_program *prog) \
8477 return libbpf_err(-EINVAL); \
8478 bpf_program__set_type(prog, TYPE); \
8482 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
8484 return bpf_program__is_type(prog, TYPE); \
8487 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
8488 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
8489 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
8490 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8491 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
8492 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
8493 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
8494 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8495 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
8496 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
8497 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
8498 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
8499 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
8501 enum bpf_attach_type
8502 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
8504 return prog->expected_attach_type;
8507 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
8508 enum bpf_attach_type type)
8510 prog->expected_attach_type = type;
8513 __u32 bpf_program__flags(const struct bpf_program *prog)
8515 return prog->prog_flags;
8518 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8520 if (prog->obj->loaded)
8521 return libbpf_err(-EBUSY);
8523 prog->prog_flags = flags;
8527 __u32 bpf_program__log_level(const struct bpf_program *prog)
8529 return prog->log_level;
8532 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8534 if (prog->obj->loaded)
8535 return libbpf_err(-EBUSY);
8537 prog->log_level = log_level;
8541 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8543 *log_size = prog->log_size;
8544 return prog->log_buf;
8547 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8549 if (log_size && !log_buf)
8551 if (prog->log_size > UINT_MAX)
8553 if (prog->obj->loaded)
8556 prog->log_buf = log_buf;
8557 prog->log_size = log_size;
8561 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8563 .prog_type = BPF_PROG_TYPE_##ptype, \
8564 .expected_attach_type = atype, \
8565 .cookie = (long)(flags), \
8566 .preload_fn = libbpf_preload_prog, \
8570 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie);
8571 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie);
8572 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie);
8573 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie);
8574 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie);
8575 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie);
8577 static const struct bpf_sec_def section_defs[] = {
8578 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
8579 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8580 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8581 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8582 SEC_DEF("uprobe/", KPROBE, 0, SEC_NONE),
8583 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8584 SEC_DEF("uretprobe/", KPROBE, 0, SEC_NONE),
8585 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
8586 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX),
8587 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8588 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8589 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8590 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8591 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8592 SEC_DEF("raw_tracepoint.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8593 SEC_DEF("raw_tp.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8594 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8595 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8596 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8597 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8598 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8599 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8600 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8601 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8602 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8603 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8604 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8605 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8606 SEC_DEF("xdp_devmap/", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8607 SEC_DEF("xdp_cpumap/", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8608 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8609 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8610 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
8611 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8612 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8613 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
8614 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8615 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8616 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8617 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8618 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8619 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8620 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8621 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8622 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8623 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8624 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8625 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8626 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8627 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8628 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8629 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8630 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8631 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8632 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8633 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8634 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8635 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8636 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8637 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8638 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8639 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8640 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8641 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8642 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8643 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8644 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8645 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8646 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8649 #define MAX_TYPE_NAME_SIZE 32
8651 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8653 const struct bpf_sec_def *sec_def;
8654 enum sec_def_flags sec_flags;
8655 int i, n = ARRAY_SIZE(section_defs), len;
8656 bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME;
8658 for (i = 0; i < n; i++) {
8659 sec_def = §ion_defs[i];
8660 sec_flags = sec_def->cookie;
8661 len = strlen(sec_def->sec);
8663 /* "type/" always has to have proper SEC("type/extras") form */
8664 if (sec_def->sec[len - 1] == '/') {
8665 if (str_has_pfx(sec_name, sec_def->sec))
8670 /* "type+" means it can be either exact SEC("type") or
8671 * well-formed SEC("type/extras") with proper '/' separator
8673 if (sec_def->sec[len - 1] == '+') {
8675 /* not even a prefix */
8676 if (strncmp(sec_name, sec_def->sec, len) != 0)
8678 /* exact match or has '/' separator */
8679 if (sec_name[len] == '\0' || sec_name[len] == '/')
8684 /* SEC_SLOPPY_PFX definitions are allowed to be just prefix
8685 * matches, unless strict section name mode
8686 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
8687 * match has to be exact.
8689 if ((sec_flags & SEC_SLOPPY_PFX) && !strict) {
8690 if (str_has_pfx(sec_name, sec_def->sec))
8695 /* Definitions not marked SEC_SLOPPY_PFX (e.g.,
8696 * SEC("syscall")) are exact matches in both modes.
8698 if (strcmp(sec_name, sec_def->sec) == 0)
8704 static char *libbpf_get_type_names(bool attach_type)
8706 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8714 /* Forge string buf with all available names */
8715 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8716 const struct bpf_sec_def *sec_def = §ion_defs[i];
8719 if (sec_def->preload_fn != libbpf_preload_prog)
8722 if (!(sec_def->cookie & SEC_ATTACHABLE))
8726 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8731 strcat(buf, section_defs[i].sec);
8737 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8738 enum bpf_attach_type *expected_attach_type)
8740 const struct bpf_sec_def *sec_def;
8744 return libbpf_err(-EINVAL);
8746 sec_def = find_sec_def(name);
8748 *prog_type = sec_def->prog_type;
8749 *expected_attach_type = sec_def->expected_attach_type;
8753 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8754 type_names = libbpf_get_type_names(false);
8755 if (type_names != NULL) {
8756 pr_debug("supported section(type) names are:%s\n", type_names);
8760 return libbpf_err(-ESRCH);
8763 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8766 struct bpf_map *map;
8769 for (i = 0; i < obj->nr_maps; i++) {
8770 map = &obj->maps[i];
8771 if (!bpf_map__is_struct_ops(map))
8773 if (map->sec_offset <= offset &&
8774 offset - map->sec_offset < map->def.value_size)
8781 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8782 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8783 Elf64_Shdr *shdr, Elf_Data *data)
8785 const struct btf_member *member;
8786 struct bpf_struct_ops *st_ops;
8787 struct bpf_program *prog;
8788 unsigned int shdr_idx;
8789 const struct btf *btf;
8790 struct bpf_map *map;
8791 unsigned int moff, insn_idx;
8799 nrels = shdr->sh_size / shdr->sh_entsize;
8800 for (i = 0; i < nrels; i++) {
8801 rel = elf_rel_by_idx(data, i);
8803 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8804 return -LIBBPF_ERRNO__FORMAT;
8807 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8809 pr_warn("struct_ops reloc: symbol %zx not found\n",
8810 (size_t)ELF64_R_SYM(rel->r_info));
8811 return -LIBBPF_ERRNO__FORMAT;
8814 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8815 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8817 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8818 (size_t)rel->r_offset);
8822 moff = rel->r_offset - map->sec_offset;
8823 shdr_idx = sym->st_shndx;
8824 st_ops = map->st_ops;
8825 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",
8827 (long long)(rel->r_info >> 32),
8828 (long long)sym->st_value,
8829 shdr_idx, (size_t)rel->r_offset,
8830 map->sec_offset, sym->st_name, name);
8832 if (shdr_idx >= SHN_LORESERVE) {
8833 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8834 map->name, (size_t)rel->r_offset, shdr_idx);
8835 return -LIBBPF_ERRNO__RELOC;
8837 if (sym->st_value % BPF_INSN_SZ) {
8838 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8839 map->name, (unsigned long long)sym->st_value);
8840 return -LIBBPF_ERRNO__FORMAT;
8842 insn_idx = sym->st_value / BPF_INSN_SZ;
8844 member = find_member_by_offset(st_ops->type, moff * 8);
8846 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8850 member_idx = member - btf_members(st_ops->type);
8851 name = btf__name_by_offset(btf, member->name_off);
8853 if (!resolve_func_ptr(btf, member->type, NULL)) {
8854 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8859 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8861 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8862 map->name, shdr_idx, name);
8866 /* prevent the use of BPF prog with invalid type */
8867 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8868 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8869 map->name, prog->name);
8873 /* if we haven't yet processed this BPF program, record proper
8874 * attach_btf_id and member_idx
8876 if (!prog->attach_btf_id) {
8877 prog->attach_btf_id = st_ops->type_id;
8878 prog->expected_attach_type = member_idx;
8881 /* struct_ops BPF prog can be re-used between multiple
8882 * .struct_ops as long as it's the same struct_ops struct
8883 * definition and the same function pointer field
8885 if (prog->attach_btf_id != st_ops->type_id ||
8886 prog->expected_attach_type != member_idx) {
8887 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",
8888 map->name, prog->name, prog->sec_name, prog->type,
8889 prog->attach_btf_id, prog->expected_attach_type, name);
8893 st_ops->progs[member_idx] = prog;
8899 #define BTF_TRACE_PREFIX "btf_trace_"
8900 #define BTF_LSM_PREFIX "bpf_lsm_"
8901 #define BTF_ITER_PREFIX "bpf_iter_"
8902 #define BTF_MAX_NAME_SIZE 128
8904 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8905 const char **prefix, int *kind)
8907 switch (attach_type) {
8908 case BPF_TRACE_RAW_TP:
8909 *prefix = BTF_TRACE_PREFIX;
8910 *kind = BTF_KIND_TYPEDEF;
8913 *prefix = BTF_LSM_PREFIX;
8914 *kind = BTF_KIND_FUNC;
8916 case BPF_TRACE_ITER:
8917 *prefix = BTF_ITER_PREFIX;
8918 *kind = BTF_KIND_FUNC;
8922 *kind = BTF_KIND_FUNC;
8926 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8927 const char *name, __u32 kind)
8929 char btf_type_name[BTF_MAX_NAME_SIZE];
8932 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8933 "%s%s", prefix, name);
8934 /* snprintf returns the number of characters written excluding the
8935 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8936 * indicates truncation.
8938 if (ret < 0 || ret >= sizeof(btf_type_name))
8939 return -ENAMETOOLONG;
8940 return btf__find_by_name_kind(btf, btf_type_name, kind);
8943 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8944 enum bpf_attach_type attach_type)
8949 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8950 return find_btf_by_prefix_kind(btf, prefix, name, kind);
8953 int libbpf_find_vmlinux_btf_id(const char *name,
8954 enum bpf_attach_type attach_type)
8959 btf = btf__load_vmlinux_btf();
8960 err = libbpf_get_error(btf);
8962 pr_warn("vmlinux BTF is not found\n");
8963 return libbpf_err(err);
8966 err = find_attach_btf_id(btf, name, attach_type);
8968 pr_warn("%s is not found in vmlinux BTF\n", name);
8971 return libbpf_err(err);
8974 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8976 struct bpf_prog_info info = {};
8977 __u32 info_len = sizeof(info);
8981 err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
8983 pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
8984 attach_prog_fd, err);
8990 pr_warn("The target program doesn't have BTF\n");
8993 btf = btf__load_from_kernel_by_id(info.btf_id);
8994 err = libbpf_get_error(btf);
8996 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
8999 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9002 pr_warn("%s is not found in prog's BTF\n", name);
9009 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9010 enum bpf_attach_type attach_type,
9011 int *btf_obj_fd, int *btf_type_id)
9015 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9017 *btf_obj_fd = 0; /* vmlinux BTF */
9024 ret = load_module_btfs(obj);
9028 for (i = 0; i < obj->btf_module_cnt; i++) {
9029 const struct module_btf *mod = &obj->btf_modules[i];
9031 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9033 *btf_obj_fd = mod->fd;
9046 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9047 int *btf_obj_fd, int *btf_type_id)
9049 enum bpf_attach_type attach_type = prog->expected_attach_type;
9050 __u32 attach_prog_fd = prog->attach_prog_fd;
9053 /* BPF program's BTF ID */
9054 if (attach_prog_fd) {
9055 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9057 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9058 attach_prog_fd, attach_name, err);
9066 /* kernel/module BTF ID */
9067 if (prog->obj->gen_loader) {
9068 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9072 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9075 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9081 int libbpf_attach_type_by_name(const char *name,
9082 enum bpf_attach_type *attach_type)
9085 const struct bpf_sec_def *sec_def;
9088 return libbpf_err(-EINVAL);
9090 sec_def = find_sec_def(name);
9092 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9093 type_names = libbpf_get_type_names(true);
9094 if (type_names != NULL) {
9095 pr_debug("attachable section(type) names are:%s\n", type_names);
9099 return libbpf_err(-EINVAL);
9102 if (sec_def->preload_fn != libbpf_preload_prog)
9103 return libbpf_err(-EINVAL);
9104 if (!(sec_def->cookie & SEC_ATTACHABLE))
9105 return libbpf_err(-EINVAL);
9107 *attach_type = sec_def->expected_attach_type;
9111 int bpf_map__fd(const struct bpf_map *map)
9113 return map ? map->fd : libbpf_err(-EINVAL);
9116 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9118 return map ? &map->def : libbpf_err_ptr(-EINVAL);
9121 static bool map_uses_real_name(const struct bpf_map *map)
9123 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9124 * their user-visible name differs from kernel-visible name. Users see
9125 * such map's corresponding ELF section name as a map name.
9126 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9127 * maps to know which name has to be returned to the user.
9129 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9131 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9136 const char *bpf_map__name(const struct bpf_map *map)
9141 if (map_uses_real_name(map))
9142 return map->real_name;
9147 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9149 return map->def.type;
9152 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9155 return libbpf_err(-EBUSY);
9156 map->def.type = type;
9160 __u32 bpf_map__map_flags(const struct bpf_map *map)
9162 return map->def.map_flags;
9165 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9168 return libbpf_err(-EBUSY);
9169 map->def.map_flags = flags;
9173 __u64 bpf_map__map_extra(const struct bpf_map *map)
9175 return map->map_extra;
9178 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9181 return libbpf_err(-EBUSY);
9182 map->map_extra = map_extra;
9186 __u32 bpf_map__numa_node(const struct bpf_map *map)
9188 return map->numa_node;
9191 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9194 return libbpf_err(-EBUSY);
9195 map->numa_node = numa_node;
9199 __u32 bpf_map__key_size(const struct bpf_map *map)
9201 return map->def.key_size;
9204 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9207 return libbpf_err(-EBUSY);
9208 map->def.key_size = size;
9212 __u32 bpf_map__value_size(const struct bpf_map *map)
9214 return map->def.value_size;
9217 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9220 return libbpf_err(-EBUSY);
9221 map->def.value_size = size;
9225 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9227 return map ? map->btf_key_type_id : 0;
9230 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9232 return map ? map->btf_value_type_id : 0;
9235 int bpf_map__set_priv(struct bpf_map *map, void *priv,
9236 bpf_map_clear_priv_t clear_priv)
9239 return libbpf_err(-EINVAL);
9242 if (map->clear_priv)
9243 map->clear_priv(map, map->priv);
9247 map->clear_priv = clear_priv;
9251 void *bpf_map__priv(const struct bpf_map *map)
9253 return map ? map->priv : libbpf_err_ptr(-EINVAL);
9256 int bpf_map__set_initial_value(struct bpf_map *map,
9257 const void *data, size_t size)
9259 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9260 size != map->def.value_size || map->fd >= 0)
9261 return libbpf_err(-EINVAL);
9263 memcpy(map->mmaped, data, size);
9267 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9271 *psize = map->def.value_size;
9275 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
9277 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9280 bool bpf_map__is_internal(const struct bpf_map *map)
9282 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9285 __u32 bpf_map__ifindex(const struct bpf_map *map)
9287 return map->map_ifindex;
9290 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9293 return libbpf_err(-EBUSY);
9294 map->map_ifindex = ifindex;
9298 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9300 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9301 pr_warn("error: unsupported map type\n");
9302 return libbpf_err(-EINVAL);
9304 if (map->inner_map_fd != -1) {
9305 pr_warn("error: inner_map_fd already specified\n");
9306 return libbpf_err(-EINVAL);
9308 if (map->inner_map) {
9309 bpf_map__destroy(map->inner_map);
9310 zfree(&map->inner_map);
9312 map->inner_map_fd = fd;
9316 static struct bpf_map *
9317 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9320 struct bpf_map *s, *e;
9322 if (!obj || !obj->maps)
9323 return errno = EINVAL, NULL;
9326 e = obj->maps + obj->nr_maps;
9328 if ((m < s) || (m >= e)) {
9329 pr_warn("error in %s: map handler doesn't belong to object\n",
9331 return errno = EINVAL, NULL;
9334 idx = (m - obj->maps) + i;
9335 if (idx >= obj->nr_maps || idx < 0)
9337 return &obj->maps[idx];
9341 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
9343 return bpf_object__next_map(obj, prev);
9347 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9352 return __bpf_map__iter(prev, obj, 1);
9356 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
9358 return bpf_object__prev_map(obj, next);
9362 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9367 return obj->maps + obj->nr_maps - 1;
9370 return __bpf_map__iter(next, obj, -1);
9374 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9376 struct bpf_map *pos;
9378 bpf_object__for_each_map(pos, obj) {
9379 /* if it's a special internal map name (which always starts
9380 * with dot) then check if that special name matches the
9381 * real map name (ELF section name)
9383 if (name[0] == '.') {
9384 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9388 /* otherwise map name has to be an exact match */
9389 if (map_uses_real_name(pos)) {
9390 if (strcmp(pos->real_name, name) == 0)
9394 if (strcmp(pos->name, name) == 0)
9397 return errno = ENOENT, NULL;
9401 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9403 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9407 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9409 return libbpf_err_ptr(-ENOTSUP);
9412 long libbpf_get_error(const void *ptr)
9414 if (!IS_ERR_OR_NULL(ptr))
9418 errno = -PTR_ERR(ptr);
9420 /* If ptr == NULL, then errno should be already set by the failing
9421 * API, because libbpf never returns NULL on success and it now always
9422 * sets errno on error. So no extra errno handling for ptr == NULL
9428 __attribute__((alias("bpf_prog_load_xattr2")))
9429 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
9430 struct bpf_object **pobj, int *prog_fd);
9432 static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
9433 struct bpf_object **pobj, int *prog_fd)
9435 struct bpf_object_open_attr open_attr = {};
9436 struct bpf_program *prog, *first_prog = NULL;
9437 struct bpf_object *obj;
9438 struct bpf_map *map;
9442 return libbpf_err(-EINVAL);
9444 return libbpf_err(-EINVAL);
9446 open_attr.file = attr->file;
9447 open_attr.prog_type = attr->prog_type;
9449 obj = bpf_object__open_xattr(&open_attr);
9450 err = libbpf_get_error(obj);
9452 return libbpf_err(-ENOENT);
9454 bpf_object__for_each_program(prog, obj) {
9455 enum bpf_attach_type attach_type = attr->expected_attach_type;
9457 * to preserve backwards compatibility, bpf_prog_load treats
9458 * attr->prog_type, if specified, as an override to whatever
9459 * bpf_object__open guessed
9461 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
9462 bpf_program__set_type(prog, attr->prog_type);
9463 bpf_program__set_expected_attach_type(prog,
9466 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
9468 * we haven't guessed from section name and user
9469 * didn't provide a fallback type, too bad...
9471 bpf_object__close(obj);
9472 return libbpf_err(-EINVAL);
9475 prog->prog_ifindex = attr->ifindex;
9476 prog->log_level = attr->log_level;
9477 prog->prog_flags |= attr->prog_flags;
9482 bpf_object__for_each_map(map, obj) {
9483 if (!bpf_map__is_offload_neutral(map))
9484 map->map_ifindex = attr->ifindex;
9488 pr_warn("object file doesn't contain bpf program\n");
9489 bpf_object__close(obj);
9490 return libbpf_err(-ENOENT);
9493 err = bpf_object__load(obj);
9495 bpf_object__close(obj);
9496 return libbpf_err(err);
9500 *prog_fd = bpf_program__fd(first_prog);
9504 COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
9505 int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
9506 struct bpf_object **pobj, int *prog_fd)
9508 struct bpf_prog_load_attr attr;
9510 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9512 attr.prog_type = type;
9513 attr.expected_attach_type = 0;
9515 return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
9519 int (*detach)(struct bpf_link *link);
9520 void (*dealloc)(struct bpf_link *link);
9521 char *pin_path; /* NULL, if not pinned */
9522 int fd; /* hook FD, -1 if not applicable */
9526 /* Replace link's underlying BPF program with the new one */
9527 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9531 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9532 return libbpf_err_errno(ret);
9535 /* Release "ownership" of underlying BPF resource (typically, BPF program
9536 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9537 * link, when destructed through bpf_link__destroy() call won't attempt to
9538 * detach/unregisted that BPF resource. This is useful in situations where,
9539 * say, attached BPF program has to outlive userspace program that attached it
9540 * in the system. Depending on type of BPF program, though, there might be
9541 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9542 * exit of userspace program doesn't trigger automatic detachment and clean up
9543 * inside the kernel.
9545 void bpf_link__disconnect(struct bpf_link *link)
9547 link->disconnected = true;
9550 int bpf_link__destroy(struct bpf_link *link)
9554 if (IS_ERR_OR_NULL(link))
9557 if (!link->disconnected && link->detach)
9558 err = link->detach(link);
9560 free(link->pin_path);
9562 link->dealloc(link);
9566 return libbpf_err(err);
9569 int bpf_link__fd(const struct bpf_link *link)
9574 const char *bpf_link__pin_path(const struct bpf_link *link)
9576 return link->pin_path;
9579 static int bpf_link__detach_fd(struct bpf_link *link)
9581 return libbpf_err_errno(close(link->fd));
9584 struct bpf_link *bpf_link__open(const char *path)
9586 struct bpf_link *link;
9589 fd = bpf_obj_get(path);
9592 pr_warn("failed to open link at %s: %d\n", path, fd);
9593 return libbpf_err_ptr(fd);
9596 link = calloc(1, sizeof(*link));
9599 return libbpf_err_ptr(-ENOMEM);
9601 link->detach = &bpf_link__detach_fd;
9604 link->pin_path = strdup(path);
9605 if (!link->pin_path) {
9606 bpf_link__destroy(link);
9607 return libbpf_err_ptr(-ENOMEM);
9613 int bpf_link__detach(struct bpf_link *link)
9615 return bpf_link_detach(link->fd) ? -errno : 0;
9618 int bpf_link__pin(struct bpf_link *link, const char *path)
9623 return libbpf_err(-EBUSY);
9624 err = make_parent_dir(path);
9626 return libbpf_err(err);
9627 err = check_path(path);
9629 return libbpf_err(err);
9631 link->pin_path = strdup(path);
9632 if (!link->pin_path)
9633 return libbpf_err(-ENOMEM);
9635 if (bpf_obj_pin(link->fd, link->pin_path)) {
9637 zfree(&link->pin_path);
9638 return libbpf_err(err);
9641 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9645 int bpf_link__unpin(struct bpf_link *link)
9649 if (!link->pin_path)
9650 return libbpf_err(-EINVAL);
9652 err = unlink(link->pin_path);
9656 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9657 zfree(&link->pin_path);
9661 struct bpf_link_perf {
9662 struct bpf_link link;
9664 /* legacy kprobe support: keep track of probe identifier and type */
9665 char *legacy_probe_name;
9666 bool legacy_is_kprobe;
9667 bool legacy_is_retprobe;
9670 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9671 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9673 static int bpf_link_perf_detach(struct bpf_link *link)
9675 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9678 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9681 if (perf_link->perf_event_fd != link->fd)
9682 close(perf_link->perf_event_fd);
9685 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9686 if (perf_link->legacy_probe_name) {
9687 if (perf_link->legacy_is_kprobe) {
9688 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9689 perf_link->legacy_is_retprobe);
9691 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9692 perf_link->legacy_is_retprobe);
9699 static void bpf_link_perf_dealloc(struct bpf_link *link)
9701 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9703 free(perf_link->legacy_probe_name);
9707 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9708 const struct bpf_perf_event_opts *opts)
9710 char errmsg[STRERR_BUFSIZE];
9711 struct bpf_link_perf *link;
9712 int prog_fd, link_fd = -1, err;
9714 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9715 return libbpf_err_ptr(-EINVAL);
9718 pr_warn("prog '%s': invalid perf event FD %d\n",
9720 return libbpf_err_ptr(-EINVAL);
9722 prog_fd = bpf_program__fd(prog);
9724 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9726 return libbpf_err_ptr(-EINVAL);
9729 link = calloc(1, sizeof(*link));
9731 return libbpf_err_ptr(-ENOMEM);
9732 link->link.detach = &bpf_link_perf_detach;
9733 link->link.dealloc = &bpf_link_perf_dealloc;
9734 link->perf_event_fd = pfd;
9736 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9737 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9738 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9740 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9743 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9745 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9748 link->link.fd = link_fd;
9750 if (OPTS_GET(opts, bpf_cookie, 0)) {
9751 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9756 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9758 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9759 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9761 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9765 link->link.fd = pfd;
9767 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9769 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9770 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9779 return libbpf_err_ptr(err);
9782 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9784 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9788 * this function is expected to parse integer in the range of [0, 2^31-1] from
9789 * given file using scanf format string fmt. If actual parsed value is
9790 * negative, the result might be indistinguishable from error
9792 static int parse_uint_from_file(const char *file, const char *fmt)
9794 char buf[STRERR_BUFSIZE];
9798 f = fopen(file, "r");
9801 pr_debug("failed to open '%s': %s\n", file,
9802 libbpf_strerror_r(err, buf, sizeof(buf)));
9805 err = fscanf(f, fmt, &ret);
9807 err = err == EOF ? -EIO : -errno;
9808 pr_debug("failed to parse '%s': %s\n", file,
9809 libbpf_strerror_r(err, buf, sizeof(buf)));
9817 static int determine_kprobe_perf_type(void)
9819 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9821 return parse_uint_from_file(file, "%d\n");
9824 static int determine_uprobe_perf_type(void)
9826 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9828 return parse_uint_from_file(file, "%d\n");
9831 static int determine_kprobe_retprobe_bit(void)
9833 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9835 return parse_uint_from_file(file, "config:%d\n");
9838 static int determine_uprobe_retprobe_bit(void)
9840 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9842 return parse_uint_from_file(file, "config:%d\n");
9845 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9846 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9848 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9849 uint64_t offset, int pid, size_t ref_ctr_off)
9851 struct perf_event_attr attr = {};
9852 char errmsg[STRERR_BUFSIZE];
9855 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9858 type = uprobe ? determine_uprobe_perf_type()
9859 : determine_kprobe_perf_type();
9861 pr_warn("failed to determine %s perf type: %s\n",
9862 uprobe ? "uprobe" : "kprobe",
9863 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9867 int bit = uprobe ? determine_uprobe_retprobe_bit()
9868 : determine_kprobe_retprobe_bit();
9871 pr_warn("failed to determine %s retprobe bit: %s\n",
9872 uprobe ? "uprobe" : "kprobe",
9873 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9876 attr.config |= 1 << bit;
9878 attr.size = sizeof(attr);
9880 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9881 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9882 attr.config2 = offset; /* kprobe_addr or probe_offset */
9884 /* pid filter is meaningful only for uprobes */
9885 pfd = syscall(__NR_perf_event_open, &attr,
9886 pid < 0 ? -1 : pid /* pid */,
9887 pid == -1 ? 0 : -1 /* cpu */,
9888 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9891 pr_warn("%s perf_event_open() failed: %s\n",
9892 uprobe ? "uprobe" : "kprobe",
9893 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9899 static int append_to_file(const char *file, const char *fmt, ...)
9904 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9909 n = vdprintf(fd, fmt, ap);
9919 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9920 const char *kfunc_name, size_t offset)
9922 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), kfunc_name, offset);
9925 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9926 const char *kfunc_name, size_t offset)
9928 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9930 return append_to_file(file, "%c:%s/%s %s+0x%zx",
9931 retprobe ? 'r' : 'p',
9932 retprobe ? "kretprobes" : "kprobes",
9933 probe_name, kfunc_name, offset);
9936 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9938 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9940 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
9943 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9947 snprintf(file, sizeof(file),
9948 "/sys/kernel/debug/tracing/events/%s/%s/id",
9949 retprobe ? "kretprobes" : "kprobes", probe_name);
9951 return parse_uint_from_file(file, "%d\n");
9954 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9955 const char *kfunc_name, size_t offset, int pid)
9957 struct perf_event_attr attr = {};
9958 char errmsg[STRERR_BUFSIZE];
9961 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9963 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9965 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9968 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
9970 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9972 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9975 attr.size = sizeof(attr);
9977 attr.type = PERF_TYPE_TRACEPOINT;
9979 pfd = syscall(__NR_perf_event_open, &attr,
9980 pid < 0 ? -1 : pid, /* pid */
9981 pid == -1 ? 0 : -1, /* cpu */
9982 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9985 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
9986 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9993 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
9994 const char *func_name,
9995 const struct bpf_kprobe_opts *opts)
9997 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9998 char errmsg[STRERR_BUFSIZE];
9999 char *legacy_probe = NULL;
10000 struct bpf_link *link;
10002 bool retprobe, legacy;
10005 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10006 return libbpf_err_ptr(-EINVAL);
10008 retprobe = OPTS_GET(opts, retprobe, false);
10009 offset = OPTS_GET(opts, offset, 0);
10010 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10012 legacy = determine_kprobe_perf_type() < 0;
10014 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10016 -1 /* pid */, 0 /* ref_ctr_off */);
10018 char probe_name[256];
10020 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10021 func_name, offset);
10023 legacy_probe = strdup(func_name);
10025 return libbpf_err_ptr(-ENOMEM);
10027 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10028 offset, -1 /* pid */);
10032 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10033 prog->name, retprobe ? "kretprobe" : "kprobe",
10035 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10038 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10039 err = libbpf_get_error(link);
10042 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10043 prog->name, retprobe ? "kretprobe" : "kprobe",
10045 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10049 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10051 perf_link->legacy_probe_name = legacy_probe;
10052 perf_link->legacy_is_kprobe = true;
10053 perf_link->legacy_is_retprobe = retprobe;
10058 free(legacy_probe);
10059 return libbpf_err_ptr(err);
10062 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10064 const char *func_name)
10066 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10067 .retprobe = retprobe,
10070 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10073 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie)
10075 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10076 unsigned long offset = 0;
10077 struct bpf_link *link;
10078 const char *func_name;
10082 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10084 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10086 func_name = prog->sec_name + sizeof("kprobe/") - 1;
10088 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10091 pr_warn("kprobe name is invalid: %s\n", func_name);
10092 return libbpf_err_ptr(err);
10094 if (opts.retprobe && offset != 0) {
10097 pr_warn("kretprobes do not support offset specification\n");
10098 return libbpf_err_ptr(err);
10101 opts.offset = offset;
10102 link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10107 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10108 const char *binary_path, uint64_t offset)
10112 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10114 /* sanitize binary_path in the probe name */
10115 for (i = 0; buf[i]; i++) {
10116 if (!isalnum(buf[i]))
10121 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10122 const char *binary_path, size_t offset)
10124 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10126 return append_to_file(file, "%c:%s/%s %s:0x%zx",
10127 retprobe ? 'r' : 'p',
10128 retprobe ? "uretprobes" : "uprobes",
10129 probe_name, binary_path, offset);
10132 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10134 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10136 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
10139 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10143 snprintf(file, sizeof(file),
10144 "/sys/kernel/debug/tracing/events/%s/%s/id",
10145 retprobe ? "uretprobes" : "uprobes", probe_name);
10147 return parse_uint_from_file(file, "%d\n");
10150 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10151 const char *binary_path, size_t offset, int pid)
10153 struct perf_event_attr attr;
10154 int type, pfd, err;
10156 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10158 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10159 binary_path, (size_t)offset, err);
10162 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10164 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10165 binary_path, offset, err);
10169 memset(&attr, 0, sizeof(attr));
10170 attr.size = sizeof(attr);
10171 attr.config = type;
10172 attr.type = PERF_TYPE_TRACEPOINT;
10174 pfd = syscall(__NR_perf_event_open, &attr,
10175 pid < 0 ? -1 : pid, /* pid */
10176 pid == -1 ? 0 : -1, /* cpu */
10177 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10180 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10186 LIBBPF_API struct bpf_link *
10187 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10188 const char *binary_path, size_t func_offset,
10189 const struct bpf_uprobe_opts *opts)
10191 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10192 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10193 struct bpf_link *link;
10194 size_t ref_ctr_off;
10196 bool retprobe, legacy;
10198 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10199 return libbpf_err_ptr(-EINVAL);
10201 retprobe = OPTS_GET(opts, retprobe, false);
10202 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10203 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10205 legacy = determine_uprobe_perf_type() < 0;
10207 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10208 func_offset, pid, ref_ctr_off);
10210 char probe_name[512];
10213 return libbpf_err_ptr(-EINVAL);
10215 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10216 binary_path, func_offset);
10218 legacy_probe = strdup(probe_name);
10220 return libbpf_err_ptr(-ENOMEM);
10222 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10223 binary_path, func_offset, pid);
10227 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10228 prog->name, retprobe ? "uretprobe" : "uprobe",
10229 binary_path, func_offset,
10230 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10234 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10235 err = libbpf_get_error(link);
10238 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10239 prog->name, retprobe ? "uretprobe" : "uprobe",
10240 binary_path, func_offset,
10241 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10245 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10247 perf_link->legacy_probe_name = legacy_probe;
10248 perf_link->legacy_is_kprobe = false;
10249 perf_link->legacy_is_retprobe = retprobe;
10253 free(legacy_probe);
10254 return libbpf_err_ptr(err);
10258 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
10259 bool retprobe, pid_t pid,
10260 const char *binary_path,
10261 size_t func_offset)
10263 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10265 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10268 static int determine_tracepoint_id(const char *tp_category,
10269 const char *tp_name)
10271 char file[PATH_MAX];
10274 ret = snprintf(file, sizeof(file),
10275 "/sys/kernel/debug/tracing/events/%s/%s/id",
10276 tp_category, tp_name);
10279 if (ret >= sizeof(file)) {
10280 pr_debug("tracepoint %s/%s path is too long\n",
10281 tp_category, tp_name);
10284 return parse_uint_from_file(file, "%d\n");
10287 static int perf_event_open_tracepoint(const char *tp_category,
10288 const char *tp_name)
10290 struct perf_event_attr attr = {};
10291 char errmsg[STRERR_BUFSIZE];
10292 int tp_id, pfd, err;
10294 tp_id = determine_tracepoint_id(tp_category, tp_name);
10296 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
10297 tp_category, tp_name,
10298 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
10302 attr.type = PERF_TYPE_TRACEPOINT;
10303 attr.size = sizeof(attr);
10304 attr.config = tp_id;
10306 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
10307 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10310 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
10311 tp_category, tp_name,
10312 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10318 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
10319 const char *tp_category,
10320 const char *tp_name,
10321 const struct bpf_tracepoint_opts *opts)
10323 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10324 char errmsg[STRERR_BUFSIZE];
10325 struct bpf_link *link;
10328 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
10329 return libbpf_err_ptr(-EINVAL);
10331 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10333 pfd = perf_event_open_tracepoint(tp_category, tp_name);
10335 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
10336 prog->name, tp_category, tp_name,
10337 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10338 return libbpf_err_ptr(pfd);
10340 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10341 err = libbpf_get_error(link);
10344 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
10345 prog->name, tp_category, tp_name,
10346 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10347 return libbpf_err_ptr(err);
10352 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
10353 const char *tp_category,
10354 const char *tp_name)
10356 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
10359 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie)
10361 char *sec_name, *tp_cat, *tp_name;
10362 struct bpf_link *link;
10364 sec_name = strdup(prog->sec_name);
10366 return libbpf_err_ptr(-ENOMEM);
10368 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
10369 if (str_has_pfx(prog->sec_name, "tp/"))
10370 tp_cat = sec_name + sizeof("tp/") - 1;
10372 tp_cat = sec_name + sizeof("tracepoint/") - 1;
10373 tp_name = strchr(tp_cat, '/');
10376 return libbpf_err_ptr(-EINVAL);
10381 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
10386 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
10387 const char *tp_name)
10389 char errmsg[STRERR_BUFSIZE];
10390 struct bpf_link *link;
10393 prog_fd = bpf_program__fd(prog);
10395 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10396 return libbpf_err_ptr(-EINVAL);
10399 link = calloc(1, sizeof(*link));
10401 return libbpf_err_ptr(-ENOMEM);
10402 link->detach = &bpf_link__detach_fd;
10404 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
10408 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
10409 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10410 return libbpf_err_ptr(pfd);
10416 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie)
10418 static const char *const prefixes[] = {
10422 "raw_tracepoint.w/",
10425 const char *tp_name = NULL;
10427 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
10428 if (str_has_pfx(prog->sec_name, prefixes[i])) {
10429 tp_name = prog->sec_name + strlen(prefixes[i]);
10434 pr_warn("prog '%s': invalid section name '%s'\n",
10435 prog->name, prog->sec_name);
10436 return libbpf_err_ptr(-EINVAL);
10439 return bpf_program__attach_raw_tracepoint(prog, tp_name);
10442 /* Common logic for all BPF program types that attach to a btf_id */
10443 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
10445 char errmsg[STRERR_BUFSIZE];
10446 struct bpf_link *link;
10449 prog_fd = bpf_program__fd(prog);
10451 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10452 return libbpf_err_ptr(-EINVAL);
10455 link = calloc(1, sizeof(*link));
10457 return libbpf_err_ptr(-ENOMEM);
10458 link->detach = &bpf_link__detach_fd;
10460 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
10464 pr_warn("prog '%s': failed to attach: %s\n",
10465 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10466 return libbpf_err_ptr(pfd);
10469 return (struct bpf_link *)link;
10472 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
10474 return bpf_program__attach_btf_id(prog);
10477 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
10479 return bpf_program__attach_btf_id(prog);
10482 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie)
10484 return bpf_program__attach_trace(prog);
10487 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie)
10489 return bpf_program__attach_lsm(prog);
10492 static struct bpf_link *
10493 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
10494 const char *target_name)
10496 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
10497 .target_btf_id = btf_id);
10498 enum bpf_attach_type attach_type;
10499 char errmsg[STRERR_BUFSIZE];
10500 struct bpf_link *link;
10501 int prog_fd, link_fd;
10503 prog_fd = bpf_program__fd(prog);
10505 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10506 return libbpf_err_ptr(-EINVAL);
10509 link = calloc(1, sizeof(*link));
10511 return libbpf_err_ptr(-ENOMEM);
10512 link->detach = &bpf_link__detach_fd;
10514 attach_type = bpf_program__get_expected_attach_type(prog);
10515 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
10519 pr_warn("prog '%s': failed to attach to %s: %s\n",
10520 prog->name, target_name,
10521 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10522 return libbpf_err_ptr(link_fd);
10524 link->fd = link_fd;
10529 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
10531 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
10535 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
10537 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
10540 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
10542 /* target_fd/target_ifindex use the same field in LINK_CREATE */
10543 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
10546 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
10548 const char *attach_func_name)
10552 if (!!target_fd != !!attach_func_name) {
10553 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
10555 return libbpf_err_ptr(-EINVAL);
10558 if (prog->type != BPF_PROG_TYPE_EXT) {
10559 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
10561 return libbpf_err_ptr(-EINVAL);
10565 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
10567 return libbpf_err_ptr(btf_id);
10569 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
10571 /* no target, so use raw_tracepoint_open for compatibility
10574 return bpf_program__attach_trace(prog);
10579 bpf_program__attach_iter(const struct bpf_program *prog,
10580 const struct bpf_iter_attach_opts *opts)
10582 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
10583 char errmsg[STRERR_BUFSIZE];
10584 struct bpf_link *link;
10585 int prog_fd, link_fd;
10586 __u32 target_fd = 0;
10588 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
10589 return libbpf_err_ptr(-EINVAL);
10591 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
10592 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
10594 prog_fd = bpf_program__fd(prog);
10596 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10597 return libbpf_err_ptr(-EINVAL);
10600 link = calloc(1, sizeof(*link));
10602 return libbpf_err_ptr(-ENOMEM);
10603 link->detach = &bpf_link__detach_fd;
10605 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
10606 &link_create_opts);
10610 pr_warn("prog '%s': failed to attach to iterator: %s\n",
10611 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10612 return libbpf_err_ptr(link_fd);
10614 link->fd = link_fd;
10618 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)
10620 return bpf_program__attach_iter(prog, NULL);
10623 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
10625 if (!prog->sec_def || !prog->sec_def->attach_fn)
10626 return libbpf_err_ptr(-ESRCH);
10628 return prog->sec_def->attach_fn(prog, prog->sec_def->cookie);
10631 static int bpf_link__detach_struct_ops(struct bpf_link *link)
10635 if (bpf_map_delete_elem(link->fd, &zero))
10641 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
10643 struct bpf_struct_ops *st_ops;
10644 struct bpf_link *link;
10648 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
10649 return libbpf_err_ptr(-EINVAL);
10651 link = calloc(1, sizeof(*link));
10653 return libbpf_err_ptr(-EINVAL);
10655 st_ops = map->st_ops;
10656 for (i = 0; i < btf_vlen(st_ops->type); i++) {
10657 struct bpf_program *prog = st_ops->progs[i];
10664 prog_fd = bpf_program__fd(prog);
10665 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10666 *(unsigned long *)kern_data = prog_fd;
10669 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10673 return libbpf_err_ptr(err);
10676 link->detach = bpf_link__detach_struct_ops;
10677 link->fd = map->fd;
10682 enum bpf_perf_event_ret
10683 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10684 void **copy_mem, size_t *copy_size,
10685 bpf_perf_event_print_t fn, void *private_data)
10687 struct perf_event_mmap_page *header = mmap_mem;
10688 __u64 data_head = ring_buffer_read_head(header);
10689 __u64 data_tail = header->data_tail;
10690 void *base = ((__u8 *)header) + page_size;
10691 int ret = LIBBPF_PERF_EVENT_CONT;
10692 struct perf_event_header *ehdr;
10695 while (data_head != data_tail) {
10696 ehdr = base + (data_tail & (mmap_size - 1));
10697 ehdr_size = ehdr->size;
10699 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10700 void *copy_start = ehdr;
10701 size_t len_first = base + mmap_size - copy_start;
10702 size_t len_secnd = ehdr_size - len_first;
10704 if (*copy_size < ehdr_size) {
10706 *copy_mem = malloc(ehdr_size);
10709 ret = LIBBPF_PERF_EVENT_ERROR;
10712 *copy_size = ehdr_size;
10715 memcpy(*copy_mem, copy_start, len_first);
10716 memcpy(*copy_mem + len_first, base, len_secnd);
10720 ret = fn(ehdr, private_data);
10721 data_tail += ehdr_size;
10722 if (ret != LIBBPF_PERF_EVENT_CONT)
10726 ring_buffer_write_tail(header, data_tail);
10727 return libbpf_err(ret);
10730 struct perf_buffer;
10732 struct perf_buffer_params {
10733 struct perf_event_attr *attr;
10734 /* if event_cb is specified, it takes precendence */
10735 perf_buffer_event_fn event_cb;
10736 /* sample_cb and lost_cb are higher-level common-case callbacks */
10737 perf_buffer_sample_fn sample_cb;
10738 perf_buffer_lost_fn lost_cb;
10745 struct perf_cpu_buf {
10746 struct perf_buffer *pb;
10747 void *base; /* mmap()'ed memory */
10748 void *buf; /* for reconstructing segmented data */
10755 struct perf_buffer {
10756 perf_buffer_event_fn event_cb;
10757 perf_buffer_sample_fn sample_cb;
10758 perf_buffer_lost_fn lost_cb;
10759 void *ctx; /* passed into callbacks */
10763 struct perf_cpu_buf **cpu_bufs;
10764 struct epoll_event *events;
10765 int cpu_cnt; /* number of allocated CPU buffers */
10766 int epoll_fd; /* perf event FD */
10767 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10770 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10771 struct perf_cpu_buf *cpu_buf)
10775 if (cpu_buf->base &&
10776 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
10777 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
10778 if (cpu_buf->fd >= 0) {
10779 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10780 close(cpu_buf->fd);
10782 free(cpu_buf->buf);
10786 void perf_buffer__free(struct perf_buffer *pb)
10790 if (IS_ERR_OR_NULL(pb))
10792 if (pb->cpu_bufs) {
10793 for (i = 0; i < pb->cpu_cnt; i++) {
10794 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10799 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10800 perf_buffer__free_cpu_buf(pb, cpu_buf);
10802 free(pb->cpu_bufs);
10804 if (pb->epoll_fd >= 0)
10805 close(pb->epoll_fd);
10810 static struct perf_cpu_buf *
10811 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10812 int cpu, int map_key)
10814 struct perf_cpu_buf *cpu_buf;
10815 char msg[STRERR_BUFSIZE];
10818 cpu_buf = calloc(1, sizeof(*cpu_buf));
10820 return ERR_PTR(-ENOMEM);
10823 cpu_buf->cpu = cpu;
10824 cpu_buf->map_key = map_key;
10826 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10827 -1, PERF_FLAG_FD_CLOEXEC);
10828 if (cpu_buf->fd < 0) {
10830 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10831 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10835 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10836 PROT_READ | PROT_WRITE, MAP_SHARED,
10838 if (cpu_buf->base == MAP_FAILED) {
10839 cpu_buf->base = NULL;
10841 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
10842 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10846 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10848 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
10849 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10856 perf_buffer__free_cpu_buf(pb, cpu_buf);
10857 return (struct perf_cpu_buf *)ERR_PTR(err);
10860 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10861 struct perf_buffer_params *p);
10863 DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
10864 struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
10865 perf_buffer_sample_fn sample_cb,
10866 perf_buffer_lost_fn lost_cb,
10868 const struct perf_buffer_opts *opts)
10870 struct perf_buffer_params p = {};
10871 struct perf_event_attr attr = {};
10873 if (!OPTS_VALID(opts, perf_buffer_opts))
10874 return libbpf_err_ptr(-EINVAL);
10876 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
10877 attr.type = PERF_TYPE_SOFTWARE;
10878 attr.sample_type = PERF_SAMPLE_RAW;
10879 attr.sample_period = 1;
10880 attr.wakeup_events = 1;
10883 p.sample_cb = sample_cb;
10884 p.lost_cb = lost_cb;
10887 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10890 COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
10891 struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
10892 const struct perf_buffer_opts *opts)
10894 return perf_buffer__new_v0_6_0(map_fd, page_cnt,
10895 opts ? opts->sample_cb : NULL,
10896 opts ? opts->lost_cb : NULL,
10897 opts ? opts->ctx : NULL,
10901 DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
10902 struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
10903 struct perf_event_attr *attr,
10904 perf_buffer_event_fn event_cb, void *ctx,
10905 const struct perf_buffer_raw_opts *opts)
10907 struct perf_buffer_params p = {};
10909 if (page_cnt == 0 || !attr)
10910 return libbpf_err_ptr(-EINVAL);
10912 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
10913 return libbpf_err_ptr(-EINVAL);
10916 p.event_cb = event_cb;
10918 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
10919 p.cpus = OPTS_GET(opts, cpus, NULL);
10920 p.map_keys = OPTS_GET(opts, map_keys, NULL);
10922 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10925 COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
10926 struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
10927 const struct perf_buffer_raw_opts *opts)
10929 LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
10930 .cpu_cnt = opts->cpu_cnt,
10931 .cpus = opts->cpus,
10932 .map_keys = opts->map_keys,
10935 return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
10936 opts->event_cb, opts->ctx, &inner_opts);
10939 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10940 struct perf_buffer_params *p)
10942 const char *online_cpus_file = "/sys/devices/system/cpu/online";
10943 struct bpf_map_info map;
10944 char msg[STRERR_BUFSIZE];
10945 struct perf_buffer *pb;
10946 bool *online = NULL;
10947 __u32 map_info_len;
10950 if (page_cnt & (page_cnt - 1)) {
10951 pr_warn("page count should be power of two, but is %zu\n",
10953 return ERR_PTR(-EINVAL);
10956 /* best-effort sanity checks */
10957 memset(&map, 0, sizeof(map));
10958 map_info_len = sizeof(map);
10959 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
10962 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
10963 * -EBADFD, -EFAULT, or -E2BIG on real error
10965 if (err != -EINVAL) {
10966 pr_warn("failed to get map info for map FD %d: %s\n",
10967 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
10968 return ERR_PTR(err);
10970 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
10973 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
10974 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
10976 return ERR_PTR(-EINVAL);
10980 pb = calloc(1, sizeof(*pb));
10982 return ERR_PTR(-ENOMEM);
10984 pb->event_cb = p->event_cb;
10985 pb->sample_cb = p->sample_cb;
10986 pb->lost_cb = p->lost_cb;
10989 pb->page_size = getpagesize();
10990 pb->mmap_size = pb->page_size * page_cnt;
10991 pb->map_fd = map_fd;
10993 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
10994 if (pb->epoll_fd < 0) {
10996 pr_warn("failed to create epoll instance: %s\n",
10997 libbpf_strerror_r(err, msg, sizeof(msg)));
11001 if (p->cpu_cnt > 0) {
11002 pb->cpu_cnt = p->cpu_cnt;
11004 pb->cpu_cnt = libbpf_num_possible_cpus();
11005 if (pb->cpu_cnt < 0) {
11009 if (map.max_entries && map.max_entries < pb->cpu_cnt)
11010 pb->cpu_cnt = map.max_entries;
11013 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11016 pr_warn("failed to allocate events: out of memory\n");
11019 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11020 if (!pb->cpu_bufs) {
11022 pr_warn("failed to allocate buffers: out of memory\n");
11026 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11028 pr_warn("failed to get online CPU mask: %d\n", err);
11032 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11033 struct perf_cpu_buf *cpu_buf;
11036 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11037 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11039 /* in case user didn't explicitly requested particular CPUs to
11040 * be attached to, skip offline/not present CPUs
11042 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11045 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11046 if (IS_ERR(cpu_buf)) {
11047 err = PTR_ERR(cpu_buf);
11051 pb->cpu_bufs[j] = cpu_buf;
11053 err = bpf_map_update_elem(pb->map_fd, &map_key,
11057 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11058 cpu, map_key, cpu_buf->fd,
11059 libbpf_strerror_r(err, msg, sizeof(msg)));
11063 pb->events[j].events = EPOLLIN;
11064 pb->events[j].data.ptr = cpu_buf;
11065 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11066 &pb->events[j]) < 0) {
11068 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11070 libbpf_strerror_r(err, msg, sizeof(msg)));
11083 perf_buffer__free(pb);
11084 return ERR_PTR(err);
11087 struct perf_sample_raw {
11088 struct perf_event_header header;
11093 struct perf_sample_lost {
11094 struct perf_event_header header;
11097 uint64_t sample_id;
11100 static enum bpf_perf_event_ret
11101 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11103 struct perf_cpu_buf *cpu_buf = ctx;
11104 struct perf_buffer *pb = cpu_buf->pb;
11107 /* user wants full control over parsing perf event */
11109 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11112 case PERF_RECORD_SAMPLE: {
11113 struct perf_sample_raw *s = data;
11116 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11119 case PERF_RECORD_LOST: {
11120 struct perf_sample_lost *s = data;
11123 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11127 pr_warn("unknown perf sample type %d\n", e->type);
11128 return LIBBPF_PERF_EVENT_ERROR;
11130 return LIBBPF_PERF_EVENT_CONT;
11133 static int perf_buffer__process_records(struct perf_buffer *pb,
11134 struct perf_cpu_buf *cpu_buf)
11136 enum bpf_perf_event_ret ret;
11138 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11139 pb->page_size, &cpu_buf->buf,
11140 &cpu_buf->buf_size,
11141 perf_buffer__process_record, cpu_buf);
11142 if (ret != LIBBPF_PERF_EVENT_CONT)
11147 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11149 return pb->epoll_fd;
11152 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11156 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11160 for (i = 0; i < cnt; i++) {
11161 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11163 err = perf_buffer__process_records(pb, cpu_buf);
11165 pr_warn("error while processing records: %d\n", err);
11166 return libbpf_err(err);
11172 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11175 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11177 return pb->cpu_cnt;
11181 * Return perf_event FD of a ring buffer in *buf_idx* slot of
11182 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11183 * select()/poll()/epoll() Linux syscalls.
11185 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11187 struct perf_cpu_buf *cpu_buf;
11189 if (buf_idx >= pb->cpu_cnt)
11190 return libbpf_err(-EINVAL);
11192 cpu_buf = pb->cpu_bufs[buf_idx];
11194 return libbpf_err(-ENOENT);
11196 return cpu_buf->fd;
11200 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11201 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11202 * consume, do nothing and return success.
11207 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11209 struct perf_cpu_buf *cpu_buf;
11211 if (buf_idx >= pb->cpu_cnt)
11212 return libbpf_err(-EINVAL);
11214 cpu_buf = pb->cpu_bufs[buf_idx];
11216 return libbpf_err(-ENOENT);
11218 return perf_buffer__process_records(pb, cpu_buf);
11221 int perf_buffer__consume(struct perf_buffer *pb)
11225 for (i = 0; i < pb->cpu_cnt; i++) {
11226 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11231 err = perf_buffer__process_records(pb, cpu_buf);
11233 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
11234 return libbpf_err(err);
11240 struct bpf_prog_info_array_desc {
11241 int array_offset; /* e.g. offset of jited_prog_insns */
11242 int count_offset; /* e.g. offset of jited_prog_len */
11243 int size_offset; /* > 0: offset of rec size,
11244 * < 0: fix size of -size_offset
11248 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
11249 [BPF_PROG_INFO_JITED_INSNS] = {
11250 offsetof(struct bpf_prog_info, jited_prog_insns),
11251 offsetof(struct bpf_prog_info, jited_prog_len),
11254 [BPF_PROG_INFO_XLATED_INSNS] = {
11255 offsetof(struct bpf_prog_info, xlated_prog_insns),
11256 offsetof(struct bpf_prog_info, xlated_prog_len),
11259 [BPF_PROG_INFO_MAP_IDS] = {
11260 offsetof(struct bpf_prog_info, map_ids),
11261 offsetof(struct bpf_prog_info, nr_map_ids),
11262 -(int)sizeof(__u32),
11264 [BPF_PROG_INFO_JITED_KSYMS] = {
11265 offsetof(struct bpf_prog_info, jited_ksyms),
11266 offsetof(struct bpf_prog_info, nr_jited_ksyms),
11267 -(int)sizeof(__u64),
11269 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
11270 offsetof(struct bpf_prog_info, jited_func_lens),
11271 offsetof(struct bpf_prog_info, nr_jited_func_lens),
11272 -(int)sizeof(__u32),
11274 [BPF_PROG_INFO_FUNC_INFO] = {
11275 offsetof(struct bpf_prog_info, func_info),
11276 offsetof(struct bpf_prog_info, nr_func_info),
11277 offsetof(struct bpf_prog_info, func_info_rec_size),
11279 [BPF_PROG_INFO_LINE_INFO] = {
11280 offsetof(struct bpf_prog_info, line_info),
11281 offsetof(struct bpf_prog_info, nr_line_info),
11282 offsetof(struct bpf_prog_info, line_info_rec_size),
11284 [BPF_PROG_INFO_JITED_LINE_INFO] = {
11285 offsetof(struct bpf_prog_info, jited_line_info),
11286 offsetof(struct bpf_prog_info, nr_jited_line_info),
11287 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
11289 [BPF_PROG_INFO_PROG_TAGS] = {
11290 offsetof(struct bpf_prog_info, prog_tags),
11291 offsetof(struct bpf_prog_info, nr_prog_tags),
11292 -(int)sizeof(__u8) * BPF_TAG_SIZE,
11297 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
11300 __u32 *array = (__u32 *)info;
11303 return array[offset / sizeof(__u32)];
11304 return -(int)offset;
11307 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
11310 __u64 *array = (__u64 *)info;
11313 return array[offset / sizeof(__u64)];
11314 return -(int)offset;
11317 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
11320 __u32 *array = (__u32 *)info;
11323 array[offset / sizeof(__u32)] = val;
11326 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
11329 __u64 *array = (__u64 *)info;
11332 array[offset / sizeof(__u64)] = val;
11335 struct bpf_prog_info_linear *
11336 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
11338 struct bpf_prog_info_linear *info_linear;
11339 struct bpf_prog_info info = {};
11340 __u32 info_len = sizeof(info);
11341 __u32 data_len = 0;
11345 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
11346 return libbpf_err_ptr(-EINVAL);
11348 /* step 1: get array dimensions */
11349 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
11351 pr_debug("can't get prog info: %s", strerror(errno));
11352 return libbpf_err_ptr(-EFAULT);
11355 /* step 2: calculate total size of all arrays */
11356 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11357 bool include_array = (arrays & (1UL << i)) > 0;
11358 struct bpf_prog_info_array_desc *desc;
11361 desc = bpf_prog_info_array_desc + i;
11363 /* kernel is too old to support this field */
11364 if (info_len < desc->array_offset + sizeof(__u32) ||
11365 info_len < desc->count_offset + sizeof(__u32) ||
11366 (desc->size_offset > 0 && info_len < desc->size_offset))
11367 include_array = false;
11369 if (!include_array) {
11370 arrays &= ~(1UL << i); /* clear the bit */
11374 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11375 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11377 data_len += count * size;
11380 /* step 3: allocate continuous memory */
11381 data_len = roundup(data_len, sizeof(__u64));
11382 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
11384 return libbpf_err_ptr(-ENOMEM);
11386 /* step 4: fill data to info_linear->info */
11387 info_linear->arrays = arrays;
11388 memset(&info_linear->info, 0, sizeof(info));
11389 ptr = info_linear->data;
11391 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11392 struct bpf_prog_info_array_desc *desc;
11395 if ((arrays & (1UL << i)) == 0)
11398 desc = bpf_prog_info_array_desc + i;
11399 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11400 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11401 bpf_prog_info_set_offset_u32(&info_linear->info,
11402 desc->count_offset, count);
11403 bpf_prog_info_set_offset_u32(&info_linear->info,
11404 desc->size_offset, size);
11405 bpf_prog_info_set_offset_u64(&info_linear->info,
11406 desc->array_offset,
11408 ptr += count * size;
11411 /* step 5: call syscall again to get required arrays */
11412 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
11414 pr_debug("can't get prog info: %s", strerror(errno));
11416 return libbpf_err_ptr(-EFAULT);
11419 /* step 6: verify the data */
11420 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11421 struct bpf_prog_info_array_desc *desc;
11424 if ((arrays & (1UL << i)) == 0)
11427 desc = bpf_prog_info_array_desc + i;
11428 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11429 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11430 desc->count_offset);
11432 pr_warn("%s: mismatch in element count\n", __func__);
11434 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11435 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11436 desc->size_offset);
11438 pr_warn("%s: mismatch in rec size\n", __func__);
11441 /* step 7: update info_len and data_len */
11442 info_linear->info_len = sizeof(struct bpf_prog_info);
11443 info_linear->data_len = data_len;
11445 return info_linear;
11448 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
11452 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11453 struct bpf_prog_info_array_desc *desc;
11456 if ((info_linear->arrays & (1UL << i)) == 0)
11459 desc = bpf_prog_info_array_desc + i;
11460 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
11461 desc->array_offset);
11462 offs = addr - ptr_to_u64(info_linear->data);
11463 bpf_prog_info_set_offset_u64(&info_linear->info,
11464 desc->array_offset, offs);
11468 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
11472 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11473 struct bpf_prog_info_array_desc *desc;
11476 if ((info_linear->arrays & (1UL << i)) == 0)
11479 desc = bpf_prog_info_array_desc + i;
11480 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
11481 desc->array_offset);
11482 addr = offs + ptr_to_u64(info_linear->data);
11483 bpf_prog_info_set_offset_u64(&info_linear->info,
11484 desc->array_offset, addr);
11488 int bpf_program__set_attach_target(struct bpf_program *prog,
11489 int attach_prog_fd,
11490 const char *attach_func_name)
11492 int btf_obj_fd = 0, btf_id = 0, err;
11494 if (!prog || attach_prog_fd < 0)
11495 return libbpf_err(-EINVAL);
11497 if (prog->obj->loaded)
11498 return libbpf_err(-EINVAL);
11500 if (attach_prog_fd && !attach_func_name) {
11501 /* remember attach_prog_fd and let bpf_program__load() find
11502 * BTF ID during the program load
11504 prog->attach_prog_fd = attach_prog_fd;
11508 if (attach_prog_fd) {
11509 btf_id = libbpf_find_prog_btf_id(attach_func_name,
11512 return libbpf_err(btf_id);
11514 if (!attach_func_name)
11515 return libbpf_err(-EINVAL);
11517 /* load btf_vmlinux, if not yet */
11518 err = bpf_object__load_vmlinux_btf(prog->obj, true);
11520 return libbpf_err(err);
11521 err = find_kernel_btf_id(prog->obj, attach_func_name,
11522 prog->expected_attach_type,
11523 &btf_obj_fd, &btf_id);
11525 return libbpf_err(err);
11528 prog->attach_btf_id = btf_id;
11529 prog->attach_btf_obj_fd = btf_obj_fd;
11530 prog->attach_prog_fd = attach_prog_fd;
11534 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
11536 int err = 0, n, len, start, end = -1;
11542 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
11544 if (*s == ',' || *s == '\n') {
11548 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
11549 if (n <= 0 || n > 2) {
11550 pr_warn("Failed to get CPU range %s: %d\n", s, n);
11553 } else if (n == 1) {
11556 if (start < 0 || start > end) {
11557 pr_warn("Invalid CPU range [%d,%d] in %s\n",
11562 tmp = realloc(*mask, end + 1);
11568 memset(tmp + *mask_sz, 0, start - *mask_sz);
11569 memset(tmp + start, 1, end - start + 1);
11570 *mask_sz = end + 1;
11574 pr_warn("Empty CPU range\n");
11584 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
11586 int fd, err = 0, len;
11589 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
11592 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
11595 len = read(fd, buf, sizeof(buf));
11598 err = len ? -errno : -EINVAL;
11599 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
11602 if (len >= sizeof(buf)) {
11603 pr_warn("CPU mask is too big in file %s\n", fcpu);
11608 return parse_cpu_mask_str(buf, mask, mask_sz);
11611 int libbpf_num_possible_cpus(void)
11613 static const char *fcpu = "/sys/devices/system/cpu/possible";
11615 int err, n, i, tmp_cpus;
11618 tmp_cpus = READ_ONCE(cpus);
11622 err = parse_cpu_mask_file(fcpu, &mask, &n);
11624 return libbpf_err(err);
11627 for (i = 0; i < n; i++) {
11633 WRITE_ONCE(cpus, tmp_cpus);
11637 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
11638 const struct bpf_object_open_opts *opts)
11640 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
11641 .object_name = s->name,
11643 struct bpf_object *obj;
11646 /* Attempt to preserve opts->object_name, unless overriden by user
11647 * explicitly. Overwriting object name for skeletons is discouraged,
11648 * as it breaks global data maps, because they contain object name
11649 * prefix as their own map name prefix. When skeleton is generated,
11650 * bpftool is making an assumption that this name will stay the same.
11653 memcpy(&skel_opts, opts, sizeof(*opts));
11654 if (!opts->object_name)
11655 skel_opts.object_name = s->name;
11658 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
11659 err = libbpf_get_error(obj);
11661 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
11663 return libbpf_err(err);
11668 for (i = 0; i < s->map_cnt; i++) {
11669 struct bpf_map **map = s->maps[i].map;
11670 const char *name = s->maps[i].name;
11671 void **mmaped = s->maps[i].mmaped;
11673 *map = bpf_object__find_map_by_name(obj, name);
11675 pr_warn("failed to find skeleton map '%s'\n", name);
11676 return libbpf_err(-ESRCH);
11679 /* externs shouldn't be pre-setup from user code */
11680 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
11681 *mmaped = (*map)->mmaped;
11684 for (i = 0; i < s->prog_cnt; i++) {
11685 struct bpf_program **prog = s->progs[i].prog;
11686 const char *name = s->progs[i].name;
11688 *prog = bpf_object__find_program_by_name(obj, name);
11690 pr_warn("failed to find skeleton program '%s'\n", name);
11691 return libbpf_err(-ESRCH);
11698 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11702 err = bpf_object__load(*s->obj);
11704 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
11705 return libbpf_err(err);
11708 for (i = 0; i < s->map_cnt; i++) {
11709 struct bpf_map *map = *s->maps[i].map;
11710 size_t mmap_sz = bpf_map_mmap_sz(map);
11711 int prot, map_fd = bpf_map__fd(map);
11712 void **mmaped = s->maps[i].mmaped;
11717 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11722 if (map->def.map_flags & BPF_F_RDONLY_PROG)
11725 prot = PROT_READ | PROT_WRITE;
11727 /* Remap anonymous mmap()-ed "map initialization image" as
11728 * a BPF map-backed mmap()-ed memory, but preserving the same
11729 * memory address. This will cause kernel to change process'
11730 * page table to point to a different piece of kernel memory,
11731 * but from userspace point of view memory address (and its
11732 * contents, being identical at this point) will stay the
11733 * same. This mapping will be released by bpf_object__close()
11734 * as per normal clean up procedure, so we don't need to worry
11735 * about it from skeleton's clean up perspective.
11737 *mmaped = mmap(map->mmaped, mmap_sz, prot,
11738 MAP_SHARED | MAP_FIXED, map_fd, 0);
11739 if (*mmaped == MAP_FAILED) {
11742 pr_warn("failed to re-mmap() map '%s': %d\n",
11743 bpf_map__name(map), err);
11744 return libbpf_err(err);
11751 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11755 for (i = 0; i < s->prog_cnt; i++) {
11756 struct bpf_program *prog = *s->progs[i].prog;
11757 struct bpf_link **link = s->progs[i].link;
11762 /* auto-attaching not supported for this program */
11763 if (!prog->sec_def || !prog->sec_def->attach_fn)
11766 *link = bpf_program__attach(prog);
11767 err = libbpf_get_error(*link);
11769 pr_warn("failed to auto-attach program '%s': %d\n",
11770 bpf_program__name(prog), err);
11771 return libbpf_err(err);
11778 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11782 for (i = 0; i < s->prog_cnt; i++) {
11783 struct bpf_link **link = s->progs[i].link;
11785 bpf_link__destroy(*link);
11790 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11793 bpf_object__detach_skeleton(s);
11795 bpf_object__close(*s->obj);