1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/list.h>
35 #include <linux/limits.h>
36 #include <linux/perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <linux/version.h>
39 #include <sys/epoll.h>
40 #include <sys/ioctl.h>
43 #include <sys/types.h>
45 #include <sys/utsname.h>
46 #include <sys/resource.h>
54 #include "str_error.h"
55 #include "libbpf_internal.h"
57 #include "bpf_gen_internal.h"
60 #define BPF_FS_MAGIC 0xcafe4a11
63 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66 * compilation if user enables corresponding warning. Disable it explicitly.
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
70 #define __printf(a, b) __attribute__((format(printf, a, b)))
72 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
73 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
75 static int __base_pr(enum libbpf_print_level level, const char *format,
78 if (level == LIBBPF_DEBUG)
81 return vfprintf(stderr, format, args);
84 static libbpf_print_fn_t __libbpf_pr = __base_pr;
86 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
88 libbpf_print_fn_t old_print_fn = __libbpf_pr;
95 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
102 va_start(args, format);
103 __libbpf_pr(level, format, args);
107 static void pr_perm_msg(int err)
112 if (err != -EPERM || geteuid() != 0)
115 err = getrlimit(RLIMIT_MEMLOCK, &limit);
119 if (limit.rlim_cur == RLIM_INFINITY)
122 if (limit.rlim_cur < 1024)
123 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
124 else if (limit.rlim_cur < 1024*1024)
125 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
127 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
129 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
133 #define STRERR_BUFSIZE 128
135 /* Copied from tools/perf/util/util.h */
137 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
141 # define zclose(fd) ({ \
144 ___err = close((fd)); \
149 static inline __u64 ptr_to_u64(const void *ptr)
151 return (__u64) (unsigned long) ptr;
154 /* this goes away in libbpf 1.0 */
155 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
157 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
159 /* __LIBBPF_STRICT_LAST is the last power-of-2 value used + 1, so to
160 * get all possible values we compensate last +1, and then (2*x - 1)
161 * to get the bit mask
163 if (mode != LIBBPF_STRICT_ALL
164 && (mode & ~((__LIBBPF_STRICT_LAST - 1) * 2 - 1)))
165 return errno = EINVAL, -EINVAL;
171 enum kern_feature_id {
172 /* v4.14: kernel support for program & map names. */
174 /* v5.2: kernel support for global data sections. */
178 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
180 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
182 /* BTF_FUNC_GLOBAL is supported */
183 FEAT_BTF_GLOBAL_FUNC,
184 /* BPF_F_MMAPABLE is supported for arrays */
186 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
187 FEAT_EXP_ATTACH_TYPE,
188 /* bpf_probe_read_{kernel,user}[_str] helpers */
189 FEAT_PROBE_READ_KERN,
190 /* BPF_PROG_BIND_MAP is supported */
192 /* Kernel support for module BTFs */
194 /* BTF_KIND_FLOAT support */
196 /* BPF perf link support */
198 /* BTF_KIND_TAG support */
203 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
215 enum reloc_type type;
223 typedef int (*init_fn_t)(struct bpf_program *prog, long cookie);
224 typedef int (*preload_fn_t)(struct bpf_program *prog, struct bpf_prog_load_params *attr, long cookie);
225 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_program *prog, long cookie);
227 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
230 /* expected_attach_type is optional, if kernel doesn't support that */
231 SEC_EXP_ATTACH_OPT = 1,
232 /* legacy, only used by libbpf_get_type_names() and
233 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
234 * This used to be associated with cgroup (and few other) BPF programs
235 * that were attachable through BPF_PROG_ATTACH command. Pretty
236 * meaningless nowadays, though.
239 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
240 /* attachment target is specified through BTF ID in either kernel or
241 * other BPF program's BTF object */
243 /* BPF program type allows sleeping/blocking in kernel */
249 enum bpf_prog_type prog_type;
250 enum bpf_attach_type expected_attach_type;
254 preload_fn_t preload_fn;
255 attach_fn_t attach_fn;
259 * bpf_prog should be a better name but it has been used in
263 const struct bpf_sec_def *sec_def;
266 /* this program's instruction offset (in number of instructions)
267 * within its containing ELF section
270 /* number of original instructions in ELF section belonging to this
271 * program, not taking into account subprogram instructions possible
272 * appended later during relocation
275 /* Offset (in number of instructions) of the start of instruction
276 * belonging to this BPF program within its containing main BPF
277 * program. For the entry-point (main) BPF program, this is always
278 * zero. For a sub-program, this gets reset before each of main BPF
279 * programs are processed and relocated and is used to determined
280 * whether sub-program was already appended to the main program, and
281 * if yes, at which instruction offset.
286 /* sec_name with / replaced by _; makes recursive pinning
287 * in bpf_object__pin_programs easier
291 /* instructions that belong to BPF program; insns[0] is located at
292 * sec_insn_off instruction within its ELF section in ELF file, so
293 * when mapping ELF file instruction index to the local instruction,
294 * one needs to subtract sec_insn_off; and vice versa.
296 struct bpf_insn *insns;
297 /* actual number of instruction in this BPF program's image; for
298 * entry-point BPF programs this includes the size of main program
299 * itself plus all the used sub-programs, appended at the end
303 struct reloc_desc *reloc_desc;
311 bpf_program_prep_t preprocessor;
313 struct bpf_object *obj;
315 bpf_program_clear_priv_t clear_priv;
318 bool mark_btf_static;
319 enum bpf_prog_type type;
320 enum bpf_attach_type expected_attach_type;
322 __u32 attach_btf_obj_fd;
324 __u32 attach_prog_fd;
326 __u32 func_info_rec_size;
330 __u32 line_info_rec_size;
335 struct bpf_struct_ops {
337 const struct btf_type *type;
338 struct bpf_program **progs;
339 __u32 *kern_func_off;
340 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
342 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
343 * btf_vmlinux's format.
344 * struct bpf_struct_ops_tcp_congestion_ops {
345 * [... some other kernel fields ...]
346 * struct tcp_congestion_ops data;
348 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
349 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
356 #define DATA_SEC ".data"
357 #define BSS_SEC ".bss"
358 #define RODATA_SEC ".rodata"
359 #define KCONFIG_SEC ".kconfig"
360 #define KSYMS_SEC ".ksyms"
361 #define STRUCT_OPS_SEC ".struct_ops"
363 enum libbpf_map_type {
371 static const char * const libbpf_type_to_btf_name[] = {
372 [LIBBPF_MAP_DATA] = DATA_SEC,
373 [LIBBPF_MAP_BSS] = BSS_SEC,
374 [LIBBPF_MAP_RODATA] = RODATA_SEC,
375 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
385 struct bpf_map_def def;
388 __u32 btf_key_type_id;
389 __u32 btf_value_type_id;
390 __u32 btf_vmlinux_value_type_id;
392 bpf_map_clear_priv_t clear_priv;
393 enum libbpf_map_type libbpf_type;
395 struct bpf_struct_ops *st_ops;
396 struct bpf_map *inner_map;
420 enum extern_type type;
436 unsigned long long addr;
438 /* target btf_id of the corresponding kernel var. */
439 int kernel_btf_obj_fd;
442 /* local btf_id of the ksym extern's type. */
448 static LIST_HEAD(bpf_objects_list);
458 char name[BPF_OBJ_NAME_LEN];
462 struct bpf_program *programs;
464 struct bpf_map *maps;
469 struct extern_desc *externs;
477 struct bpf_gen *gen_loader;
480 * Information when doing elf related work. Only valid if fd
493 Elf_Data *st_ops_data;
494 size_t shstrndx; /* section index for section name strings */
503 __u32 btf_maps_sec_btf_id;
512 * All loaded bpf_object is linked in a list, which is
513 * hidden to caller. bpf_objects__<func> handlers deal with
516 struct list_head list;
519 struct btf_ext *btf_ext;
521 /* Parse and load BTF vmlinux if any of the programs in the object need
524 struct btf *btf_vmlinux;
525 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
526 * override for vmlinux BTF.
528 char *btf_custom_path;
529 /* vmlinux BTF override for CO-RE relocations */
530 struct btf *btf_vmlinux_override;
531 /* Lazily initialized kernel module BTFs */
532 struct module_btf *btf_modules;
533 bool btf_modules_loaded;
534 size_t btf_module_cnt;
535 size_t btf_module_cap;
538 bpf_object_clear_priv_t clear_priv;
542 #define obj_elf_valid(o) ((o)->efile.elf)
544 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
545 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
546 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
547 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
548 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr);
549 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
550 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
552 void bpf_program__unload(struct bpf_program *prog)
560 * If the object is opened but the program was never loaded,
561 * it is possible that prog->instances.nr == -1.
563 if (prog->instances.nr > 0) {
564 for (i = 0; i < prog->instances.nr; i++)
565 zclose(prog->instances.fds[i]);
566 } else if (prog->instances.nr != -1) {
567 pr_warn("Internal error: instances.nr is %d\n",
571 prog->instances.nr = -1;
572 zfree(&prog->instances.fds);
574 zfree(&prog->func_info);
575 zfree(&prog->line_info);
578 static void bpf_program__exit(struct bpf_program *prog)
583 if (prog->clear_priv)
584 prog->clear_priv(prog, prog->priv);
587 prog->clear_priv = NULL;
589 bpf_program__unload(prog);
591 zfree(&prog->sec_name);
592 zfree(&prog->pin_name);
594 zfree(&prog->reloc_desc);
601 static char *__bpf_program__pin_name(struct bpf_program *prog)
605 name = p = strdup(prog->sec_name);
606 while ((p = strchr(p, '/')))
612 static bool insn_is_subprog_call(const struct bpf_insn *insn)
614 return BPF_CLASS(insn->code) == BPF_JMP &&
615 BPF_OP(insn->code) == BPF_CALL &&
616 BPF_SRC(insn->code) == BPF_K &&
617 insn->src_reg == BPF_PSEUDO_CALL &&
618 insn->dst_reg == 0 &&
622 static bool is_call_insn(const struct bpf_insn *insn)
624 return insn->code == (BPF_JMP | BPF_CALL);
627 static bool insn_is_pseudo_func(struct bpf_insn *insn)
629 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
633 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
634 const char *name, size_t sec_idx, const char *sec_name,
635 size_t sec_off, void *insn_data, size_t insn_data_sz)
637 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
638 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
639 sec_name, name, sec_off, insn_data_sz);
643 memset(prog, 0, sizeof(*prog));
646 prog->sec_idx = sec_idx;
647 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
648 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
649 /* insns_cnt can later be increased by appending used subprograms */
650 prog->insns_cnt = prog->sec_insn_cnt;
652 prog->type = BPF_PROG_TYPE_UNSPEC;
655 prog->instances.fds = NULL;
656 prog->instances.nr = -1;
658 prog->sec_name = strdup(sec_name);
662 prog->name = strdup(name);
666 prog->pin_name = __bpf_program__pin_name(prog);
670 prog->insns = malloc(insn_data_sz);
673 memcpy(prog->insns, insn_data, insn_data_sz);
677 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
678 bpf_program__exit(prog);
683 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
684 const char *sec_name, int sec_idx)
686 Elf_Data *symbols = obj->efile.symbols;
687 struct bpf_program *prog, *progs;
688 void *data = sec_data->d_buf;
689 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
690 int nr_progs, err, i;
694 progs = obj->programs;
695 nr_progs = obj->nr_programs;
696 nr_syms = symbols->d_size / sizeof(GElf_Sym);
699 for (i = 0; i < nr_syms; i++) {
700 if (!gelf_getsym(symbols, i, &sym))
702 if (sym.st_shndx != sec_idx)
704 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
707 prog_sz = sym.st_size;
708 sec_off = sym.st_value;
710 name = elf_sym_str(obj, sym.st_name);
712 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
714 return -LIBBPF_ERRNO__FORMAT;
717 if (sec_off + prog_sz > sec_sz) {
718 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
720 return -LIBBPF_ERRNO__FORMAT;
723 if (sec_idx != obj->efile.text_shndx && GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
724 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
728 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
729 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
731 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
734 * In this case the original obj->programs
735 * is still valid, so don't need special treat for
736 * bpf_close_object().
738 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
742 obj->programs = progs;
744 prog = &progs[nr_progs];
746 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
747 sec_off, data + sec_off, prog_sz);
751 /* if function is a global/weak symbol, but has restricted
752 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
753 * as static to enable more permissive BPF verification mode
754 * with more outside context available to BPF verifier
756 if (GELF_ST_BIND(sym.st_info) != STB_LOCAL
757 && (GELF_ST_VISIBILITY(sym.st_other) == STV_HIDDEN
758 || GELF_ST_VISIBILITY(sym.st_other) == STV_INTERNAL))
759 prog->mark_btf_static = true;
762 obj->nr_programs = nr_progs;
768 static __u32 get_kernel_version(void)
770 __u32 major, minor, patch;
774 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
776 return KERNEL_VERSION(major, minor, patch);
779 static const struct btf_member *
780 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
782 struct btf_member *m;
785 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
786 if (btf_member_bit_offset(t, i) == bit_offset)
793 static const struct btf_member *
794 find_member_by_name(const struct btf *btf, const struct btf_type *t,
797 struct btf_member *m;
800 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
801 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
808 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
809 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
810 const char *name, __u32 kind);
813 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
814 const struct btf_type **type, __u32 *type_id,
815 const struct btf_type **vtype, __u32 *vtype_id,
816 const struct btf_member **data_member)
818 const struct btf_type *kern_type, *kern_vtype;
819 const struct btf_member *kern_data_member;
820 __s32 kern_vtype_id, kern_type_id;
823 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
824 if (kern_type_id < 0) {
825 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
829 kern_type = btf__type_by_id(btf, kern_type_id);
831 /* Find the corresponding "map_value" type that will be used
832 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
833 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
836 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
837 tname, BTF_KIND_STRUCT);
838 if (kern_vtype_id < 0) {
839 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
840 STRUCT_OPS_VALUE_PREFIX, tname);
841 return kern_vtype_id;
843 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
845 /* Find "struct tcp_congestion_ops" from
846 * struct bpf_struct_ops_tcp_congestion_ops {
848 * struct tcp_congestion_ops data;
851 kern_data_member = btf_members(kern_vtype);
852 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
853 if (kern_data_member->type == kern_type_id)
856 if (i == btf_vlen(kern_vtype)) {
857 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
858 tname, STRUCT_OPS_VALUE_PREFIX, tname);
863 *type_id = kern_type_id;
865 *vtype_id = kern_vtype_id;
866 *data_member = kern_data_member;
871 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
873 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
876 /* Init the map's fields that depend on kern_btf */
877 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
878 const struct btf *btf,
879 const struct btf *kern_btf)
881 const struct btf_member *member, *kern_member, *kern_data_member;
882 const struct btf_type *type, *kern_type, *kern_vtype;
883 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
884 struct bpf_struct_ops *st_ops;
885 void *data, *kern_data;
889 st_ops = map->st_ops;
891 tname = st_ops->tname;
892 err = find_struct_ops_kern_types(kern_btf, tname,
893 &kern_type, &kern_type_id,
894 &kern_vtype, &kern_vtype_id,
899 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
900 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
902 map->def.value_size = kern_vtype->size;
903 map->btf_vmlinux_value_type_id = kern_vtype_id;
905 st_ops->kern_vdata = calloc(1, kern_vtype->size);
906 if (!st_ops->kern_vdata)
910 kern_data_off = kern_data_member->offset / 8;
911 kern_data = st_ops->kern_vdata + kern_data_off;
913 member = btf_members(type);
914 for (i = 0; i < btf_vlen(type); i++, member++) {
915 const struct btf_type *mtype, *kern_mtype;
916 __u32 mtype_id, kern_mtype_id;
917 void *mdata, *kern_mdata;
918 __s64 msize, kern_msize;
919 __u32 moff, kern_moff;
920 __u32 kern_member_idx;
923 mname = btf__name_by_offset(btf, member->name_off);
924 kern_member = find_member_by_name(kern_btf, kern_type, mname);
926 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
931 kern_member_idx = kern_member - btf_members(kern_type);
932 if (btf_member_bitfield_size(type, i) ||
933 btf_member_bitfield_size(kern_type, kern_member_idx)) {
934 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
939 moff = member->offset / 8;
940 kern_moff = kern_member->offset / 8;
943 kern_mdata = kern_data + kern_moff;
945 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
946 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
948 if (BTF_INFO_KIND(mtype->info) !=
949 BTF_INFO_KIND(kern_mtype->info)) {
950 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
951 map->name, mname, BTF_INFO_KIND(mtype->info),
952 BTF_INFO_KIND(kern_mtype->info));
956 if (btf_is_ptr(mtype)) {
957 struct bpf_program *prog;
959 prog = st_ops->progs[i];
963 kern_mtype = skip_mods_and_typedefs(kern_btf,
967 /* mtype->type must be a func_proto which was
968 * guaranteed in bpf_object__collect_st_ops_relos(),
969 * so only check kern_mtype for func_proto here.
971 if (!btf_is_func_proto(kern_mtype)) {
972 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
977 prog->attach_btf_id = kern_type_id;
978 prog->expected_attach_type = kern_member_idx;
980 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
982 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
983 map->name, mname, prog->name, moff,
989 msize = btf__resolve_size(btf, mtype_id);
990 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
991 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
992 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
993 map->name, mname, (ssize_t)msize,
994 (ssize_t)kern_msize);
998 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
999 map->name, mname, (unsigned int)msize,
1001 memcpy(kern_mdata, mdata, msize);
1007 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1009 struct bpf_map *map;
1013 for (i = 0; i < obj->nr_maps; i++) {
1014 map = &obj->maps[i];
1016 if (!bpf_map__is_struct_ops(map))
1019 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1028 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1030 const struct btf_type *type, *datasec;
1031 const struct btf_var_secinfo *vsi;
1032 struct bpf_struct_ops *st_ops;
1033 const char *tname, *var_name;
1034 __s32 type_id, datasec_id;
1035 const struct btf *btf;
1036 struct bpf_map *map;
1039 if (obj->efile.st_ops_shndx == -1)
1043 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1045 if (datasec_id < 0) {
1046 pr_warn("struct_ops init: DATASEC %s not found\n",
1051 datasec = btf__type_by_id(btf, datasec_id);
1052 vsi = btf_var_secinfos(datasec);
1053 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1054 type = btf__type_by_id(obj->btf, vsi->type);
1055 var_name = btf__name_by_offset(obj->btf, type->name_off);
1057 type_id = btf__resolve_type(obj->btf, vsi->type);
1059 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1060 vsi->type, STRUCT_OPS_SEC);
1064 type = btf__type_by_id(obj->btf, type_id);
1065 tname = btf__name_by_offset(obj->btf, type->name_off);
1067 pr_warn("struct_ops init: anonymous type is not supported\n");
1070 if (!btf_is_struct(type)) {
1071 pr_warn("struct_ops init: %s is not a struct\n", tname);
1075 map = bpf_object__add_map(obj);
1077 return PTR_ERR(map);
1079 map->sec_idx = obj->efile.st_ops_shndx;
1080 map->sec_offset = vsi->offset;
1081 map->name = strdup(var_name);
1085 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1086 map->def.key_size = sizeof(int);
1087 map->def.value_size = type->size;
1088 map->def.max_entries = 1;
1090 map->st_ops = calloc(1, sizeof(*map->st_ops));
1093 st_ops = map->st_ops;
1094 st_ops->data = malloc(type->size);
1095 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1096 st_ops->kern_func_off = malloc(btf_vlen(type) *
1097 sizeof(*st_ops->kern_func_off));
1098 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1101 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1102 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1103 var_name, STRUCT_OPS_SEC);
1107 memcpy(st_ops->data,
1108 obj->efile.st_ops_data->d_buf + vsi->offset,
1110 st_ops->tname = tname;
1111 st_ops->type = type;
1112 st_ops->type_id = type_id;
1114 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1115 tname, type_id, var_name, vsi->offset);
1121 static struct bpf_object *bpf_object__new(const char *path,
1122 const void *obj_buf,
1124 const char *obj_name)
1126 struct bpf_object *obj;
1129 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1131 pr_warn("alloc memory failed for %s\n", path);
1132 return ERR_PTR(-ENOMEM);
1135 strcpy(obj->path, path);
1137 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1138 obj->name[sizeof(obj->name) - 1] = 0;
1140 /* Using basename() GNU version which doesn't modify arg. */
1141 strncpy(obj->name, basename((void *)path),
1142 sizeof(obj->name) - 1);
1143 end = strchr(obj->name, '.');
1150 * Caller of this function should also call
1151 * bpf_object__elf_finish() after data collection to return
1152 * obj_buf to user. If not, we should duplicate the buffer to
1153 * avoid user freeing them before elf finish.
1155 obj->efile.obj_buf = obj_buf;
1156 obj->efile.obj_buf_sz = obj_buf_sz;
1157 obj->efile.maps_shndx = -1;
1158 obj->efile.btf_maps_shndx = -1;
1159 obj->efile.data_shndx = -1;
1160 obj->efile.rodata_shndx = -1;
1161 obj->efile.bss_shndx = -1;
1162 obj->efile.st_ops_shndx = -1;
1163 obj->kconfig_map_idx = -1;
1164 obj->rodata_map_idx = -1;
1166 obj->kern_version = get_kernel_version();
1167 obj->loaded = false;
1169 INIT_LIST_HEAD(&obj->list);
1170 list_add(&obj->list, &bpf_objects_list);
1174 static void bpf_object__elf_finish(struct bpf_object *obj)
1176 if (!obj_elf_valid(obj))
1179 if (obj->efile.elf) {
1180 elf_end(obj->efile.elf);
1181 obj->efile.elf = NULL;
1183 obj->efile.symbols = NULL;
1184 obj->efile.data = NULL;
1185 obj->efile.rodata = NULL;
1186 obj->efile.bss = NULL;
1187 obj->efile.st_ops_data = NULL;
1189 zfree(&obj->efile.reloc_sects);
1190 obj->efile.nr_reloc_sects = 0;
1191 zclose(obj->efile.fd);
1192 obj->efile.obj_buf = NULL;
1193 obj->efile.obj_buf_sz = 0;
1196 static int bpf_object__elf_init(struct bpf_object *obj)
1201 if (obj_elf_valid(obj)) {
1202 pr_warn("elf: init internal error\n");
1203 return -LIBBPF_ERRNO__LIBELF;
1206 if (obj->efile.obj_buf_sz > 0) {
1208 * obj_buf should have been validated by
1209 * bpf_object__open_buffer().
1211 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1212 obj->efile.obj_buf_sz);
1214 obj->efile.fd = open(obj->path, O_RDONLY);
1215 if (obj->efile.fd < 0) {
1216 char errmsg[STRERR_BUFSIZE], *cp;
1219 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1220 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1224 obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1227 if (!obj->efile.elf) {
1228 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1229 err = -LIBBPF_ERRNO__LIBELF;
1233 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1234 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1235 err = -LIBBPF_ERRNO__FORMAT;
1238 ep = &obj->efile.ehdr;
1240 if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) {
1241 pr_warn("elf: failed to get section names section index for %s: %s\n",
1242 obj->path, elf_errmsg(-1));
1243 err = -LIBBPF_ERRNO__FORMAT;
1247 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1248 if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) {
1249 pr_warn("elf: failed to get section names strings from %s: %s\n",
1250 obj->path, elf_errmsg(-1));
1251 err = -LIBBPF_ERRNO__FORMAT;
1255 /* Old LLVM set e_machine to EM_NONE */
1256 if (ep->e_type != ET_REL ||
1257 (ep->e_machine && ep->e_machine != EM_BPF)) {
1258 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1259 err = -LIBBPF_ERRNO__FORMAT;
1265 bpf_object__elf_finish(obj);
1269 static int bpf_object__check_endianness(struct bpf_object *obj)
1271 #if __BYTE_ORDER == __LITTLE_ENDIAN
1272 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1274 #elif __BYTE_ORDER == __BIG_ENDIAN
1275 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1278 # error "Unrecognized __BYTE_ORDER__"
1280 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1281 return -LIBBPF_ERRNO__ENDIAN;
1285 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1287 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1288 pr_debug("license of %s is %s\n", obj->path, obj->license);
1293 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1297 if (size != sizeof(kver)) {
1298 pr_warn("invalid kver section in %s\n", obj->path);
1299 return -LIBBPF_ERRNO__FORMAT;
1301 memcpy(&kver, data, sizeof(kver));
1302 obj->kern_version = kver;
1303 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1307 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1309 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1310 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1315 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1323 } else if (!strcmp(name, DATA_SEC)) {
1324 if (obj->efile.data)
1325 *size = obj->efile.data->d_size;
1326 } else if (!strcmp(name, BSS_SEC)) {
1328 *size = obj->efile.bss->d_size;
1329 } else if (!strcmp(name, RODATA_SEC)) {
1330 if (obj->efile.rodata)
1331 *size = obj->efile.rodata->d_size;
1332 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1333 if (obj->efile.st_ops_data)
1334 *size = obj->efile.st_ops_data->d_size;
1336 Elf_Scn *scn = elf_sec_by_name(obj, name);
1337 Elf_Data *data = elf_sec_data(obj, scn);
1340 ret = 0; /* found it */
1341 *size = data->d_size;
1345 return *size ? 0 : ret;
1348 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1351 Elf_Data *symbols = obj->efile.symbols;
1358 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1361 if (!gelf_getsym(symbols, si, &sym))
1363 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1364 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1367 sname = elf_sym_str(obj, sym.st_name);
1369 pr_warn("failed to get sym name string for var %s\n",
1373 if (strcmp(name, sname) == 0) {
1374 *off = sym.st_value;
1382 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1384 struct bpf_map *new_maps;
1388 if (obj->nr_maps < obj->maps_cap)
1389 return &obj->maps[obj->nr_maps++];
1391 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1392 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1394 pr_warn("alloc maps for object failed\n");
1395 return ERR_PTR(-ENOMEM);
1398 obj->maps_cap = new_cap;
1399 obj->maps = new_maps;
1401 /* zero out new maps */
1402 memset(obj->maps + obj->nr_maps, 0,
1403 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1405 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1406 * when failure (zclose won't close negative fd)).
1408 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1409 obj->maps[i].fd = -1;
1410 obj->maps[i].inner_map_fd = -1;
1413 return &obj->maps[obj->nr_maps++];
1416 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1418 long page_sz = sysconf(_SC_PAGE_SIZE);
1421 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1422 map_sz = roundup(map_sz, page_sz);
1426 static char *internal_map_name(struct bpf_object *obj,
1427 enum libbpf_map_type type)
1429 char map_name[BPF_OBJ_NAME_LEN], *p;
1430 const char *sfx = libbpf_type_to_btf_name[type];
1431 int sfx_len = max((size_t)7, strlen(sfx));
1432 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1435 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1436 sfx_len, libbpf_type_to_btf_name[type]);
1438 /* sanitise map name to characters allowed by kernel */
1439 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1440 if (!isalnum(*p) && *p != '_' && *p != '.')
1443 return strdup(map_name);
1447 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1448 int sec_idx, void *data, size_t data_sz)
1450 struct bpf_map_def *def;
1451 struct bpf_map *map;
1454 map = bpf_object__add_map(obj);
1456 return PTR_ERR(map);
1458 map->libbpf_type = type;
1459 map->sec_idx = sec_idx;
1460 map->sec_offset = 0;
1461 map->name = internal_map_name(obj, type);
1463 pr_warn("failed to alloc map name\n");
1468 def->type = BPF_MAP_TYPE_ARRAY;
1469 def->key_size = sizeof(int);
1470 def->value_size = data_sz;
1471 def->max_entries = 1;
1472 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1473 ? BPF_F_RDONLY_PROG : 0;
1474 def->map_flags |= BPF_F_MMAPABLE;
1476 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1477 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1479 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1480 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1481 if (map->mmaped == MAP_FAILED) {
1484 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1491 memcpy(map->mmaped, data, data_sz);
1493 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1497 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1502 * Populate obj->maps with libbpf internal maps.
1504 if (obj->efile.data_shndx >= 0) {
1505 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1506 obj->efile.data_shndx,
1507 obj->efile.data->d_buf,
1508 obj->efile.data->d_size);
1512 if (obj->efile.rodata_shndx >= 0) {
1513 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1514 obj->efile.rodata_shndx,
1515 obj->efile.rodata->d_buf,
1516 obj->efile.rodata->d_size);
1520 obj->rodata_map_idx = obj->nr_maps - 1;
1522 if (obj->efile.bss_shndx >= 0) {
1523 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1524 obj->efile.bss_shndx,
1526 obj->efile.bss->d_size);
1534 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1539 for (i = 0; i < obj->nr_extern; i++) {
1540 if (strcmp(obj->externs[i].name, name) == 0)
1541 return &obj->externs[i];
1546 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1549 switch (ext->kcfg.type) {
1552 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1556 *(bool *)ext_val = value == 'y' ? true : false;
1560 *(enum libbpf_tristate *)ext_val = TRI_YES;
1561 else if (value == 'm')
1562 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1563 else /* value == 'n' */
1564 *(enum libbpf_tristate *)ext_val = TRI_NO;
1567 *(char *)ext_val = value;
1573 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1581 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1586 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1587 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1591 len = strlen(value);
1592 if (value[len - 1] != '"') {
1593 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1600 if (len >= ext->kcfg.sz) {
1601 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1602 ext->name, value, len, ext->kcfg.sz - 1);
1603 len = ext->kcfg.sz - 1;
1605 memcpy(ext_val, value + 1, len);
1606 ext_val[len] = '\0';
1611 static int parse_u64(const char *value, __u64 *res)
1617 *res = strtoull(value, &value_end, 0);
1620 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1624 pr_warn("failed to parse '%s' as integer completely\n", value);
1630 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1632 int bit_sz = ext->kcfg.sz * 8;
1634 if (ext->kcfg.sz == 8)
1637 /* Validate that value stored in u64 fits in integer of `ext->sz`
1638 * bytes size without any loss of information. If the target integer
1639 * is signed, we rely on the following limits of integer type of
1640 * Y bits and subsequent transformation:
1642 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1643 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1644 * 0 <= X + 2^(Y-1) < 2^Y
1646 * For unsigned target integer, check that all the (64 - Y) bits are
1649 if (ext->kcfg.is_signed)
1650 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1652 return (v >> bit_sz) == 0;
1655 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1658 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1659 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1660 ext->name, (unsigned long long)value);
1663 if (!is_kcfg_value_in_range(ext, value)) {
1664 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1665 ext->name, (unsigned long long)value, ext->kcfg.sz);
1668 switch (ext->kcfg.sz) {
1669 case 1: *(__u8 *)ext_val = value; break;
1670 case 2: *(__u16 *)ext_val = value; break;
1671 case 4: *(__u32 *)ext_val = value; break;
1672 case 8: *(__u64 *)ext_val = value; break;
1680 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1681 char *buf, void *data)
1683 struct extern_desc *ext;
1689 if (!str_has_pfx(buf, "CONFIG_"))
1692 sep = strchr(buf, '=');
1694 pr_warn("failed to parse '%s': no separator\n", buf);
1698 /* Trim ending '\n' */
1700 if (buf[len - 1] == '\n')
1701 buf[len - 1] = '\0';
1702 /* Split on '=' and ensure that a value is present. */
1706 pr_warn("failed to parse '%s': no value\n", buf);
1710 ext = find_extern_by_name(obj, buf);
1711 if (!ext || ext->is_set)
1714 ext_val = data + ext->kcfg.data_off;
1718 case 'y': case 'n': case 'm':
1719 err = set_kcfg_value_tri(ext, ext_val, *value);
1722 err = set_kcfg_value_str(ext, ext_val, value);
1725 /* assume integer */
1726 err = parse_u64(value, &num);
1728 pr_warn("extern (kcfg) %s=%s should be integer\n",
1732 err = set_kcfg_value_num(ext, ext_val, num);
1737 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1741 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1749 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1752 else if (len >= PATH_MAX)
1753 return -ENAMETOOLONG;
1755 /* gzopen also accepts uncompressed files. */
1756 file = gzopen(buf, "r");
1758 file = gzopen("/proc/config.gz", "r");
1761 pr_warn("failed to open system Kconfig\n");
1765 while (gzgets(file, buf, sizeof(buf))) {
1766 err = bpf_object__process_kconfig_line(obj, buf, data);
1768 pr_warn("error parsing system Kconfig line '%s': %d\n",
1779 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1780 const char *config, void *data)
1786 file = fmemopen((void *)config, strlen(config), "r");
1789 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1793 while (fgets(buf, sizeof(buf), file)) {
1794 err = bpf_object__process_kconfig_line(obj, buf, data);
1796 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1806 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1808 struct extern_desc *last_ext = NULL, *ext;
1812 for (i = 0; i < obj->nr_extern; i++) {
1813 ext = &obj->externs[i];
1814 if (ext->type == EXT_KCFG)
1821 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1822 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1823 obj->efile.symbols_shndx,
1828 obj->kconfig_map_idx = obj->nr_maps - 1;
1833 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1835 Elf_Data *symbols = obj->efile.symbols;
1836 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1837 Elf_Data *data = NULL;
1840 if (obj->efile.maps_shndx < 0)
1846 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1847 data = elf_sec_data(obj, scn);
1848 if (!scn || !data) {
1849 pr_warn("elf: failed to get legacy map definitions for %s\n",
1855 * Count number of maps. Each map has a name.
1856 * Array of maps is not supported: only the first element is
1859 * TODO: Detect array of map and report error.
1861 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1862 for (i = 0; i < nr_syms; i++) {
1865 if (!gelf_getsym(symbols, i, &sym))
1867 if (sym.st_shndx != obj->efile.maps_shndx)
1871 /* Assume equally sized map definitions */
1872 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1873 nr_maps, data->d_size, obj->path);
1875 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1876 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1880 map_def_sz = data->d_size / nr_maps;
1882 /* Fill obj->maps using data in "maps" section. */
1883 for (i = 0; i < nr_syms; i++) {
1885 const char *map_name;
1886 struct bpf_map_def *def;
1887 struct bpf_map *map;
1889 if (!gelf_getsym(symbols, i, &sym))
1891 if (sym.st_shndx != obj->efile.maps_shndx)
1893 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION)
1896 map = bpf_object__add_map(obj);
1898 return PTR_ERR(map);
1900 map_name = elf_sym_str(obj, sym.st_name);
1902 pr_warn("failed to get map #%d name sym string for obj %s\n",
1904 return -LIBBPF_ERRNO__FORMAT;
1907 if (GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
1908 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
1912 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1913 map->sec_idx = sym.st_shndx;
1914 map->sec_offset = sym.st_value;
1915 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1916 map_name, map->sec_idx, map->sec_offset);
1917 if (sym.st_value + map_def_sz > data->d_size) {
1918 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1919 obj->path, map_name);
1923 map->name = strdup(map_name);
1925 pr_warn("failed to alloc map name\n");
1928 pr_debug("map %d is \"%s\"\n", i, map->name);
1929 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1931 * If the definition of the map in the object file fits in
1932 * bpf_map_def, copy it. Any extra fields in our version
1933 * of bpf_map_def will default to zero as a result of the
1936 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1937 memcpy(&map->def, def, map_def_sz);
1940 * Here the map structure being read is bigger than what
1941 * we expect, truncate if the excess bits are all zero.
1942 * If they are not zero, reject this map as
1947 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1948 b < ((char *)def) + map_def_sz; b++) {
1950 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1951 obj->path, map_name);
1956 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1962 const struct btf_type *
1963 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1965 const struct btf_type *t = btf__type_by_id(btf, id);
1970 while (btf_is_mod(t) || btf_is_typedef(t)) {
1973 t = btf__type_by_id(btf, t->type);
1979 static const struct btf_type *
1980 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1982 const struct btf_type *t;
1984 t = skip_mods_and_typedefs(btf, id, NULL);
1988 t = skip_mods_and_typedefs(btf, t->type, res_id);
1990 return btf_is_func_proto(t) ? t : NULL;
1993 static const char *__btf_kind_str(__u16 kind)
1996 case BTF_KIND_UNKN: return "void";
1997 case BTF_KIND_INT: return "int";
1998 case BTF_KIND_PTR: return "ptr";
1999 case BTF_KIND_ARRAY: return "array";
2000 case BTF_KIND_STRUCT: return "struct";
2001 case BTF_KIND_UNION: return "union";
2002 case BTF_KIND_ENUM: return "enum";
2003 case BTF_KIND_FWD: return "fwd";
2004 case BTF_KIND_TYPEDEF: return "typedef";
2005 case BTF_KIND_VOLATILE: return "volatile";
2006 case BTF_KIND_CONST: return "const";
2007 case BTF_KIND_RESTRICT: return "restrict";
2008 case BTF_KIND_FUNC: return "func";
2009 case BTF_KIND_FUNC_PROTO: return "func_proto";
2010 case BTF_KIND_VAR: return "var";
2011 case BTF_KIND_DATASEC: return "datasec";
2012 case BTF_KIND_FLOAT: return "float";
2013 case BTF_KIND_TAG: return "tag";
2014 default: return "unknown";
2018 const char *btf_kind_str(const struct btf_type *t)
2020 return __btf_kind_str(btf_kind(t));
2024 * Fetch integer attribute of BTF map definition. Such attributes are
2025 * represented using a pointer to an array, in which dimensionality of array
2026 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2027 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2028 * type definition, while using only sizeof(void *) space in ELF data section.
2030 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2031 const struct btf_member *m, __u32 *res)
2033 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2034 const char *name = btf__name_by_offset(btf, m->name_off);
2035 const struct btf_array *arr_info;
2036 const struct btf_type *arr_t;
2038 if (!btf_is_ptr(t)) {
2039 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2040 map_name, name, btf_kind_str(t));
2044 arr_t = btf__type_by_id(btf, t->type);
2046 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2047 map_name, name, t->type);
2050 if (!btf_is_array(arr_t)) {
2051 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2052 map_name, name, btf_kind_str(arr_t));
2055 arr_info = btf_array(arr_t);
2056 *res = arr_info->nelems;
2060 static int build_map_pin_path(struct bpf_map *map, const char *path)
2066 path = "/sys/fs/bpf";
2068 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2071 else if (len >= PATH_MAX)
2072 return -ENAMETOOLONG;
2074 return bpf_map__set_pin_path(map, buf);
2077 int parse_btf_map_def(const char *map_name, struct btf *btf,
2078 const struct btf_type *def_t, bool strict,
2079 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2081 const struct btf_type *t;
2082 const struct btf_member *m;
2083 bool is_inner = inner_def == NULL;
2086 vlen = btf_vlen(def_t);
2087 m = btf_members(def_t);
2088 for (i = 0; i < vlen; i++, m++) {
2089 const char *name = btf__name_by_offset(btf, m->name_off);
2092 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2095 if (strcmp(name, "type") == 0) {
2096 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2098 map_def->parts |= MAP_DEF_MAP_TYPE;
2099 } else if (strcmp(name, "max_entries") == 0) {
2100 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2102 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2103 } else if (strcmp(name, "map_flags") == 0) {
2104 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2106 map_def->parts |= MAP_DEF_MAP_FLAGS;
2107 } else if (strcmp(name, "numa_node") == 0) {
2108 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2110 map_def->parts |= MAP_DEF_NUMA_NODE;
2111 } else if (strcmp(name, "key_size") == 0) {
2114 if (!get_map_field_int(map_name, btf, m, &sz))
2116 if (map_def->key_size && map_def->key_size != sz) {
2117 pr_warn("map '%s': conflicting key size %u != %u.\n",
2118 map_name, map_def->key_size, sz);
2121 map_def->key_size = sz;
2122 map_def->parts |= MAP_DEF_KEY_SIZE;
2123 } else if (strcmp(name, "key") == 0) {
2126 t = btf__type_by_id(btf, m->type);
2128 pr_warn("map '%s': key type [%d] not found.\n",
2132 if (!btf_is_ptr(t)) {
2133 pr_warn("map '%s': key spec is not PTR: %s.\n",
2134 map_name, btf_kind_str(t));
2137 sz = btf__resolve_size(btf, t->type);
2139 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2140 map_name, t->type, (ssize_t)sz);
2143 if (map_def->key_size && map_def->key_size != sz) {
2144 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2145 map_name, map_def->key_size, (ssize_t)sz);
2148 map_def->key_size = sz;
2149 map_def->key_type_id = t->type;
2150 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2151 } else if (strcmp(name, "value_size") == 0) {
2154 if (!get_map_field_int(map_name, btf, m, &sz))
2156 if (map_def->value_size && map_def->value_size != sz) {
2157 pr_warn("map '%s': conflicting value size %u != %u.\n",
2158 map_name, map_def->value_size, sz);
2161 map_def->value_size = sz;
2162 map_def->parts |= MAP_DEF_VALUE_SIZE;
2163 } else if (strcmp(name, "value") == 0) {
2166 t = btf__type_by_id(btf, m->type);
2168 pr_warn("map '%s': value type [%d] not found.\n",
2172 if (!btf_is_ptr(t)) {
2173 pr_warn("map '%s': value spec is not PTR: %s.\n",
2174 map_name, btf_kind_str(t));
2177 sz = btf__resolve_size(btf, t->type);
2179 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2180 map_name, t->type, (ssize_t)sz);
2183 if (map_def->value_size && map_def->value_size != sz) {
2184 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2185 map_name, map_def->value_size, (ssize_t)sz);
2188 map_def->value_size = sz;
2189 map_def->value_type_id = t->type;
2190 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2192 else if (strcmp(name, "values") == 0) {
2193 char inner_map_name[128];
2197 pr_warn("map '%s': multi-level inner maps not supported.\n",
2201 if (i != vlen - 1) {
2202 pr_warn("map '%s': '%s' member should be last.\n",
2206 if (!bpf_map_type__is_map_in_map(map_def->map_type)) {
2207 pr_warn("map '%s': should be map-in-map.\n",
2211 if (map_def->value_size && map_def->value_size != 4) {
2212 pr_warn("map '%s': conflicting value size %u != 4.\n",
2213 map_name, map_def->value_size);
2216 map_def->value_size = 4;
2217 t = btf__type_by_id(btf, m->type);
2219 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2223 if (!btf_is_array(t) || btf_array(t)->nelems) {
2224 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2228 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2229 if (!btf_is_ptr(t)) {
2230 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2231 map_name, btf_kind_str(t));
2234 t = skip_mods_and_typedefs(btf, t->type, NULL);
2235 if (!btf_is_struct(t)) {
2236 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2237 map_name, btf_kind_str(t));
2241 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2242 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2246 map_def->parts |= MAP_DEF_INNER_MAP;
2247 } else if (strcmp(name, "pinning") == 0) {
2251 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2254 if (!get_map_field_int(map_name, btf, m, &val))
2256 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2257 pr_warn("map '%s': invalid pinning value %u.\n",
2261 map_def->pinning = val;
2262 map_def->parts |= MAP_DEF_PINNING;
2265 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2268 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2272 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2273 pr_warn("map '%s': map type isn't specified.\n", map_name);
2280 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2282 map->def.type = def->map_type;
2283 map->def.key_size = def->key_size;
2284 map->def.value_size = def->value_size;
2285 map->def.max_entries = def->max_entries;
2286 map->def.map_flags = def->map_flags;
2288 map->numa_node = def->numa_node;
2289 map->btf_key_type_id = def->key_type_id;
2290 map->btf_value_type_id = def->value_type_id;
2292 if (def->parts & MAP_DEF_MAP_TYPE)
2293 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2295 if (def->parts & MAP_DEF_KEY_TYPE)
2296 pr_debug("map '%s': found key [%u], sz = %u.\n",
2297 map->name, def->key_type_id, def->key_size);
2298 else if (def->parts & MAP_DEF_KEY_SIZE)
2299 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2301 if (def->parts & MAP_DEF_VALUE_TYPE)
2302 pr_debug("map '%s': found value [%u], sz = %u.\n",
2303 map->name, def->value_type_id, def->value_size);
2304 else if (def->parts & MAP_DEF_VALUE_SIZE)
2305 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2307 if (def->parts & MAP_DEF_MAX_ENTRIES)
2308 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2309 if (def->parts & MAP_DEF_MAP_FLAGS)
2310 pr_debug("map '%s': found map_flags = %u.\n", map->name, def->map_flags);
2311 if (def->parts & MAP_DEF_PINNING)
2312 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2313 if (def->parts & MAP_DEF_NUMA_NODE)
2314 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2316 if (def->parts & MAP_DEF_INNER_MAP)
2317 pr_debug("map '%s': found inner map definition.\n", map->name);
2320 static const char *btf_var_linkage_str(__u32 linkage)
2323 case BTF_VAR_STATIC: return "static";
2324 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2325 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2326 default: return "unknown";
2330 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2331 const struct btf_type *sec,
2332 int var_idx, int sec_idx,
2333 const Elf_Data *data, bool strict,
2334 const char *pin_root_path)
2336 struct btf_map_def map_def = {}, inner_def = {};
2337 const struct btf_type *var, *def;
2338 const struct btf_var_secinfo *vi;
2339 const struct btf_var *var_extra;
2340 const char *map_name;
2341 struct bpf_map *map;
2344 vi = btf_var_secinfos(sec) + var_idx;
2345 var = btf__type_by_id(obj->btf, vi->type);
2346 var_extra = btf_var(var);
2347 map_name = btf__name_by_offset(obj->btf, var->name_off);
2349 if (map_name == NULL || map_name[0] == '\0') {
2350 pr_warn("map #%d: empty name.\n", var_idx);
2353 if ((__u64)vi->offset + vi->size > data->d_size) {
2354 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2357 if (!btf_is_var(var)) {
2358 pr_warn("map '%s': unexpected var kind %s.\n",
2359 map_name, btf_kind_str(var));
2362 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2363 pr_warn("map '%s': unsupported map linkage %s.\n",
2364 map_name, btf_var_linkage_str(var_extra->linkage));
2368 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2369 if (!btf_is_struct(def)) {
2370 pr_warn("map '%s': unexpected def kind %s.\n",
2371 map_name, btf_kind_str(var));
2374 if (def->size > vi->size) {
2375 pr_warn("map '%s': invalid def size.\n", map_name);
2379 map = bpf_object__add_map(obj);
2381 return PTR_ERR(map);
2382 map->name = strdup(map_name);
2384 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2387 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2388 map->def.type = BPF_MAP_TYPE_UNSPEC;
2389 map->sec_idx = sec_idx;
2390 map->sec_offset = vi->offset;
2391 map->btf_var_idx = var_idx;
2392 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2393 map_name, map->sec_idx, map->sec_offset);
2395 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2399 fill_map_from_def(map, &map_def);
2401 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2402 err = build_map_pin_path(map, pin_root_path);
2404 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2409 if (map_def.parts & MAP_DEF_INNER_MAP) {
2410 map->inner_map = calloc(1, sizeof(*map->inner_map));
2411 if (!map->inner_map)
2413 map->inner_map->fd = -1;
2414 map->inner_map->sec_idx = sec_idx;
2415 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2416 if (!map->inner_map->name)
2418 sprintf(map->inner_map->name, "%s.inner", map_name);
2420 fill_map_from_def(map->inner_map, &inner_def);
2426 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2427 const char *pin_root_path)
2429 const struct btf_type *sec = NULL;
2430 int nr_types, i, vlen, err;
2431 const struct btf_type *t;
2436 if (obj->efile.btf_maps_shndx < 0)
2439 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2440 data = elf_sec_data(obj, scn);
2441 if (!scn || !data) {
2442 pr_warn("elf: failed to get %s map definitions for %s\n",
2443 MAPS_ELF_SEC, obj->path);
2447 nr_types = btf__get_nr_types(obj->btf);
2448 for (i = 1; i <= nr_types; i++) {
2449 t = btf__type_by_id(obj->btf, i);
2450 if (!btf_is_datasec(t))
2452 name = btf__name_by_offset(obj->btf, t->name_off);
2453 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2455 obj->efile.btf_maps_sec_btf_id = i;
2461 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2465 vlen = btf_vlen(sec);
2466 for (i = 0; i < vlen; i++) {
2467 err = bpf_object__init_user_btf_map(obj, sec, i,
2468 obj->efile.btf_maps_shndx,
2478 static int bpf_object__init_maps(struct bpf_object *obj,
2479 const struct bpf_object_open_opts *opts)
2481 const char *pin_root_path;
2485 strict = !OPTS_GET(opts, relaxed_maps, false);
2486 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2488 err = bpf_object__init_user_maps(obj, strict);
2489 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2490 err = err ?: bpf_object__init_global_data_maps(obj);
2491 err = err ?: bpf_object__init_kconfig_map(obj);
2492 err = err ?: bpf_object__init_struct_ops_maps(obj);
2497 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2501 if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh))
2504 return sh.sh_flags & SHF_EXECINSTR;
2507 static bool btf_needs_sanitization(struct bpf_object *obj)
2509 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2510 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2511 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2512 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2513 bool has_tag = kernel_supports(obj, FEAT_BTF_TAG);
2515 return !has_func || !has_datasec || !has_func_global || !has_float || !has_tag;
2518 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2520 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2521 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2522 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2523 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2524 bool has_tag = kernel_supports(obj, FEAT_BTF_TAG);
2528 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2529 t = (struct btf_type *)btf__type_by_id(btf, i);
2531 if ((!has_datasec && btf_is_var(t)) || (!has_tag && btf_is_tag(t))) {
2532 /* replace VAR/TAG with INT */
2533 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2535 * using size = 1 is the safest choice, 4 will be too
2536 * big and cause kernel BTF validation failure if
2537 * original variable took less than 4 bytes
2540 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2541 } else if (!has_datasec && btf_is_datasec(t)) {
2542 /* replace DATASEC with STRUCT */
2543 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2544 struct btf_member *m = btf_members(t);
2545 struct btf_type *vt;
2548 name = (char *)btf__name_by_offset(btf, t->name_off);
2556 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2557 for (j = 0; j < vlen; j++, v++, m++) {
2558 /* order of field assignments is important */
2559 m->offset = v->offset * 8;
2561 /* preserve variable name as member name */
2562 vt = (void *)btf__type_by_id(btf, v->type);
2563 m->name_off = vt->name_off;
2565 } else if (!has_func && btf_is_func_proto(t)) {
2566 /* replace FUNC_PROTO with ENUM */
2568 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2569 t->size = sizeof(__u32); /* kernel enforced */
2570 } else if (!has_func && btf_is_func(t)) {
2571 /* replace FUNC with TYPEDEF */
2572 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2573 } else if (!has_func_global && btf_is_func(t)) {
2574 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2575 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2576 } else if (!has_float && btf_is_float(t)) {
2577 /* replace FLOAT with an equally-sized empty STRUCT;
2578 * since C compilers do not accept e.g. "float" as a
2579 * valid struct name, make it anonymous
2582 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2587 static bool libbpf_needs_btf(const struct bpf_object *obj)
2589 return obj->efile.btf_maps_shndx >= 0 ||
2590 obj->efile.st_ops_shndx >= 0 ||
2594 static bool kernel_needs_btf(const struct bpf_object *obj)
2596 return obj->efile.st_ops_shndx >= 0;
2599 static int bpf_object__init_btf(struct bpf_object *obj,
2601 Elf_Data *btf_ext_data)
2606 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2607 err = libbpf_get_error(obj->btf);
2610 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2613 /* enforce 8-byte pointers for BPF-targeted BTFs */
2614 btf__set_pointer_size(obj->btf, 8);
2618 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2619 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2622 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2623 err = libbpf_get_error(obj->btf_ext);
2625 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2626 BTF_EXT_ELF_SEC, err);
2627 obj->btf_ext = NULL;
2632 if (err && libbpf_needs_btf(obj)) {
2633 pr_warn("BTF is required, but is missing or corrupted.\n");
2639 static int bpf_object__finalize_btf(struct bpf_object *obj)
2646 err = btf__finalize_data(obj, obj->btf);
2648 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2655 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2657 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2658 prog->type == BPF_PROG_TYPE_LSM)
2661 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2662 * also need vmlinux BTF
2664 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2670 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2672 struct bpf_program *prog;
2675 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2678 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2681 /* Support for typed ksyms needs kernel BTF */
2682 for (i = 0; i < obj->nr_extern; i++) {
2683 const struct extern_desc *ext;
2685 ext = &obj->externs[i];
2686 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2690 bpf_object__for_each_program(prog, obj) {
2693 if (prog_needs_vmlinux_btf(prog))
2700 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2704 /* btf_vmlinux could be loaded earlier */
2705 if (obj->btf_vmlinux || obj->gen_loader)
2708 if (!force && !obj_needs_vmlinux_btf(obj))
2711 obj->btf_vmlinux = btf__load_vmlinux_btf();
2712 err = libbpf_get_error(obj->btf_vmlinux);
2714 pr_warn("Error loading vmlinux BTF: %d\n", err);
2715 obj->btf_vmlinux = NULL;
2721 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2723 struct btf *kern_btf = obj->btf;
2724 bool btf_mandatory, sanitize;
2730 if (!kernel_supports(obj, FEAT_BTF)) {
2731 if (kernel_needs_btf(obj)) {
2735 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2739 /* Even though some subprogs are global/weak, user might prefer more
2740 * permissive BPF verification process that BPF verifier performs for
2741 * static functions, taking into account more context from the caller
2742 * functions. In such case, they need to mark such subprogs with
2743 * __attribute__((visibility("hidden"))) and libbpf will adjust
2744 * corresponding FUNC BTF type to be marked as static and trigger more
2745 * involved BPF verification process.
2747 for (i = 0; i < obj->nr_programs; i++) {
2748 struct bpf_program *prog = &obj->programs[i];
2753 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2756 n = btf__get_nr_types(obj->btf);
2757 for (j = 1; j <= n; j++) {
2758 t = btf_type_by_id(obj->btf, j);
2759 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2762 name = btf__str_by_offset(obj->btf, t->name_off);
2763 if (strcmp(name, prog->name) != 0)
2766 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2771 sanitize = btf_needs_sanitization(obj);
2773 const void *raw_data;
2776 /* clone BTF to sanitize a copy and leave the original intact */
2777 raw_data = btf__get_raw_data(obj->btf, &sz);
2778 kern_btf = btf__new(raw_data, sz);
2779 err = libbpf_get_error(kern_btf);
2783 /* enforce 8-byte pointers for BPF-targeted BTFs */
2784 btf__set_pointer_size(obj->btf, 8);
2785 bpf_object__sanitize_btf(obj, kern_btf);
2788 if (obj->gen_loader) {
2790 const void *raw_data = btf__get_raw_data(kern_btf, &raw_size);
2794 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
2795 /* Pretend to have valid FD to pass various fd >= 0 checks.
2796 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
2798 btf__set_fd(kern_btf, 0);
2800 err = btf__load_into_kernel(kern_btf);
2804 /* move fd to libbpf's BTF */
2805 btf__set_fd(obj->btf, btf__fd(kern_btf));
2806 btf__set_fd(kern_btf, -1);
2808 btf__free(kern_btf);
2812 btf_mandatory = kernel_needs_btf(obj);
2813 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2814 btf_mandatory ? "BTF is mandatory, can't proceed."
2815 : "BTF is optional, ignoring.");
2822 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
2826 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
2828 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2829 off, obj->path, elf_errmsg(-1));
2836 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
2840 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
2842 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2843 off, obj->path, elf_errmsg(-1));
2850 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
2854 scn = elf_getscn(obj->efile.elf, idx);
2856 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
2857 idx, obj->path, elf_errmsg(-1));
2863 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
2865 Elf_Scn *scn = NULL;
2866 Elf *elf = obj->efile.elf;
2867 const char *sec_name;
2869 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2870 sec_name = elf_sec_name(obj, scn);
2874 if (strcmp(sec_name, name) != 0)
2882 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr)
2887 if (gelf_getshdr(scn, hdr) != hdr) {
2888 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
2889 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2896 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
2904 if (elf_sec_hdr(obj, scn, &sh))
2907 name = elf_sec_str(obj, sh.sh_name);
2909 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
2910 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2917 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
2924 data = elf_getdata(scn, 0);
2926 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
2927 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
2928 obj->path, elf_errmsg(-1));
2935 static bool is_sec_name_dwarf(const char *name)
2937 /* approximation, but the actual list is too long */
2938 return str_has_pfx(name, ".debug_");
2941 static bool ignore_elf_section(GElf_Shdr *hdr, const char *name)
2943 /* no special handling of .strtab */
2944 if (hdr->sh_type == SHT_STRTAB)
2947 /* ignore .llvm_addrsig section as well */
2948 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
2951 /* no subprograms will lead to an empty .text section, ignore it */
2952 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
2953 strcmp(name, ".text") == 0)
2956 /* DWARF sections */
2957 if (is_sec_name_dwarf(name))
2960 if (str_has_pfx(name, ".rel")) {
2961 name += sizeof(".rel") - 1;
2962 /* DWARF section relocations */
2963 if (is_sec_name_dwarf(name))
2966 /* .BTF and .BTF.ext don't need relocations */
2967 if (strcmp(name, BTF_ELF_SEC) == 0 ||
2968 strcmp(name, BTF_EXT_ELF_SEC) == 0)
2975 static int cmp_progs(const void *_a, const void *_b)
2977 const struct bpf_program *a = _a;
2978 const struct bpf_program *b = _b;
2980 if (a->sec_idx != b->sec_idx)
2981 return a->sec_idx < b->sec_idx ? -1 : 1;
2983 /* sec_insn_off can't be the same within the section */
2984 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
2987 static int bpf_object__elf_collect(struct bpf_object *obj)
2989 Elf *elf = obj->efile.elf;
2990 Elf_Data *btf_ext_data = NULL;
2991 Elf_Data *btf_data = NULL;
2992 int idx = 0, err = 0;
2998 /* a bunch of ELF parsing functionality depends on processing symbols,
2999 * so do the first pass and find the symbol table
3002 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3003 if (elf_sec_hdr(obj, scn, &sh))
3004 return -LIBBPF_ERRNO__FORMAT;
3006 if (sh.sh_type == SHT_SYMTAB) {
3007 if (obj->efile.symbols) {
3008 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3009 return -LIBBPF_ERRNO__FORMAT;
3012 data = elf_sec_data(obj, scn);
3014 return -LIBBPF_ERRNO__FORMAT;
3016 obj->efile.symbols = data;
3017 obj->efile.symbols_shndx = elf_ndxscn(scn);
3018 obj->efile.strtabidx = sh.sh_link;
3022 if (!obj->efile.symbols) {
3023 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3029 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3032 if (elf_sec_hdr(obj, scn, &sh))
3033 return -LIBBPF_ERRNO__FORMAT;
3035 name = elf_sec_str(obj, sh.sh_name);
3037 return -LIBBPF_ERRNO__FORMAT;
3039 if (ignore_elf_section(&sh, name))
3042 data = elf_sec_data(obj, scn);
3044 return -LIBBPF_ERRNO__FORMAT;
3046 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3047 idx, name, (unsigned long)data->d_size,
3048 (int)sh.sh_link, (unsigned long)sh.sh_flags,
3051 if (strcmp(name, "license") == 0) {
3052 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3055 } else if (strcmp(name, "version") == 0) {
3056 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3059 } else if (strcmp(name, "maps") == 0) {
3060 obj->efile.maps_shndx = idx;
3061 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3062 obj->efile.btf_maps_shndx = idx;
3063 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3065 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3066 btf_ext_data = data;
3067 } else if (sh.sh_type == SHT_SYMTAB) {
3068 /* already processed during the first pass above */
3069 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
3070 if (sh.sh_flags & SHF_EXECINSTR) {
3071 if (strcmp(name, ".text") == 0)
3072 obj->efile.text_shndx = idx;
3073 err = bpf_object__add_programs(obj, data, name, idx);
3076 } else if (strcmp(name, DATA_SEC) == 0) {
3077 obj->efile.data = data;
3078 obj->efile.data_shndx = idx;
3079 } else if (strcmp(name, RODATA_SEC) == 0) {
3080 obj->efile.rodata = data;
3081 obj->efile.rodata_shndx = idx;
3082 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3083 obj->efile.st_ops_data = data;
3084 obj->efile.st_ops_shndx = idx;
3086 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3089 } else if (sh.sh_type == SHT_REL) {
3090 int nr_sects = obj->efile.nr_reloc_sects;
3091 void *sects = obj->efile.reloc_sects;
3092 int sec = sh.sh_info; /* points to other section */
3094 /* Only do relo for section with exec instructions */
3095 if (!section_have_execinstr(obj, sec) &&
3096 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3097 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3098 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3100 elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>");
3104 sects = libbpf_reallocarray(sects, nr_sects + 1,
3105 sizeof(*obj->efile.reloc_sects));
3109 obj->efile.reloc_sects = sects;
3110 obj->efile.nr_reloc_sects++;
3112 obj->efile.reloc_sects[nr_sects].shdr = sh;
3113 obj->efile.reloc_sects[nr_sects].data = data;
3114 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3115 obj->efile.bss = data;
3116 obj->efile.bss_shndx = idx;
3118 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3119 (size_t)sh.sh_size);
3123 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3124 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3125 return -LIBBPF_ERRNO__FORMAT;
3128 /* sort BPF programs by section name and in-section instruction offset
3129 * for faster search */
3130 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3132 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3135 static bool sym_is_extern(const GElf_Sym *sym)
3137 int bind = GELF_ST_BIND(sym->st_info);
3138 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3139 return sym->st_shndx == SHN_UNDEF &&
3140 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3141 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
3144 static bool sym_is_subprog(const GElf_Sym *sym, int text_shndx)
3146 int bind = GELF_ST_BIND(sym->st_info);
3147 int type = GELF_ST_TYPE(sym->st_info);
3149 /* in .text section */
3150 if (sym->st_shndx != text_shndx)
3153 /* local function */
3154 if (bind == STB_LOCAL && type == STT_SECTION)
3157 /* global function */
3158 return bind == STB_GLOBAL && type == STT_FUNC;
3161 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3163 const struct btf_type *t;
3170 n = btf__get_nr_types(btf);
3171 for (i = 1; i <= n; i++) {
3172 t = btf__type_by_id(btf, i);
3174 if (!btf_is_var(t) && !btf_is_func(t))
3177 tname = btf__name_by_offset(btf, t->name_off);
3178 if (strcmp(tname, ext_name))
3181 if (btf_is_var(t) &&
3182 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3185 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3194 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3195 const struct btf_var_secinfo *vs;
3196 const struct btf_type *t;
3202 n = btf__get_nr_types(btf);
3203 for (i = 1; i <= n; i++) {
3204 t = btf__type_by_id(btf, i);
3206 if (!btf_is_datasec(t))
3209 vs = btf_var_secinfos(t);
3210 for (j = 0; j < btf_vlen(t); j++, vs++) {
3211 if (vs->type == ext_btf_id)
3219 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3222 const struct btf_type *t;
3225 t = skip_mods_and_typedefs(btf, id, NULL);
3226 name = btf__name_by_offset(btf, t->name_off);
3230 switch (btf_kind(t)) {
3231 case BTF_KIND_INT: {
3232 int enc = btf_int_encoding(t);
3234 if (enc & BTF_INT_BOOL)
3235 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3237 *is_signed = enc & BTF_INT_SIGNED;
3240 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3241 return KCFG_UNKNOWN;
3246 return KCFG_UNKNOWN;
3247 if (strcmp(name, "libbpf_tristate"))
3248 return KCFG_UNKNOWN;
3249 return KCFG_TRISTATE;
3250 case BTF_KIND_ARRAY:
3251 if (btf_array(t)->nelems == 0)
3252 return KCFG_UNKNOWN;
3253 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3254 return KCFG_UNKNOWN;
3255 return KCFG_CHAR_ARR;
3257 return KCFG_UNKNOWN;
3261 static int cmp_externs(const void *_a, const void *_b)
3263 const struct extern_desc *a = _a;
3264 const struct extern_desc *b = _b;
3266 if (a->type != b->type)
3267 return a->type < b->type ? -1 : 1;
3269 if (a->type == EXT_KCFG) {
3270 /* descending order by alignment requirements */
3271 if (a->kcfg.align != b->kcfg.align)
3272 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3273 /* ascending order by size, within same alignment class */
3274 if (a->kcfg.sz != b->kcfg.sz)
3275 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3278 /* resolve ties by name */
3279 return strcmp(a->name, b->name);
3282 static int find_int_btf_id(const struct btf *btf)
3284 const struct btf_type *t;
3287 n = btf__get_nr_types(btf);
3288 for (i = 1; i <= n; i++) {
3289 t = btf__type_by_id(btf, i);
3291 if (btf_is_int(t) && btf_int_bits(t) == 32)
3298 static int add_dummy_ksym_var(struct btf *btf)
3300 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3301 const struct btf_var_secinfo *vs;
3302 const struct btf_type *sec;
3307 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3312 sec = btf__type_by_id(btf, sec_btf_id);
3313 vs = btf_var_secinfos(sec);
3314 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3315 const struct btf_type *vt;
3317 vt = btf__type_by_id(btf, vs->type);
3318 if (btf_is_func(vt))
3322 /* No func in ksyms sec. No need to add dummy var. */
3323 if (i == btf_vlen(sec))
3326 int_btf_id = find_int_btf_id(btf);
3327 dummy_var_btf_id = btf__add_var(btf,
3329 BTF_VAR_GLOBAL_ALLOCATED,
3331 if (dummy_var_btf_id < 0)
3332 pr_warn("cannot create a dummy_ksym var\n");
3334 return dummy_var_btf_id;
3337 static int bpf_object__collect_externs(struct bpf_object *obj)
3339 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3340 const struct btf_type *t;
3341 struct extern_desc *ext;
3342 int i, n, off, dummy_var_btf_id;
3343 const char *ext_name, *sec_name;
3347 if (!obj->efile.symbols)
3350 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3351 if (elf_sec_hdr(obj, scn, &sh))
3352 return -LIBBPF_ERRNO__FORMAT;
3354 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3355 if (dummy_var_btf_id < 0)
3356 return dummy_var_btf_id;
3358 n = sh.sh_size / sh.sh_entsize;
3359 pr_debug("looking for externs among %d symbols...\n", n);
3361 for (i = 0; i < n; i++) {
3364 if (!gelf_getsym(obj->efile.symbols, i, &sym))
3365 return -LIBBPF_ERRNO__FORMAT;
3366 if (!sym_is_extern(&sym))
3368 ext_name = elf_sym_str(obj, sym.st_name);
3369 if (!ext_name || !ext_name[0])
3373 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3377 ext = &ext[obj->nr_extern];
3378 memset(ext, 0, sizeof(*ext));
3381 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3382 if (ext->btf_id <= 0) {
3383 pr_warn("failed to find BTF for extern '%s': %d\n",
3384 ext_name, ext->btf_id);
3387 t = btf__type_by_id(obj->btf, ext->btf_id);
3388 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3390 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
3392 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3393 if (ext->sec_btf_id <= 0) {
3394 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3395 ext_name, ext->btf_id, ext->sec_btf_id);
3396 return ext->sec_btf_id;
3398 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3399 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3401 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3402 if (btf_is_func(t)) {
3403 pr_warn("extern function %s is unsupported under %s section\n",
3404 ext->name, KCONFIG_SEC);
3408 ext->type = EXT_KCFG;
3409 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3410 if (ext->kcfg.sz <= 0) {
3411 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3412 ext_name, ext->kcfg.sz);
3413 return ext->kcfg.sz;
3415 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3416 if (ext->kcfg.align <= 0) {
3417 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3418 ext_name, ext->kcfg.align);
3421 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3422 &ext->kcfg.is_signed);
3423 if (ext->kcfg.type == KCFG_UNKNOWN) {
3424 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3427 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3428 if (btf_is_func(t) && ext->is_weak) {
3429 pr_warn("extern weak function %s is unsupported\n",
3434 ext->type = EXT_KSYM;
3435 skip_mods_and_typedefs(obj->btf, t->type,
3436 &ext->ksym.type_id);
3438 pr_warn("unrecognized extern section '%s'\n", sec_name);
3442 pr_debug("collected %d externs total\n", obj->nr_extern);
3444 if (!obj->nr_extern)
3447 /* sort externs by type, for kcfg ones also by (align, size, name) */
3448 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3450 /* for .ksyms section, we need to turn all externs into allocated
3451 * variables in BTF to pass kernel verification; we do this by
3452 * pretending that each extern is a 8-byte variable
3455 /* find existing 4-byte integer type in BTF to use for fake
3456 * extern variables in DATASEC
3458 int int_btf_id = find_int_btf_id(obj->btf);
3459 /* For extern function, a dummy_var added earlier
3460 * will be used to replace the vs->type and
3461 * its name string will be used to refill
3462 * the missing param's name.
3464 const struct btf_type *dummy_var;
3466 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3467 for (i = 0; i < obj->nr_extern; i++) {
3468 ext = &obj->externs[i];
3469 if (ext->type != EXT_KSYM)
3471 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3472 i, ext->sym_idx, ext->name);
3477 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3478 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3479 struct btf_type *vt;
3481 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3482 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3483 ext = find_extern_by_name(obj, ext_name);
3485 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3486 btf_kind_str(vt), ext_name);
3489 if (btf_is_func(vt)) {
3490 const struct btf_type *func_proto;
3491 struct btf_param *param;
3494 func_proto = btf__type_by_id(obj->btf,
3496 param = btf_params(func_proto);
3497 /* Reuse the dummy_var string if the
3498 * func proto does not have param name.
3500 for (j = 0; j < btf_vlen(func_proto); j++)
3501 if (param[j].type && !param[j].name_off)
3503 dummy_var->name_off;
3504 vs->type = dummy_var_btf_id;
3505 vt->info &= ~0xffff;
3506 vt->info |= BTF_FUNC_GLOBAL;
3508 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3509 vt->type = int_btf_id;
3512 vs->size = sizeof(int);
3519 /* for kcfg externs calculate their offsets within a .kconfig map */
3521 for (i = 0; i < obj->nr_extern; i++) {
3522 ext = &obj->externs[i];
3523 if (ext->type != EXT_KCFG)
3526 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3527 off = ext->kcfg.data_off + ext->kcfg.sz;
3528 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3529 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3533 for (i = 0; i < n; i++) {
3534 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3536 t = btf__type_by_id(obj->btf, vs->type);
3537 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3538 ext = find_extern_by_name(obj, ext_name);
3540 pr_warn("failed to find extern definition for BTF var '%s'\n",
3544 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3545 vs->offset = ext->kcfg.data_off;
3551 struct bpf_program *
3552 bpf_object__find_program_by_title(const struct bpf_object *obj,
3555 struct bpf_program *pos;
3557 bpf_object__for_each_program(pos, obj) {
3558 if (pos->sec_name && !strcmp(pos->sec_name, title))
3561 return errno = ENOENT, NULL;
3564 static bool prog_is_subprog(const struct bpf_object *obj,
3565 const struct bpf_program *prog)
3567 /* For legacy reasons, libbpf supports an entry-point BPF programs
3568 * without SEC() attribute, i.e., those in the .text section. But if
3569 * there are 2 or more such programs in the .text section, they all
3570 * must be subprograms called from entry-point BPF programs in
3571 * designated SEC()'tions, otherwise there is no way to distinguish
3572 * which of those programs should be loaded vs which are a subprogram.
3573 * Similarly, if there is a function/program in .text and at least one
3574 * other BPF program with custom SEC() attribute, then we just assume
3575 * .text programs are subprograms (even if they are not called from
3576 * other programs), because libbpf never explicitly supported mixing
3577 * SEC()-designated BPF programs and .text entry-point BPF programs.
3579 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3582 struct bpf_program *
3583 bpf_object__find_program_by_name(const struct bpf_object *obj,
3586 struct bpf_program *prog;
3588 bpf_object__for_each_program(prog, obj) {
3589 if (prog_is_subprog(obj, prog))
3591 if (!strcmp(prog->name, name))
3594 return errno = ENOENT, NULL;
3597 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3600 return shndx == obj->efile.data_shndx ||
3601 shndx == obj->efile.bss_shndx ||
3602 shndx == obj->efile.rodata_shndx;
3605 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3608 return shndx == obj->efile.maps_shndx ||
3609 shndx == obj->efile.btf_maps_shndx;
3612 static enum libbpf_map_type
3613 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3615 if (shndx == obj->efile.data_shndx)
3616 return LIBBPF_MAP_DATA;
3617 else if (shndx == obj->efile.bss_shndx)
3618 return LIBBPF_MAP_BSS;
3619 else if (shndx == obj->efile.rodata_shndx)
3620 return LIBBPF_MAP_RODATA;
3621 else if (shndx == obj->efile.symbols_shndx)
3622 return LIBBPF_MAP_KCONFIG;
3624 return LIBBPF_MAP_UNSPEC;
3627 static int bpf_program__record_reloc(struct bpf_program *prog,
3628 struct reloc_desc *reloc_desc,
3629 __u32 insn_idx, const char *sym_name,
3630 const GElf_Sym *sym, const GElf_Rel *rel)
3632 struct bpf_insn *insn = &prog->insns[insn_idx];
3633 size_t map_idx, nr_maps = prog->obj->nr_maps;
3634 struct bpf_object *obj = prog->obj;
3635 __u32 shdr_idx = sym->st_shndx;
3636 enum libbpf_map_type type;
3637 const char *sym_sec_name;
3638 struct bpf_map *map;
3640 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3641 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3642 prog->name, sym_name, insn_idx, insn->code);
3643 return -LIBBPF_ERRNO__RELOC;
3646 if (sym_is_extern(sym)) {
3647 int sym_idx = GELF_R_SYM(rel->r_info);
3648 int i, n = obj->nr_extern;
3649 struct extern_desc *ext;
3651 for (i = 0; i < n; i++) {
3652 ext = &obj->externs[i];
3653 if (ext->sym_idx == sym_idx)
3657 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3658 prog->name, sym_name, sym_idx);
3659 return -LIBBPF_ERRNO__RELOC;
3661 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3662 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3663 if (insn->code == (BPF_JMP | BPF_CALL))
3664 reloc_desc->type = RELO_EXTERN_FUNC;
3666 reloc_desc->type = RELO_EXTERN_VAR;
3667 reloc_desc->insn_idx = insn_idx;
3668 reloc_desc->sym_off = i; /* sym_off stores extern index */
3672 /* sub-program call relocation */
3673 if (is_call_insn(insn)) {
3674 if (insn->src_reg != BPF_PSEUDO_CALL) {
3675 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3676 return -LIBBPF_ERRNO__RELOC;
3678 /* text_shndx can be 0, if no default "main" program exists */
3679 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3680 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3681 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3682 prog->name, sym_name, sym_sec_name);
3683 return -LIBBPF_ERRNO__RELOC;
3685 if (sym->st_value % BPF_INSN_SZ) {
3686 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3687 prog->name, sym_name, (size_t)sym->st_value);
3688 return -LIBBPF_ERRNO__RELOC;
3690 reloc_desc->type = RELO_CALL;
3691 reloc_desc->insn_idx = insn_idx;
3692 reloc_desc->sym_off = sym->st_value;
3696 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3697 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3698 prog->name, sym_name, shdr_idx);
3699 return -LIBBPF_ERRNO__RELOC;
3702 /* loading subprog addresses */
3703 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3704 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3705 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3707 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3708 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3709 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3710 return -LIBBPF_ERRNO__RELOC;
3713 reloc_desc->type = RELO_SUBPROG_ADDR;
3714 reloc_desc->insn_idx = insn_idx;
3715 reloc_desc->sym_off = sym->st_value;
3719 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3720 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3722 /* generic map reference relocation */
3723 if (type == LIBBPF_MAP_UNSPEC) {
3724 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3725 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3726 prog->name, sym_name, sym_sec_name);
3727 return -LIBBPF_ERRNO__RELOC;
3729 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3730 map = &obj->maps[map_idx];
3731 if (map->libbpf_type != type ||
3732 map->sec_idx != sym->st_shndx ||
3733 map->sec_offset != sym->st_value)
3735 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
3736 prog->name, map_idx, map->name, map->sec_idx,
3737 map->sec_offset, insn_idx);
3740 if (map_idx >= nr_maps) {
3741 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
3742 prog->name, sym_sec_name, (size_t)sym->st_value);
3743 return -LIBBPF_ERRNO__RELOC;
3745 reloc_desc->type = RELO_LD64;
3746 reloc_desc->insn_idx = insn_idx;
3747 reloc_desc->map_idx = map_idx;
3748 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3752 /* global data map relocation */
3753 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3754 pr_warn("prog '%s': bad data relo against section '%s'\n",
3755 prog->name, sym_sec_name);
3756 return -LIBBPF_ERRNO__RELOC;
3758 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3759 map = &obj->maps[map_idx];
3760 if (map->libbpf_type != type)
3762 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3763 prog->name, map_idx, map->name, map->sec_idx,
3764 map->sec_offset, insn_idx);
3767 if (map_idx >= nr_maps) {
3768 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
3769 prog->name, sym_sec_name);
3770 return -LIBBPF_ERRNO__RELOC;
3773 reloc_desc->type = RELO_DATA;
3774 reloc_desc->insn_idx = insn_idx;
3775 reloc_desc->map_idx = map_idx;
3776 reloc_desc->sym_off = sym->st_value;
3780 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
3782 return insn_idx >= prog->sec_insn_off &&
3783 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
3786 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
3787 size_t sec_idx, size_t insn_idx)
3789 int l = 0, r = obj->nr_programs - 1, m;
3790 struct bpf_program *prog;
3793 m = l + (r - l + 1) / 2;
3794 prog = &obj->programs[m];
3796 if (prog->sec_idx < sec_idx ||
3797 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
3802 /* matching program could be at index l, but it still might be the
3803 * wrong one, so we need to double check conditions for the last time
3805 prog = &obj->programs[l];
3806 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
3812 bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data)
3814 Elf_Data *symbols = obj->efile.symbols;
3815 const char *relo_sec_name, *sec_name;
3816 size_t sec_idx = shdr->sh_info;
3817 struct bpf_program *prog;
3818 struct reloc_desc *relos;
3820 const char *sym_name;
3827 scn = elf_sec_by_idx(obj, sec_idx);
3828 scn_data = elf_sec_data(obj, scn);
3830 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
3831 sec_name = elf_sec_name(obj, scn);
3832 if (!relo_sec_name || !sec_name)
3835 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
3836 relo_sec_name, sec_idx, sec_name);
3837 nrels = shdr->sh_size / shdr->sh_entsize;
3839 for (i = 0; i < nrels; i++) {
3840 if (!gelf_getrel(data, i, &rel)) {
3841 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
3842 return -LIBBPF_ERRNO__FORMAT;
3844 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3845 pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n",
3846 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3847 return -LIBBPF_ERRNO__FORMAT;
3850 if (rel.r_offset % BPF_INSN_SZ || rel.r_offset >= scn_data->d_size) {
3851 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
3852 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3853 return -LIBBPF_ERRNO__FORMAT;
3856 insn_idx = rel.r_offset / BPF_INSN_SZ;
3857 /* relocations against static functions are recorded as
3858 * relocations against the section that contains a function;
3859 * in such case, symbol will be STT_SECTION and sym.st_name
3860 * will point to empty string (0), so fetch section name
3863 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0)
3864 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx));
3866 sym_name = elf_sym_str(obj, sym.st_name);
3867 sym_name = sym_name ?: "<?";
3869 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
3870 relo_sec_name, i, insn_idx, sym_name);
3872 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
3874 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
3875 relo_sec_name, i, sec_name, insn_idx);
3879 relos = libbpf_reallocarray(prog->reloc_desc,
3880 prog->nr_reloc + 1, sizeof(*relos));
3883 prog->reloc_desc = relos;
3885 /* adjust insn_idx to local BPF program frame of reference */
3886 insn_idx -= prog->sec_insn_off;
3887 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
3888 insn_idx, sym_name, &sym, &rel);
3897 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3899 struct bpf_map_def *def = &map->def;
3900 __u32 key_type_id = 0, value_type_id = 0;
3903 /* if it's BTF-defined map, we don't need to search for type IDs.
3904 * For struct_ops map, it does not need btf_key_type_id and
3905 * btf_value_type_id.
3907 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3908 bpf_map__is_struct_ops(map))
3911 if (!bpf_map__is_internal(map)) {
3912 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3913 def->value_size, &key_type_id,
3917 * LLVM annotates global data differently in BTF, that is,
3918 * only as '.data', '.bss' or '.rodata'.
3920 ret = btf__find_by_name(obj->btf,
3921 libbpf_type_to_btf_name[map->libbpf_type]);
3926 map->btf_key_type_id = key_type_id;
3927 map->btf_value_type_id = bpf_map__is_internal(map) ?
3928 ret : value_type_id;
3932 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
3934 char file[PATH_MAX], buff[4096];
3939 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
3940 memset(info, 0, sizeof(*info));
3942 fp = fopen(file, "r");
3945 pr_warn("failed to open %s: %d. No procfs support?\n", file,
3950 while (fgets(buff, sizeof(buff), fp)) {
3951 if (sscanf(buff, "map_type:\t%u", &val) == 1)
3953 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
3954 info->key_size = val;
3955 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
3956 info->value_size = val;
3957 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
3958 info->max_entries = val;
3959 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
3960 info->map_flags = val;
3968 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3970 struct bpf_map_info info = {};
3971 __u32 len = sizeof(info);
3975 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3976 if (err && errno == EINVAL)
3977 err = bpf_get_map_info_from_fdinfo(fd, &info);
3979 return libbpf_err(err);
3981 new_name = strdup(info.name);
3983 return libbpf_err(-errno);
3985 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3988 goto err_free_new_name;
3991 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3994 goto err_close_new_fd;
3997 err = zclose(map->fd);
4000 goto err_close_new_fd;
4005 map->name = new_name;
4006 map->def.type = info.type;
4007 map->def.key_size = info.key_size;
4008 map->def.value_size = info.value_size;
4009 map->def.max_entries = info.max_entries;
4010 map->def.map_flags = info.map_flags;
4011 map->btf_key_type_id = info.btf_key_type_id;
4012 map->btf_value_type_id = info.btf_value_type_id;
4021 return libbpf_err(err);
4024 __u32 bpf_map__max_entries(const struct bpf_map *map)
4026 return map->def.max_entries;
4029 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4031 if (!bpf_map_type__is_map_in_map(map->def.type))
4032 return errno = EINVAL, NULL;
4034 return map->inner_map;
4037 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4040 return libbpf_err(-EBUSY);
4041 map->def.max_entries = max_entries;
4045 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4047 if (!map || !max_entries)
4048 return libbpf_err(-EINVAL);
4050 return bpf_map__set_max_entries(map, max_entries);
4054 bpf_object__probe_loading(struct bpf_object *obj)
4056 struct bpf_load_program_attr attr;
4057 char *cp, errmsg[STRERR_BUFSIZE];
4058 struct bpf_insn insns[] = {
4059 BPF_MOV64_IMM(BPF_REG_0, 0),
4064 if (obj->gen_loader)
4067 /* make sure basic loading works */
4069 memset(&attr, 0, sizeof(attr));
4070 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4072 attr.insns_cnt = ARRAY_SIZE(insns);
4073 attr.license = "GPL";
4075 ret = bpf_load_program_xattr(&attr, NULL, 0);
4077 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4078 ret = bpf_load_program_xattr(&attr, NULL, 0);
4082 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4083 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4084 "program. Make sure your kernel supports BPF "
4085 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4086 "set to big enough value.\n", __func__, cp, ret);
4094 static int probe_fd(int fd)
4101 static int probe_kern_prog_name(void)
4103 struct bpf_load_program_attr attr;
4104 struct bpf_insn insns[] = {
4105 BPF_MOV64_IMM(BPF_REG_0, 0),
4110 /* make sure loading with name works */
4112 memset(&attr, 0, sizeof(attr));
4113 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4115 attr.insns_cnt = ARRAY_SIZE(insns);
4116 attr.license = "GPL";
4118 ret = bpf_load_program_xattr(&attr, NULL, 0);
4119 return probe_fd(ret);
4122 static int probe_kern_global_data(void)
4124 struct bpf_load_program_attr prg_attr;
4125 struct bpf_create_map_attr map_attr;
4126 char *cp, errmsg[STRERR_BUFSIZE];
4127 struct bpf_insn insns[] = {
4128 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4129 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4130 BPF_MOV64_IMM(BPF_REG_0, 0),
4135 memset(&map_attr, 0, sizeof(map_attr));
4136 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4137 map_attr.key_size = sizeof(int);
4138 map_attr.value_size = 32;
4139 map_attr.max_entries = 1;
4141 map = bpf_create_map_xattr(&map_attr);
4144 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4145 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4146 __func__, cp, -ret);
4152 memset(&prg_attr, 0, sizeof(prg_attr));
4153 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4154 prg_attr.insns = insns;
4155 prg_attr.insns_cnt = ARRAY_SIZE(insns);
4156 prg_attr.license = "GPL";
4158 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
4160 return probe_fd(ret);
4163 static int probe_kern_btf(void)
4165 static const char strs[] = "\0int";
4168 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4171 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4172 strs, sizeof(strs)));
4175 static int probe_kern_btf_func(void)
4177 static const char strs[] = "\0int\0x\0a";
4178 /* void x(int a) {} */
4181 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4182 /* FUNC_PROTO */ /* [2] */
4183 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4184 BTF_PARAM_ENC(7, 1),
4185 /* FUNC x */ /* [3] */
4186 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4189 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4190 strs, sizeof(strs)));
4193 static int probe_kern_btf_func_global(void)
4195 static const char strs[] = "\0int\0x\0a";
4196 /* static void x(int a) {} */
4199 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4200 /* FUNC_PROTO */ /* [2] */
4201 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4202 BTF_PARAM_ENC(7, 1),
4203 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4204 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4207 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4208 strs, sizeof(strs)));
4211 static int probe_kern_btf_datasec(void)
4213 static const char strs[] = "\0x\0.data";
4217 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4218 /* VAR x */ /* [2] */
4219 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4221 /* DATASEC val */ /* [3] */
4222 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4223 BTF_VAR_SECINFO_ENC(2, 0, 4),
4226 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4227 strs, sizeof(strs)));
4230 static int probe_kern_btf_float(void)
4232 static const char strs[] = "\0float";
4235 BTF_TYPE_FLOAT_ENC(1, 4),
4238 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4239 strs, sizeof(strs)));
4242 static int probe_kern_btf_tag(void)
4244 static const char strs[] = "\0tag";
4247 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4248 /* VAR x */ /* [2] */
4249 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4252 BTF_TYPE_TAG_ENC(1, 2, -1),
4255 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4256 strs, sizeof(strs)));
4259 static int probe_kern_array_mmap(void)
4261 struct bpf_create_map_attr attr = {
4262 .map_type = BPF_MAP_TYPE_ARRAY,
4263 .map_flags = BPF_F_MMAPABLE,
4264 .key_size = sizeof(int),
4265 .value_size = sizeof(int),
4269 return probe_fd(bpf_create_map_xattr(&attr));
4272 static int probe_kern_exp_attach_type(void)
4274 struct bpf_load_program_attr attr;
4275 struct bpf_insn insns[] = {
4276 BPF_MOV64_IMM(BPF_REG_0, 0),
4280 memset(&attr, 0, sizeof(attr));
4281 /* use any valid combination of program type and (optional)
4282 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4283 * to see if kernel supports expected_attach_type field for
4284 * BPF_PROG_LOAD command
4286 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
4287 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
4289 attr.insns_cnt = ARRAY_SIZE(insns);
4290 attr.license = "GPL";
4292 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4295 static int probe_kern_probe_read_kernel(void)
4297 struct bpf_load_program_attr attr;
4298 struct bpf_insn insns[] = {
4299 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4300 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4301 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4302 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4303 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4307 memset(&attr, 0, sizeof(attr));
4308 attr.prog_type = BPF_PROG_TYPE_KPROBE;
4310 attr.insns_cnt = ARRAY_SIZE(insns);
4311 attr.license = "GPL";
4313 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4316 static int probe_prog_bind_map(void)
4318 struct bpf_load_program_attr prg_attr;
4319 struct bpf_create_map_attr map_attr;
4320 char *cp, errmsg[STRERR_BUFSIZE];
4321 struct bpf_insn insns[] = {
4322 BPF_MOV64_IMM(BPF_REG_0, 0),
4327 memset(&map_attr, 0, sizeof(map_attr));
4328 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4329 map_attr.key_size = sizeof(int);
4330 map_attr.value_size = 32;
4331 map_attr.max_entries = 1;
4333 map = bpf_create_map_xattr(&map_attr);
4336 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4337 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4338 __func__, cp, -ret);
4342 memset(&prg_attr, 0, sizeof(prg_attr));
4343 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4344 prg_attr.insns = insns;
4345 prg_attr.insns_cnt = ARRAY_SIZE(insns);
4346 prg_attr.license = "GPL";
4348 prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
4354 ret = bpf_prog_bind_map(prog, map, NULL);
4362 static int probe_module_btf(void)
4364 static const char strs[] = "\0int";
4367 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4369 struct bpf_btf_info info;
4370 __u32 len = sizeof(info);
4374 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4376 return 0; /* BTF not supported at all */
4378 memset(&info, 0, sizeof(info));
4379 info.name = ptr_to_u64(name);
4380 info.name_len = sizeof(name);
4382 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4383 * kernel's module BTF support coincides with support for
4384 * name/name_len fields in struct bpf_btf_info.
4386 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4391 static int probe_perf_link(void)
4393 struct bpf_load_program_attr attr;
4394 struct bpf_insn insns[] = {
4395 BPF_MOV64_IMM(BPF_REG_0, 0),
4398 int prog_fd, link_fd, err;
4400 memset(&attr, 0, sizeof(attr));
4401 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4403 attr.insns_cnt = ARRAY_SIZE(insns);
4404 attr.license = "GPL";
4405 prog_fd = bpf_load_program_xattr(&attr, NULL, 0);
4409 /* use invalid perf_event FD to get EBADF, if link is supported;
4410 * otherwise EINVAL should be returned
4412 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4413 err = -errno; /* close() can clobber errno */
4419 return link_fd < 0 && err == -EBADF;
4422 enum kern_feature_result {
4428 typedef int (*feature_probe_fn)(void);
4430 static struct kern_feature_desc {
4432 feature_probe_fn probe;
4433 enum kern_feature_result res;
4434 } feature_probes[__FEAT_CNT] = {
4435 [FEAT_PROG_NAME] = {
4436 "BPF program name", probe_kern_prog_name,
4438 [FEAT_GLOBAL_DATA] = {
4439 "global variables", probe_kern_global_data,
4442 "minimal BTF", probe_kern_btf,
4445 "BTF functions", probe_kern_btf_func,
4447 [FEAT_BTF_GLOBAL_FUNC] = {
4448 "BTF global function", probe_kern_btf_func_global,
4450 [FEAT_BTF_DATASEC] = {
4451 "BTF data section and variable", probe_kern_btf_datasec,
4453 [FEAT_ARRAY_MMAP] = {
4454 "ARRAY map mmap()", probe_kern_array_mmap,
4456 [FEAT_EXP_ATTACH_TYPE] = {
4457 "BPF_PROG_LOAD expected_attach_type attribute",
4458 probe_kern_exp_attach_type,
4460 [FEAT_PROBE_READ_KERN] = {
4461 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4463 [FEAT_PROG_BIND_MAP] = {
4464 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4466 [FEAT_MODULE_BTF] = {
4467 "module BTF support", probe_module_btf,
4469 [FEAT_BTF_FLOAT] = {
4470 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4472 [FEAT_PERF_LINK] = {
4473 "BPF perf link support", probe_perf_link,
4476 "BTF_KIND_TAG support", probe_kern_btf_tag,
4480 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4482 struct kern_feature_desc *feat = &feature_probes[feat_id];
4485 if (obj->gen_loader)
4486 /* To generate loader program assume the latest kernel
4487 * to avoid doing extra prog_load, map_create syscalls.
4491 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4492 ret = feat->probe();
4494 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4495 } else if (ret == 0) {
4496 WRITE_ONCE(feat->res, FEAT_MISSING);
4498 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4499 WRITE_ONCE(feat->res, FEAT_MISSING);
4503 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4506 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4508 struct bpf_map_info map_info = {};
4509 char msg[STRERR_BUFSIZE];
4513 map_info_len = sizeof(map_info);
4515 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4516 if (err && errno == EINVAL)
4517 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4519 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4520 libbpf_strerror_r(errno, msg, sizeof(msg)));
4524 return (map_info.type == map->def.type &&
4525 map_info.key_size == map->def.key_size &&
4526 map_info.value_size == map->def.value_size &&
4527 map_info.max_entries == map->def.max_entries &&
4528 map_info.map_flags == map->def.map_flags);
4532 bpf_object__reuse_map(struct bpf_map *map)
4534 char *cp, errmsg[STRERR_BUFSIZE];
4537 pin_fd = bpf_obj_get(map->pin_path);
4540 if (err == -ENOENT) {
4541 pr_debug("found no pinned map to reuse at '%s'\n",
4546 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4547 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4552 if (!map_is_reuse_compat(map, pin_fd)) {
4553 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4559 err = bpf_map__reuse_fd(map, pin_fd);
4565 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4571 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4573 enum libbpf_map_type map_type = map->libbpf_type;
4574 char *cp, errmsg[STRERR_BUFSIZE];
4577 if (obj->gen_loader) {
4578 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4579 map->mmaped, map->def.value_size);
4580 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4581 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4584 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4587 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4588 pr_warn("Error setting initial map(%s) contents: %s\n",
4593 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4594 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4595 err = bpf_map_freeze(map->fd);
4598 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4599 pr_warn("Error freezing map(%s) as read-only: %s\n",
4607 static void bpf_map__destroy(struct bpf_map *map);
4609 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4611 struct bpf_create_map_attr create_attr;
4612 struct bpf_map_def *def = &map->def;
4615 memset(&create_attr, 0, sizeof(create_attr));
4617 if (kernel_supports(obj, FEAT_PROG_NAME))
4618 create_attr.name = map->name;
4619 create_attr.map_ifindex = map->map_ifindex;
4620 create_attr.map_type = def->type;
4621 create_attr.map_flags = def->map_flags;
4622 create_attr.key_size = def->key_size;
4623 create_attr.value_size = def->value_size;
4624 create_attr.numa_node = map->numa_node;
4626 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4629 nr_cpus = libbpf_num_possible_cpus();
4631 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4632 map->name, nr_cpus);
4635 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4636 create_attr.max_entries = nr_cpus;
4638 create_attr.max_entries = def->max_entries;
4641 if (bpf_map__is_struct_ops(map))
4642 create_attr.btf_vmlinux_value_type_id =
4643 map->btf_vmlinux_value_type_id;
4645 create_attr.btf_fd = 0;
4646 create_attr.btf_key_type_id = 0;
4647 create_attr.btf_value_type_id = 0;
4648 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4649 create_attr.btf_fd = btf__fd(obj->btf);
4650 create_attr.btf_key_type_id = map->btf_key_type_id;
4651 create_attr.btf_value_type_id = map->btf_value_type_id;
4654 if (bpf_map_type__is_map_in_map(def->type)) {
4655 if (map->inner_map) {
4656 err = bpf_object__create_map(obj, map->inner_map, true);
4658 pr_warn("map '%s': failed to create inner map: %d\n",
4662 map->inner_map_fd = bpf_map__fd(map->inner_map);
4664 if (map->inner_map_fd >= 0)
4665 create_attr.inner_map_fd = map->inner_map_fd;
4668 if (obj->gen_loader) {
4669 bpf_gen__map_create(obj->gen_loader, &create_attr, is_inner ? -1 : map - obj->maps);
4670 /* Pretend to have valid FD to pass various fd >= 0 checks.
4671 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4675 map->fd = bpf_create_map_xattr(&create_attr);
4677 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4678 create_attr.btf_value_type_id)) {
4679 char *cp, errmsg[STRERR_BUFSIZE];
4682 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4683 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4684 map->name, cp, err);
4685 create_attr.btf_fd = 0;
4686 create_attr.btf_key_type_id = 0;
4687 create_attr.btf_value_type_id = 0;
4688 map->btf_key_type_id = 0;
4689 map->btf_value_type_id = 0;
4690 map->fd = bpf_create_map_xattr(&create_attr);
4693 err = map->fd < 0 ? -errno : 0;
4695 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4696 if (obj->gen_loader)
4697 map->inner_map->fd = -1;
4698 bpf_map__destroy(map->inner_map);
4699 zfree(&map->inner_map);
4705 static int init_map_slots(struct bpf_object *obj, struct bpf_map *map)
4707 const struct bpf_map *targ_map;
4711 for (i = 0; i < map->init_slots_sz; i++) {
4712 if (!map->init_slots[i])
4715 targ_map = map->init_slots[i];
4716 fd = bpf_map__fd(targ_map);
4717 if (obj->gen_loader) {
4718 pr_warn("// TODO map_update_elem: idx %td key %d value==map_idx %td\n",
4719 map - obj->maps, i, targ_map - obj->maps);
4722 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4726 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4727 map->name, i, targ_map->name,
4731 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4732 map->name, i, targ_map->name, fd);
4735 zfree(&map->init_slots);
4736 map->init_slots_sz = 0;
4742 bpf_object__create_maps(struct bpf_object *obj)
4744 struct bpf_map *map;
4745 char *cp, errmsg[STRERR_BUFSIZE];
4750 for (i = 0; i < obj->nr_maps; i++) {
4751 map = &obj->maps[i];
4755 if (map->pin_path) {
4756 err = bpf_object__reuse_map(map);
4758 pr_warn("map '%s': error reusing pinned map\n",
4762 if (retried && map->fd < 0) {
4763 pr_warn("map '%s': cannot find pinned map\n",
4771 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
4772 map->name, map->fd);
4774 err = bpf_object__create_map(obj, map, false);
4778 pr_debug("map '%s': created successfully, fd=%d\n",
4779 map->name, map->fd);
4781 if (bpf_map__is_internal(map)) {
4782 err = bpf_object__populate_internal_map(obj, map);
4789 if (map->init_slots_sz) {
4790 err = init_map_slots(obj, map);
4798 if (map->pin_path && !map->pinned) {
4799 err = bpf_map__pin(map, NULL);
4802 if (!retried && err == -EEXIST) {
4806 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
4807 map->name, map->pin_path, err);
4816 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4817 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
4819 for (j = 0; j < i; j++)
4820 zclose(obj->maps[j].fd);
4824 static bool bpf_core_is_flavor_sep(const char *s)
4826 /* check X___Y name pattern, where X and Y are not underscores */
4827 return s[0] != '_' && /* X */
4828 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4829 s[4] != '_'; /* Y */
4832 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4833 * before last triple underscore. Struct name part after last triple
4834 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4836 size_t bpf_core_essential_name_len(const char *name)
4838 size_t n = strlen(name);
4841 for (i = n - 5; i >= 0; i--) {
4842 if (bpf_core_is_flavor_sep(name + i))
4848 static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
4854 static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
4855 size_t local_essent_len,
4856 const struct btf *targ_btf,
4857 const char *targ_btf_name,
4859 struct bpf_core_cand_list *cands)
4861 struct bpf_core_cand *new_cands, *cand;
4862 const struct btf_type *t;
4863 const char *targ_name;
4864 size_t targ_essent_len;
4867 n = btf__get_nr_types(targ_btf);
4868 for (i = targ_start_id; i <= n; i++) {
4869 t = btf__type_by_id(targ_btf, i);
4870 if (btf_kind(t) != btf_kind(local_cand->t))
4873 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4874 if (str_is_empty(targ_name))
4877 targ_essent_len = bpf_core_essential_name_len(targ_name);
4878 if (targ_essent_len != local_essent_len)
4881 if (strncmp(local_cand->name, targ_name, local_essent_len) != 0)
4884 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
4885 local_cand->id, btf_kind_str(local_cand->t),
4886 local_cand->name, i, btf_kind_str(t), targ_name,
4888 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
4889 sizeof(*cands->cands));
4893 cand = &new_cands[cands->len];
4894 cand->btf = targ_btf;
4896 cand->name = targ_name;
4899 cands->cands = new_cands;
4905 static int load_module_btfs(struct bpf_object *obj)
4907 struct bpf_btf_info info;
4908 struct module_btf *mod_btf;
4914 if (obj->btf_modules_loaded)
4917 if (obj->gen_loader)
4920 /* don't do this again, even if we find no module BTFs */
4921 obj->btf_modules_loaded = true;
4923 /* kernel too old to support module BTFs */
4924 if (!kernel_supports(obj, FEAT_MODULE_BTF))
4928 err = bpf_btf_get_next_id(id, &id);
4929 if (err && errno == ENOENT)
4933 pr_warn("failed to iterate BTF objects: %d\n", err);
4937 fd = bpf_btf_get_fd_by_id(id);
4939 if (errno == ENOENT)
4940 continue; /* expected race: BTF was unloaded */
4942 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
4947 memset(&info, 0, sizeof(info));
4948 info.name = ptr_to_u64(name);
4949 info.name_len = sizeof(name);
4951 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4954 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
4958 /* ignore non-module BTFs */
4959 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
4964 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
4965 err = libbpf_get_error(btf);
4967 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
4972 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
4973 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4977 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
4982 mod_btf->name = strdup(name);
4983 if (!mod_btf->name) {
4997 static struct bpf_core_cand_list *
4998 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5000 struct bpf_core_cand local_cand = {};
5001 struct bpf_core_cand_list *cands;
5002 const struct btf *main_btf;
5003 size_t local_essent_len;
5006 local_cand.btf = local_btf;
5007 local_cand.t = btf__type_by_id(local_btf, local_type_id);
5009 return ERR_PTR(-EINVAL);
5011 local_cand.name = btf__name_by_offset(local_btf, local_cand.t->name_off);
5012 if (str_is_empty(local_cand.name))
5013 return ERR_PTR(-EINVAL);
5014 local_essent_len = bpf_core_essential_name_len(local_cand.name);
5016 cands = calloc(1, sizeof(*cands));
5018 return ERR_PTR(-ENOMEM);
5020 /* Attempt to find target candidates in vmlinux BTF first */
5021 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5022 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5026 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5030 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5031 if (obj->btf_vmlinux_override)
5034 /* now look through module BTFs, trying to still find candidates */
5035 err = load_module_btfs(obj);
5039 for (i = 0; i < obj->btf_module_cnt; i++) {
5040 err = bpf_core_add_cands(&local_cand, local_essent_len,
5041 obj->btf_modules[i].btf,
5042 obj->btf_modules[i].name,
5043 btf__get_nr_types(obj->btf_vmlinux) + 1,
5051 bpf_core_free_cands(cands);
5052 return ERR_PTR(err);
5055 /* Check local and target types for compatibility. This check is used for
5056 * type-based CO-RE relocations and follow slightly different rules than
5057 * field-based relocations. This function assumes that root types were already
5058 * checked for name match. Beyond that initial root-level name check, names
5059 * are completely ignored. Compatibility rules are as follows:
5060 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5061 * kind should match for local and target types (i.e., STRUCT is not
5062 * compatible with UNION);
5063 * - for ENUMs, the size is ignored;
5064 * - for INT, size and signedness are ignored;
5065 * - for ARRAY, dimensionality is ignored, element types are checked for
5066 * compatibility recursively;
5067 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5068 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5069 * - FUNC_PROTOs are compatible if they have compatible signature: same
5070 * number of input args and compatible return and argument types.
5071 * These rules are not set in stone and probably will be adjusted as we get
5072 * more experience with using BPF CO-RE relocations.
5074 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5075 const struct btf *targ_btf, __u32 targ_id)
5077 const struct btf_type *local_type, *targ_type;
5078 int depth = 32; /* max recursion depth */
5080 /* caller made sure that names match (ignoring flavor suffix) */
5081 local_type = btf__type_by_id(local_btf, local_id);
5082 targ_type = btf__type_by_id(targ_btf, targ_id);
5083 if (btf_kind(local_type) != btf_kind(targ_type))
5091 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5092 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5093 if (!local_type || !targ_type)
5096 if (btf_kind(local_type) != btf_kind(targ_type))
5099 switch (btf_kind(local_type)) {
5101 case BTF_KIND_STRUCT:
5102 case BTF_KIND_UNION:
5107 /* just reject deprecated bitfield-like integers; all other
5108 * integers are by default compatible between each other
5110 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5112 local_id = local_type->type;
5113 targ_id = targ_type->type;
5115 case BTF_KIND_ARRAY:
5116 local_id = btf_array(local_type)->type;
5117 targ_id = btf_array(targ_type)->type;
5119 case BTF_KIND_FUNC_PROTO: {
5120 struct btf_param *local_p = btf_params(local_type);
5121 struct btf_param *targ_p = btf_params(targ_type);
5122 __u16 local_vlen = btf_vlen(local_type);
5123 __u16 targ_vlen = btf_vlen(targ_type);
5126 if (local_vlen != targ_vlen)
5129 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5130 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5131 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5132 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5137 /* tail recurse for return type check */
5138 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5139 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5143 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5144 btf_kind_str(local_type), local_id, targ_id);
5149 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5154 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5159 static void *u32_as_hash_key(__u32 x)
5161 return (void *)(uintptr_t)x;
5164 static int bpf_core_apply_relo(struct bpf_program *prog,
5165 const struct bpf_core_relo *relo,
5167 const struct btf *local_btf,
5168 struct hashmap *cand_cache)
5170 const void *type_key = u32_as_hash_key(relo->type_id);
5171 struct bpf_core_cand_list *cands = NULL;
5172 const char *prog_name = prog->name;
5173 const struct btf_type *local_type;
5174 const char *local_name;
5175 __u32 local_id = relo->type_id;
5176 struct bpf_insn *insn;
5179 if (relo->insn_off % BPF_INSN_SZ)
5181 insn_idx = relo->insn_off / BPF_INSN_SZ;
5182 /* adjust insn_idx from section frame of reference to the local
5183 * program's frame of reference; (sub-)program code is not yet
5184 * relocated, so it's enough to just subtract in-section offset
5186 insn_idx = insn_idx - prog->sec_insn_off;
5187 if (insn_idx > prog->insns_cnt)
5189 insn = &prog->insns[insn_idx];
5191 local_type = btf__type_by_id(local_btf, local_id);
5195 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5199 if (prog->obj->gen_loader) {
5200 pr_warn("// TODO core_relo: prog %td insn[%d] %s kind %d\n",
5201 prog - prog->obj->programs, relo->insn_off / 8,
5202 local_name, relo->kind);
5206 if (relo->kind != BPF_TYPE_ID_LOCAL &&
5207 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5208 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5209 if (IS_ERR(cands)) {
5210 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5211 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5212 local_name, PTR_ERR(cands));
5213 return PTR_ERR(cands);
5215 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5217 bpf_core_free_cands(cands);
5222 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo, relo_idx, local_btf, cands);
5226 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5228 const struct btf_ext_info_sec *sec;
5229 const struct bpf_core_relo *rec;
5230 const struct btf_ext_info *seg;
5231 struct hashmap_entry *entry;
5232 struct hashmap *cand_cache = NULL;
5233 struct bpf_program *prog;
5234 const char *sec_name;
5235 int i, err = 0, insn_idx, sec_idx;
5237 if (obj->btf_ext->core_relo_info.len == 0)
5240 if (targ_btf_path) {
5241 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5242 err = libbpf_get_error(obj->btf_vmlinux_override);
5244 pr_warn("failed to parse target BTF: %d\n", err);
5249 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5250 if (IS_ERR(cand_cache)) {
5251 err = PTR_ERR(cand_cache);
5255 seg = &obj->btf_ext->core_relo_info;
5256 for_each_btf_ext_sec(seg, sec) {
5257 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5258 if (str_is_empty(sec_name)) {
5262 /* bpf_object's ELF is gone by now so it's not easy to find
5263 * section index by section name, but we can find *any*
5264 * bpf_program within desired section name and use it's
5265 * prog->sec_idx to do a proper search by section index and
5266 * instruction offset
5269 for (i = 0; i < obj->nr_programs; i++) {
5270 prog = &obj->programs[i];
5271 if (strcmp(prog->sec_name, sec_name) == 0)
5275 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5278 sec_idx = prog->sec_idx;
5280 pr_debug("sec '%s': found %d CO-RE relocations\n",
5281 sec_name, sec->num_info);
5283 for_each_btf_ext_rec(seg, sec, i, rec) {
5284 insn_idx = rec->insn_off / BPF_INSN_SZ;
5285 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5287 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5288 sec_name, insn_idx, i);
5292 /* no need to apply CO-RE relocation if the program is
5293 * not going to be loaded
5298 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
5300 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5301 prog->name, i, err);
5308 /* obj->btf_vmlinux and module BTFs are freed after object load */
5309 btf__free(obj->btf_vmlinux_override);
5310 obj->btf_vmlinux_override = NULL;
5312 if (!IS_ERR_OR_NULL(cand_cache)) {
5313 hashmap__for_each_entry(cand_cache, entry, i) {
5314 bpf_core_free_cands(entry->value);
5316 hashmap__free(cand_cache);
5321 /* Relocate data references within program code:
5323 * - global variable references;
5324 * - extern references.
5327 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5331 for (i = 0; i < prog->nr_reloc; i++) {
5332 struct reloc_desc *relo = &prog->reloc_desc[i];
5333 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5334 struct extern_desc *ext;
5336 switch (relo->type) {
5338 if (obj->gen_loader) {
5339 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5340 insn[0].imm = relo->map_idx;
5342 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5343 insn[0].imm = obj->maps[relo->map_idx].fd;
5347 insn[1].imm = insn[0].imm + relo->sym_off;
5348 if (obj->gen_loader) {
5349 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5350 insn[0].imm = relo->map_idx;
5352 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5353 insn[0].imm = obj->maps[relo->map_idx].fd;
5356 case RELO_EXTERN_VAR:
5357 ext = &obj->externs[relo->sym_off];
5358 if (ext->type == EXT_KCFG) {
5359 if (obj->gen_loader) {
5360 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5361 insn[0].imm = obj->kconfig_map_idx;
5363 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5364 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5366 insn[1].imm = ext->kcfg.data_off;
5367 } else /* EXT_KSYM */ {
5368 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5369 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5370 insn[0].imm = ext->ksym.kernel_btf_id;
5371 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5372 } else { /* typeless ksyms or unresolved typed ksyms */
5373 insn[0].imm = (__u32)ext->ksym.addr;
5374 insn[1].imm = ext->ksym.addr >> 32;
5378 case RELO_EXTERN_FUNC:
5379 ext = &obj->externs[relo->sym_off];
5380 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5381 insn[0].imm = ext->ksym.kernel_btf_id;
5383 case RELO_SUBPROG_ADDR:
5384 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5385 pr_warn("prog '%s': relo #%d: bad insn\n",
5389 /* handled already */
5392 /* handled already */
5395 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5396 prog->name, i, relo->type);
5404 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5405 const struct bpf_program *prog,
5406 const struct btf_ext_info *ext_info,
5407 void **prog_info, __u32 *prog_rec_cnt,
5410 void *copy_start = NULL, *copy_end = NULL;
5411 void *rec, *rec_end, *new_prog_info;
5412 const struct btf_ext_info_sec *sec;
5413 size_t old_sz, new_sz;
5414 const char *sec_name;
5417 for_each_btf_ext_sec(ext_info, sec) {
5418 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5421 if (strcmp(sec_name, prog->sec_name) != 0)
5424 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5425 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5427 if (insn_off < prog->sec_insn_off)
5429 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5434 copy_end = rec + ext_info->rec_size;
5440 /* append func/line info of a given (sub-)program to the main
5441 * program func/line info
5443 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5444 new_sz = old_sz + (copy_end - copy_start);
5445 new_prog_info = realloc(*prog_info, new_sz);
5448 *prog_info = new_prog_info;
5449 *prog_rec_cnt = new_sz / ext_info->rec_size;
5450 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5452 /* Kernel instruction offsets are in units of 8-byte
5453 * instructions, while .BTF.ext instruction offsets generated
5454 * by Clang are in units of bytes. So convert Clang offsets
5455 * into kernel offsets and adjust offset according to program
5456 * relocated position.
5458 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5459 rec = new_prog_info + old_sz;
5460 rec_end = new_prog_info + new_sz;
5461 for (; rec < rec_end; rec += ext_info->rec_size) {
5462 __u32 *insn_off = rec;
5464 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5466 *prog_rec_sz = ext_info->rec_size;
5474 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5475 struct bpf_program *main_prog,
5476 const struct bpf_program *prog)
5480 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5481 * supprot func/line info
5483 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5486 /* only attempt func info relocation if main program's func_info
5487 * relocation was successful
5489 if (main_prog != prog && !main_prog->func_info)
5492 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5493 &main_prog->func_info,
5494 &main_prog->func_info_cnt,
5495 &main_prog->func_info_rec_size);
5497 if (err != -ENOENT) {
5498 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5502 if (main_prog->func_info) {
5504 * Some info has already been found but has problem
5505 * in the last btf_ext reloc. Must have to error out.
5507 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5510 /* Have problem loading the very first info. Ignore the rest. */
5511 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5516 /* don't relocate line info if main program's relocation failed */
5517 if (main_prog != prog && !main_prog->line_info)
5520 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5521 &main_prog->line_info,
5522 &main_prog->line_info_cnt,
5523 &main_prog->line_info_rec_size);
5525 if (err != -ENOENT) {
5526 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5530 if (main_prog->line_info) {
5532 * Some info has already been found but has problem
5533 * in the last btf_ext reloc. Must have to error out.
5535 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5538 /* Have problem loading the very first info. Ignore the rest. */
5539 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5545 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5547 size_t insn_idx = *(const size_t *)key;
5548 const struct reloc_desc *relo = elem;
5550 if (insn_idx == relo->insn_idx)
5552 return insn_idx < relo->insn_idx ? -1 : 1;
5555 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5557 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5558 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5561 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5563 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5564 struct reloc_desc *relos;
5567 if (main_prog == subprog)
5569 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5572 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5573 sizeof(*relos) * subprog->nr_reloc);
5575 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5576 relos[i].insn_idx += subprog->sub_insn_off;
5577 /* After insn_idx adjustment the 'relos' array is still sorted
5578 * by insn_idx and doesn't break bsearch.
5580 main_prog->reloc_desc = relos;
5581 main_prog->nr_reloc = new_cnt;
5586 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5587 struct bpf_program *prog)
5589 size_t sub_insn_idx, insn_idx, new_cnt;
5590 struct bpf_program *subprog;
5591 struct bpf_insn *insns, *insn;
5592 struct reloc_desc *relo;
5595 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5599 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5600 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5601 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
5604 relo = find_prog_insn_relo(prog, insn_idx);
5605 if (relo && relo->type == RELO_EXTERN_FUNC)
5606 /* kfunc relocations will be handled later
5607 * in bpf_object__relocate_data()
5610 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
5611 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
5612 prog->name, insn_idx, relo->type);
5613 return -LIBBPF_ERRNO__RELOC;
5616 /* sub-program instruction index is a combination of
5617 * an offset of a symbol pointed to by relocation and
5618 * call instruction's imm field; for global functions,
5619 * call always has imm = -1, but for static functions
5620 * relocation is against STT_SECTION and insn->imm
5621 * points to a start of a static function
5623 * for subprog addr relocation, the relo->sym_off + insn->imm is
5624 * the byte offset in the corresponding section.
5626 if (relo->type == RELO_CALL)
5627 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
5629 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
5630 } else if (insn_is_pseudo_func(insn)) {
5632 * RELO_SUBPROG_ADDR relo is always emitted even if both
5633 * functions are in the same section, so it shouldn't reach here.
5635 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
5636 prog->name, insn_idx);
5637 return -LIBBPF_ERRNO__RELOC;
5639 /* if subprogram call is to a static function within
5640 * the same ELF section, there won't be any relocation
5641 * emitted, but it also means there is no additional
5642 * offset necessary, insns->imm is relative to
5643 * instruction's original position within the section
5645 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
5648 /* we enforce that sub-programs should be in .text section */
5649 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
5651 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
5653 return -LIBBPF_ERRNO__RELOC;
5656 /* if it's the first call instruction calling into this
5657 * subprogram (meaning this subprog hasn't been processed
5658 * yet) within the context of current main program:
5659 * - append it at the end of main program's instructions blog;
5660 * - process is recursively, while current program is put on hold;
5661 * - if that subprogram calls some other not yet processes
5662 * subprogram, same thing will happen recursively until
5663 * there are no more unprocesses subprograms left to append
5666 if (subprog->sub_insn_off == 0) {
5667 subprog->sub_insn_off = main_prog->insns_cnt;
5669 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
5670 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
5672 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
5675 main_prog->insns = insns;
5676 main_prog->insns_cnt = new_cnt;
5678 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
5679 subprog->insns_cnt * sizeof(*insns));
5681 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
5682 main_prog->name, subprog->insns_cnt, subprog->name);
5684 /* The subprog insns are now appended. Append its relos too. */
5685 err = append_subprog_relos(main_prog, subprog);
5688 err = bpf_object__reloc_code(obj, main_prog, subprog);
5693 /* main_prog->insns memory could have been re-allocated, so
5694 * calculate pointer again
5696 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5697 /* calculate correct instruction position within current main
5698 * prog; each main prog can have a different set of
5699 * subprograms appended (potentially in different order as
5700 * well), so position of any subprog can be different for
5701 * different main programs */
5702 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
5704 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
5705 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
5712 * Relocate sub-program calls.
5714 * Algorithm operates as follows. Each entry-point BPF program (referred to as
5715 * main prog) is processed separately. For each subprog (non-entry functions,
5716 * that can be called from either entry progs or other subprogs) gets their
5717 * sub_insn_off reset to zero. This serves as indicator that this subprogram
5718 * hasn't been yet appended and relocated within current main prog. Once its
5719 * relocated, sub_insn_off will point at the position within current main prog
5720 * where given subprog was appended. This will further be used to relocate all
5721 * the call instructions jumping into this subprog.
5723 * We start with main program and process all call instructions. If the call
5724 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
5725 * is zero), subprog instructions are appended at the end of main program's
5726 * instruction array. Then main program is "put on hold" while we recursively
5727 * process newly appended subprogram. If that subprogram calls into another
5728 * subprogram that hasn't been appended, new subprogram is appended again to
5729 * the *main* prog's instructions (subprog's instructions are always left
5730 * untouched, as they need to be in unmodified state for subsequent main progs
5731 * and subprog instructions are always sent only as part of a main prog) and
5732 * the process continues recursively. Once all the subprogs called from a main
5733 * prog or any of its subprogs are appended (and relocated), all their
5734 * positions within finalized instructions array are known, so it's easy to
5735 * rewrite call instructions with correct relative offsets, corresponding to
5736 * desired target subprog.
5738 * Its important to realize that some subprogs might not be called from some
5739 * main prog and any of its called/used subprogs. Those will keep their
5740 * subprog->sub_insn_off as zero at all times and won't be appended to current
5741 * main prog and won't be relocated within the context of current main prog.
5742 * They might still be used from other main progs later.
5744 * Visually this process can be shown as below. Suppose we have two main
5745 * programs mainA and mainB and BPF object contains three subprogs: subA,
5746 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
5747 * subC both call subB:
5749 * +--------+ +-------+
5751 * +--+---+ +--+-+-+ +---+--+
5752 * | subA | | subB | | subC |
5753 * +--+---+ +------+ +---+--+
5756 * +---+-------+ +------+----+
5757 * | mainA | | mainB |
5758 * +-----------+ +-----------+
5760 * We'll start relocating mainA, will find subA, append it and start
5761 * processing sub A recursively:
5763 * +-----------+------+
5765 * +-----------+------+
5767 * At this point we notice that subB is used from subA, so we append it and
5768 * relocate (there are no further subcalls from subB):
5770 * +-----------+------+------+
5771 * | mainA | subA | subB |
5772 * +-----------+------+------+
5774 * At this point, we relocate subA calls, then go one level up and finish with
5775 * relocatin mainA calls. mainA is done.
5777 * For mainB process is similar but results in different order. We start with
5778 * mainB and skip subA and subB, as mainB never calls them (at least
5779 * directly), but we see subC is needed, so we append and start processing it:
5781 * +-----------+------+
5783 * +-----------+------+
5784 * Now we see subC needs subB, so we go back to it, append and relocate it:
5786 * +-----------+------+------+
5787 * | mainB | subC | subB |
5788 * +-----------+------+------+
5790 * At this point we unwind recursion, relocate calls in subC, then in mainB.
5793 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
5795 struct bpf_program *subprog;
5798 /* mark all subprogs as not relocated (yet) within the context of
5799 * current main program
5801 for (i = 0; i < obj->nr_programs; i++) {
5802 subprog = &obj->programs[i];
5803 if (!prog_is_subprog(obj, subprog))
5806 subprog->sub_insn_off = 0;
5809 err = bpf_object__reloc_code(obj, prog, prog);
5818 bpf_object__free_relocs(struct bpf_object *obj)
5820 struct bpf_program *prog;
5823 /* free up relocation descriptors */
5824 for (i = 0; i < obj->nr_programs; i++) {
5825 prog = &obj->programs[i];
5826 zfree(&prog->reloc_desc);
5832 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
5834 struct bpf_program *prog;
5839 err = bpf_object__relocate_core(obj, targ_btf_path);
5841 pr_warn("failed to perform CO-RE relocations: %d\n",
5847 /* Before relocating calls pre-process relocations and mark
5848 * few ld_imm64 instructions that points to subprogs.
5849 * Otherwise bpf_object__reloc_code() later would have to consider
5850 * all ld_imm64 insns as relocation candidates. That would
5851 * reduce relocation speed, since amount of find_prog_insn_relo()
5852 * would increase and most of them will fail to find a relo.
5854 for (i = 0; i < obj->nr_programs; i++) {
5855 prog = &obj->programs[i];
5856 for (j = 0; j < prog->nr_reloc; j++) {
5857 struct reloc_desc *relo = &prog->reloc_desc[j];
5858 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5860 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
5861 if (relo->type == RELO_SUBPROG_ADDR)
5862 insn[0].src_reg = BPF_PSEUDO_FUNC;
5866 /* relocate subprogram calls and append used subprograms to main
5867 * programs; each copy of subprogram code needs to be relocated
5868 * differently for each main program, because its code location might
5870 * Append subprog relos to main programs to allow data relos to be
5871 * processed after text is completely relocated.
5873 for (i = 0; i < obj->nr_programs; i++) {
5874 prog = &obj->programs[i];
5875 /* sub-program's sub-calls are relocated within the context of
5876 * its main program only
5878 if (prog_is_subprog(obj, prog))
5881 err = bpf_object__relocate_calls(obj, prog);
5883 pr_warn("prog '%s': failed to relocate calls: %d\n",
5888 /* Process data relos for main programs */
5889 for (i = 0; i < obj->nr_programs; i++) {
5890 prog = &obj->programs[i];
5891 if (prog_is_subprog(obj, prog))
5893 err = bpf_object__relocate_data(obj, prog);
5895 pr_warn("prog '%s': failed to relocate data references: %d\n",
5900 if (!obj->gen_loader)
5901 bpf_object__free_relocs(obj);
5905 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5906 GElf_Shdr *shdr, Elf_Data *data);
5908 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5909 GElf_Shdr *shdr, Elf_Data *data)
5911 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
5912 int i, j, nrels, new_sz;
5913 const struct btf_var_secinfo *vi = NULL;
5914 const struct btf_type *sec, *var, *def;
5915 struct bpf_map *map = NULL, *targ_map;
5916 const struct btf_member *member;
5917 const char *name, *mname;
5924 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5926 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5930 symbols = obj->efile.symbols;
5931 nrels = shdr->sh_size / shdr->sh_entsize;
5932 for (i = 0; i < nrels; i++) {
5933 if (!gelf_getrel(data, i, &rel)) {
5934 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5935 return -LIBBPF_ERRNO__FORMAT;
5937 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5938 pr_warn(".maps relo #%d: symbol %zx not found\n",
5939 i, (size_t)GELF_R_SYM(rel.r_info));
5940 return -LIBBPF_ERRNO__FORMAT;
5942 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
5943 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5944 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5946 return -LIBBPF_ERRNO__RELOC;
5949 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5950 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5951 (size_t)rel.r_offset, sym.st_name, name);
5953 for (j = 0; j < obj->nr_maps; j++) {
5954 map = &obj->maps[j];
5955 if (map->sec_idx != obj->efile.btf_maps_shndx)
5958 vi = btf_var_secinfos(sec) + map->btf_var_idx;
5959 if (vi->offset <= rel.r_offset &&
5960 rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
5963 if (j == obj->nr_maps) {
5964 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5965 i, name, (size_t)rel.r_offset);
5969 if (!bpf_map_type__is_map_in_map(map->def.type))
5971 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5972 map->def.key_size != sizeof(int)) {
5973 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5974 i, map->name, sizeof(int));
5978 targ_map = bpf_object__find_map_by_name(obj, name);
5982 var = btf__type_by_id(obj->btf, vi->type);
5983 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5984 if (btf_vlen(def) == 0)
5986 member = btf_members(def) + btf_vlen(def) - 1;
5987 mname = btf__name_by_offset(obj->btf, member->name_off);
5988 if (strcmp(mname, "values"))
5991 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5992 if (rel.r_offset - vi->offset < moff)
5995 moff = rel.r_offset - vi->offset - moff;
5996 /* here we use BPF pointer size, which is always 64 bit, as we
5997 * are parsing ELF that was built for BPF target
5999 if (moff % bpf_ptr_sz)
6002 if (moff >= map->init_slots_sz) {
6004 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6007 map->init_slots = tmp;
6008 memset(map->init_slots + map->init_slots_sz, 0,
6009 (new_sz - map->init_slots_sz) * host_ptr_sz);
6010 map->init_slots_sz = new_sz;
6012 map->init_slots[moff] = targ_map;
6014 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
6015 i, map->name, moff, name);
6021 static int cmp_relocs(const void *_a, const void *_b)
6023 const struct reloc_desc *a = _a;
6024 const struct reloc_desc *b = _b;
6026 if (a->insn_idx != b->insn_idx)
6027 return a->insn_idx < b->insn_idx ? -1 : 1;
6029 /* no two relocations should have the same insn_idx, but ... */
6030 if (a->type != b->type)
6031 return a->type < b->type ? -1 : 1;
6036 static int bpf_object__collect_relos(struct bpf_object *obj)
6040 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
6041 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
6042 Elf_Data *data = obj->efile.reloc_sects[i].data;
6043 int idx = shdr->sh_info;
6045 if (shdr->sh_type != SHT_REL) {
6046 pr_warn("internal error at %d\n", __LINE__);
6047 return -LIBBPF_ERRNO__INTERNAL;
6050 if (idx == obj->efile.st_ops_shndx)
6051 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6052 else if (idx == obj->efile.btf_maps_shndx)
6053 err = bpf_object__collect_map_relos(obj, shdr, data);
6055 err = bpf_object__collect_prog_relos(obj, shdr, data);
6060 for (i = 0; i < obj->nr_programs; i++) {
6061 struct bpf_program *p = &obj->programs[i];
6066 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6071 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6073 if (BPF_CLASS(insn->code) == BPF_JMP &&
6074 BPF_OP(insn->code) == BPF_CALL &&
6075 BPF_SRC(insn->code) == BPF_K &&
6076 insn->src_reg == 0 &&
6077 insn->dst_reg == 0) {
6078 *func_id = insn->imm;
6084 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6086 struct bpf_insn *insn = prog->insns;
6087 enum bpf_func_id func_id;
6090 if (obj->gen_loader)
6093 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6094 if (!insn_is_helper_call(insn, &func_id))
6097 /* on kernels that don't yet support
6098 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6099 * to bpf_probe_read() which works well for old kernels
6102 case BPF_FUNC_probe_read_kernel:
6103 case BPF_FUNC_probe_read_user:
6104 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6105 insn->imm = BPF_FUNC_probe_read;
6107 case BPF_FUNC_probe_read_kernel_str:
6108 case BPF_FUNC_probe_read_user_str:
6109 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6110 insn->imm = BPF_FUNC_probe_read_str;
6119 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6120 int *btf_obj_fd, int *btf_type_id);
6122 /* this is called as prog->sec_def->preload_fn for libbpf-supported sec_defs */
6123 static int libbpf_preload_prog(struct bpf_program *prog,
6124 struct bpf_prog_load_params *attr, long cookie)
6126 enum sec_def_flags def = cookie;
6128 /* old kernels might not support specifying expected_attach_type */
6129 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6130 attr->expected_attach_type = 0;
6132 if (def & SEC_SLEEPABLE)
6133 attr->prog_flags |= BPF_F_SLEEPABLE;
6135 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6136 prog->type == BPF_PROG_TYPE_LSM ||
6137 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6138 int btf_obj_fd = 0, btf_type_id = 0, err;
6139 const char *attach_name;
6141 attach_name = strchr(prog->sec_name, '/') + 1;
6142 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6146 /* cache resolved BTF FD and BTF type ID in the prog */
6147 prog->attach_btf_obj_fd = btf_obj_fd;
6148 prog->attach_btf_id = btf_type_id;
6150 /* but by now libbpf common logic is not utilizing
6151 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6152 * this callback is called after attrs were populated by
6153 * libbpf, so this callback has to update attr explicitly here
6155 attr->attach_btf_obj_fd = btf_obj_fd;
6156 attr->attach_btf_id = btf_type_id;
6162 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
6163 char *license, __u32 kern_version, int *pfd)
6165 struct bpf_prog_load_params load_attr = {};
6166 char *cp, errmsg[STRERR_BUFSIZE];
6167 size_t log_buf_size = 0;
6168 char *log_buf = NULL;
6169 int btf_fd, ret, err;
6171 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6173 * The program type must be set. Most likely we couldn't find a proper
6174 * section definition at load time, and thus we didn't infer the type.
6176 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6177 prog->name, prog->sec_name);
6181 if (!insns || !insns_cnt)
6184 load_attr.prog_type = prog->type;
6185 load_attr.expected_attach_type = prog->expected_attach_type;
6186 if (kernel_supports(prog->obj, FEAT_PROG_NAME))
6187 load_attr.name = prog->name;
6188 load_attr.insns = insns;
6189 load_attr.insn_cnt = insns_cnt;
6190 load_attr.license = license;
6191 load_attr.attach_btf_id = prog->attach_btf_id;
6192 load_attr.attach_prog_fd = prog->attach_prog_fd;
6193 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6194 load_attr.attach_btf_id = prog->attach_btf_id;
6195 load_attr.kern_version = kern_version;
6196 load_attr.prog_ifindex = prog->prog_ifindex;
6198 /* specify func_info/line_info only if kernel supports them */
6199 btf_fd = bpf_object__btf_fd(prog->obj);
6200 if (btf_fd >= 0 && kernel_supports(prog->obj, FEAT_BTF_FUNC)) {
6201 load_attr.prog_btf_fd = btf_fd;
6202 load_attr.func_info = prog->func_info;
6203 load_attr.func_info_rec_size = prog->func_info_rec_size;
6204 load_attr.func_info_cnt = prog->func_info_cnt;
6205 load_attr.line_info = prog->line_info;
6206 load_attr.line_info_rec_size = prog->line_info_rec_size;
6207 load_attr.line_info_cnt = prog->line_info_cnt;
6209 load_attr.log_level = prog->log_level;
6210 load_attr.prog_flags = prog->prog_flags;
6212 /* adjust load_attr if sec_def provides custom preload callback */
6213 if (prog->sec_def && prog->sec_def->preload_fn) {
6214 err = prog->sec_def->preload_fn(prog, &load_attr, prog->sec_def->cookie);
6216 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6222 if (prog->obj->gen_loader) {
6223 bpf_gen__prog_load(prog->obj->gen_loader, &load_attr,
6224 prog - prog->obj->programs);
6230 log_buf = malloc(log_buf_size);
6237 load_attr.log_buf = log_buf;
6238 load_attr.log_buf_sz = log_buf_size;
6239 ret = libbpf__bpf_prog_load(&load_attr);
6242 if (log_buf && load_attr.log_level)
6243 pr_debug("verifier log:\n%s", log_buf);
6245 if (prog->obj->rodata_map_idx >= 0 &&
6246 kernel_supports(prog->obj, FEAT_PROG_BIND_MAP)) {
6247 struct bpf_map *rodata_map =
6248 &prog->obj->maps[prog->obj->rodata_map_idx];
6250 if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) {
6251 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6252 pr_warn("prog '%s': failed to bind .rodata map: %s\n",
6254 /* Don't fail hard if can't bind rodata. */
6263 if (!log_buf || errno == ENOSPC) {
6264 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
6270 ret = errno ? -errno : -LIBBPF_ERRNO__LOAD;
6271 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6272 pr_warn("load bpf program failed: %s\n", cp);
6275 if (log_buf && log_buf[0] != '\0') {
6276 ret = -LIBBPF_ERRNO__VERIFY;
6277 pr_warn("-- BEGIN DUMP LOG ---\n");
6278 pr_warn("\n%s\n", log_buf);
6279 pr_warn("-- END LOG --\n");
6280 } else if (load_attr.insn_cnt >= BPF_MAXINSNS) {
6281 pr_warn("Program too large (%zu insns), at most %d insns\n",
6282 load_attr.insn_cnt, BPF_MAXINSNS);
6283 ret = -LIBBPF_ERRNO__PROG2BIG;
6284 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
6285 /* Wrong program type? */
6288 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
6289 load_attr.expected_attach_type = 0;
6290 load_attr.log_buf = NULL;
6291 load_attr.log_buf_sz = 0;
6292 fd = libbpf__bpf_prog_load(&load_attr);
6295 ret = -LIBBPF_ERRNO__PROGTYPE;
6305 static int bpf_program__record_externs(struct bpf_program *prog)
6307 struct bpf_object *obj = prog->obj;
6310 for (i = 0; i < prog->nr_reloc; i++) {
6311 struct reloc_desc *relo = &prog->reloc_desc[i];
6312 struct extern_desc *ext = &obj->externs[relo->sym_off];
6314 switch (relo->type) {
6315 case RELO_EXTERN_VAR:
6316 if (ext->type != EXT_KSYM)
6318 if (!ext->ksym.type_id) {
6319 pr_warn("typeless ksym %s is not supported yet\n",
6323 bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_VAR,
6326 case RELO_EXTERN_FUNC:
6327 bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_FUNC,
6337 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
6341 if (prog->obj->loaded) {
6342 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6343 return libbpf_err(-EINVAL);
6346 if (prog->instances.nr < 0 || !prog->instances.fds) {
6347 if (prog->preprocessor) {
6348 pr_warn("Internal error: can't load program '%s'\n",
6350 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
6353 prog->instances.fds = malloc(sizeof(int));
6354 if (!prog->instances.fds) {
6355 pr_warn("Not enough memory for BPF fds\n");
6356 return libbpf_err(-ENOMEM);
6358 prog->instances.nr = 1;
6359 prog->instances.fds[0] = -1;
6362 if (!prog->preprocessor) {
6363 if (prog->instances.nr != 1) {
6364 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6365 prog->name, prog->instances.nr);
6367 if (prog->obj->gen_loader)
6368 bpf_program__record_externs(prog);
6369 err = load_program(prog, prog->insns, prog->insns_cnt,
6370 license, kern_ver, &fd);
6372 prog->instances.fds[0] = fd;
6376 for (i = 0; i < prog->instances.nr; i++) {
6377 struct bpf_prog_prep_result result;
6378 bpf_program_prep_t preprocessor = prog->preprocessor;
6380 memset(&result, 0, sizeof(result));
6381 err = preprocessor(prog, i, prog->insns,
6382 prog->insns_cnt, &result);
6384 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6389 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6390 pr_debug("Skip loading the %dth instance of program '%s'\n",
6392 prog->instances.fds[i] = -1;
6398 err = load_program(prog, result.new_insn_ptr,
6399 result.new_insn_cnt, license, kern_ver, &fd);
6401 pr_warn("Loading the %dth instance of program '%s' failed\n",
6408 prog->instances.fds[i] = fd;
6412 pr_warn("failed to load program '%s'\n", prog->name);
6413 zfree(&prog->insns);
6414 prog->insns_cnt = 0;
6415 return libbpf_err(err);
6419 bpf_object__load_progs(struct bpf_object *obj, int log_level)
6421 struct bpf_program *prog;
6425 for (i = 0; i < obj->nr_programs; i++) {
6426 prog = &obj->programs[i];
6427 err = bpf_object__sanitize_prog(obj, prog);
6432 for (i = 0; i < obj->nr_programs; i++) {
6433 prog = &obj->programs[i];
6434 if (prog_is_subprog(obj, prog))
6437 pr_debug("prog '%s': skipped loading\n", prog->name);
6440 prog->log_level |= log_level;
6441 err = bpf_program__load(prog, obj->license, obj->kern_version);
6445 if (obj->gen_loader)
6446 bpf_object__free_relocs(obj);
6450 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6452 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
6454 struct bpf_program *prog;
6457 bpf_object__for_each_program(prog, obj) {
6458 prog->sec_def = find_sec_def(prog->sec_name);
6459 if (!prog->sec_def) {
6460 /* couldn't guess, but user might manually specify */
6461 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6462 prog->name, prog->sec_name);
6466 bpf_program__set_type(prog, prog->sec_def->prog_type);
6467 bpf_program__set_expected_attach_type(prog, prog->sec_def->expected_attach_type);
6469 #pragma GCC diagnostic push
6470 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
6471 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6472 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6473 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6474 #pragma GCC diagnostic pop
6476 /* sec_def can have custom callback which should be called
6477 * after bpf_program is initialized to adjust its properties
6479 if (prog->sec_def->init_fn) {
6480 err = prog->sec_def->init_fn(prog, prog->sec_def->cookie);
6482 pr_warn("prog '%s': failed to initialize: %d\n",
6492 static struct bpf_object *
6493 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6494 const struct bpf_object_open_opts *opts)
6496 const char *obj_name, *kconfig, *btf_tmp_path;
6497 struct bpf_object *obj;
6501 if (elf_version(EV_CURRENT) == EV_NONE) {
6502 pr_warn("failed to init libelf for %s\n",
6503 path ? : "(mem buf)");
6504 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6507 if (!OPTS_VALID(opts, bpf_object_open_opts))
6508 return ERR_PTR(-EINVAL);
6510 obj_name = OPTS_GET(opts, object_name, NULL);
6513 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6514 (unsigned long)obj_buf,
6515 (unsigned long)obj_buf_sz);
6516 obj_name = tmp_name;
6519 pr_debug("loading object '%s' from buffer\n", obj_name);
6522 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6526 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
6528 if (strlen(btf_tmp_path) >= PATH_MAX) {
6529 err = -ENAMETOOLONG;
6532 obj->btf_custom_path = strdup(btf_tmp_path);
6533 if (!obj->btf_custom_path) {
6539 kconfig = OPTS_GET(opts, kconfig, NULL);
6541 obj->kconfig = strdup(kconfig);
6542 if (!obj->kconfig) {
6548 err = bpf_object__elf_init(obj);
6549 err = err ? : bpf_object__check_endianness(obj);
6550 err = err ? : bpf_object__elf_collect(obj);
6551 err = err ? : bpf_object__collect_externs(obj);
6552 err = err ? : bpf_object__finalize_btf(obj);
6553 err = err ? : bpf_object__init_maps(obj, opts);
6554 err = err ? : bpf_object_init_progs(obj, opts);
6555 err = err ? : bpf_object__collect_relos(obj);
6559 bpf_object__elf_finish(obj);
6563 bpf_object__close(obj);
6564 return ERR_PTR(err);
6567 static struct bpf_object *
6568 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
6570 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6571 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
6574 /* param validation */
6578 pr_debug("loading %s\n", attr->file);
6579 return __bpf_object__open(attr->file, NULL, 0, &opts);
6582 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
6584 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
6587 struct bpf_object *bpf_object__open(const char *path)
6589 struct bpf_object_open_attr attr = {
6591 .prog_type = BPF_PROG_TYPE_UNSPEC,
6594 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6598 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
6601 return libbpf_err_ptr(-EINVAL);
6603 pr_debug("loading %s\n", path);
6605 return libbpf_ptr(__bpf_object__open(path, NULL, 0, opts));
6609 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
6610 const struct bpf_object_open_opts *opts)
6612 if (!obj_buf || obj_buf_sz == 0)
6613 return libbpf_err_ptr(-EINVAL);
6615 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, opts));
6619 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
6622 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6623 .object_name = name,
6624 /* wrong default, but backwards-compatible */
6625 .relaxed_maps = true,
6628 /* returning NULL is wrong, but backwards-compatible */
6629 if (!obj_buf || obj_buf_sz == 0)
6630 return errno = EINVAL, NULL;
6632 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, &opts));
6635 int bpf_object__unload(struct bpf_object *obj)
6640 return libbpf_err(-EINVAL);
6642 for (i = 0; i < obj->nr_maps; i++) {
6643 zclose(obj->maps[i].fd);
6644 if (obj->maps[i].st_ops)
6645 zfree(&obj->maps[i].st_ops->kern_vdata);
6648 for (i = 0; i < obj->nr_programs; i++)
6649 bpf_program__unload(&obj->programs[i]);
6654 static int bpf_object__sanitize_maps(struct bpf_object *obj)
6658 bpf_object__for_each_map(m, obj) {
6659 if (!bpf_map__is_internal(m))
6661 if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) {
6662 pr_warn("kernel doesn't support global data\n");
6665 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
6666 m->def.map_flags ^= BPF_F_MMAPABLE;
6672 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
6674 char sym_type, sym_name[500];
6675 unsigned long long sym_addr;
6676 const struct btf_type *t;
6677 struct extern_desc *ext;
6681 f = fopen("/proc/kallsyms", "r");
6684 pr_warn("failed to open /proc/kallsyms: %d\n", err);
6689 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
6690 &sym_addr, &sym_type, sym_name);
6691 if (ret == EOF && feof(f))
6694 pr_warn("failed to read kallsyms entry: %d\n", ret);
6699 ext = find_extern_by_name(obj, sym_name);
6700 if (!ext || ext->type != EXT_KSYM)
6703 t = btf__type_by_id(obj->btf, ext->btf_id);
6707 if (ext->is_set && ext->ksym.addr != sym_addr) {
6708 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
6709 sym_name, ext->ksym.addr, sym_addr);
6715 ext->ksym.addr = sym_addr;
6716 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
6725 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
6726 __u16 kind, struct btf **res_btf,
6729 int i, id, btf_fd, err;
6732 btf = obj->btf_vmlinux;
6734 id = btf__find_by_name_kind(btf, ksym_name, kind);
6736 if (id == -ENOENT) {
6737 err = load_module_btfs(obj);
6741 for (i = 0; i < obj->btf_module_cnt; i++) {
6742 btf = obj->btf_modules[i].btf;
6743 /* we assume module BTF FD is always >0 */
6744 btf_fd = obj->btf_modules[i].fd;
6745 id = btf__find_by_name_kind(btf, ksym_name, kind);
6754 *res_btf_fd = btf_fd;
6758 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
6759 struct extern_desc *ext)
6761 const struct btf_type *targ_var, *targ_type;
6762 __u32 targ_type_id, local_type_id;
6763 const char *targ_var_name;
6764 int id, btf_fd = 0, err;
6765 struct btf *btf = NULL;
6767 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &btf_fd);
6768 if (id == -ESRCH && ext->is_weak) {
6770 } else if (id < 0) {
6771 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
6776 /* find local type_id */
6777 local_type_id = ext->ksym.type_id;
6779 /* find target type_id */
6780 targ_var = btf__type_by_id(btf, id);
6781 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
6782 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
6784 err = bpf_core_types_are_compat(obj->btf, local_type_id,
6787 const struct btf_type *local_type;
6788 const char *targ_name, *local_name;
6790 local_type = btf__type_by_id(obj->btf, local_type_id);
6791 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
6792 targ_name = btf__name_by_offset(btf, targ_type->name_off);
6794 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
6795 ext->name, local_type_id,
6796 btf_kind_str(local_type), local_name, targ_type_id,
6797 btf_kind_str(targ_type), targ_name);
6802 ext->ksym.kernel_btf_obj_fd = btf_fd;
6803 ext->ksym.kernel_btf_id = id;
6804 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
6805 ext->name, id, btf_kind_str(targ_var), targ_var_name);
6810 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
6811 struct extern_desc *ext)
6813 int local_func_proto_id, kfunc_proto_id, kfunc_id;
6814 const struct btf_type *kern_func;
6815 struct btf *kern_btf = NULL;
6816 int ret, kern_btf_fd = 0;
6818 local_func_proto_id = ext->ksym.type_id;
6820 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC,
6821 &kern_btf, &kern_btf_fd);
6823 pr_warn("extern (func ksym) '%s': not found in kernel BTF\n",
6828 if (kern_btf != obj->btf_vmlinux) {
6829 pr_warn("extern (func ksym) '%s': function in kernel module is not supported\n",
6834 kern_func = btf__type_by_id(kern_btf, kfunc_id);
6835 kfunc_proto_id = kern_func->type;
6837 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
6838 kern_btf, kfunc_proto_id);
6840 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
6841 ext->name, local_func_proto_id, kfunc_proto_id);
6846 ext->ksym.kernel_btf_obj_fd = kern_btf_fd;
6847 ext->ksym.kernel_btf_id = kfunc_id;
6848 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
6849 ext->name, kfunc_id);
6854 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
6856 const struct btf_type *t;
6857 struct extern_desc *ext;
6860 for (i = 0; i < obj->nr_extern; i++) {
6861 ext = &obj->externs[i];
6862 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
6865 if (obj->gen_loader) {
6867 ext->ksym.kernel_btf_obj_fd = 0;
6868 ext->ksym.kernel_btf_id = 0;
6871 t = btf__type_by_id(obj->btf, ext->btf_id);
6873 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
6875 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
6882 static int bpf_object__resolve_externs(struct bpf_object *obj,
6883 const char *extra_kconfig)
6885 bool need_config = false, need_kallsyms = false;
6886 bool need_vmlinux_btf = false;
6887 struct extern_desc *ext;
6888 void *kcfg_data = NULL;
6891 if (obj->nr_extern == 0)
6894 if (obj->kconfig_map_idx >= 0)
6895 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
6897 for (i = 0; i < obj->nr_extern; i++) {
6898 ext = &obj->externs[i];
6900 if (ext->type == EXT_KCFG &&
6901 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
6902 void *ext_val = kcfg_data + ext->kcfg.data_off;
6903 __u32 kver = get_kernel_version();
6906 pr_warn("failed to get kernel version\n");
6909 err = set_kcfg_value_num(ext, ext_val, kver);
6912 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
6913 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
6915 } else if (ext->type == EXT_KSYM) {
6916 if (ext->ksym.type_id)
6917 need_vmlinux_btf = true;
6919 need_kallsyms = true;
6921 pr_warn("unrecognized extern '%s'\n", ext->name);
6925 if (need_config && extra_kconfig) {
6926 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
6929 need_config = false;
6930 for (i = 0; i < obj->nr_extern; i++) {
6931 ext = &obj->externs[i];
6932 if (ext->type == EXT_KCFG && !ext->is_set) {
6939 err = bpf_object__read_kconfig_file(obj, kcfg_data);
6943 if (need_kallsyms) {
6944 err = bpf_object__read_kallsyms_file(obj);
6948 if (need_vmlinux_btf) {
6949 err = bpf_object__resolve_ksyms_btf_id(obj);
6953 for (i = 0; i < obj->nr_extern; i++) {
6954 ext = &obj->externs[i];
6956 if (!ext->is_set && !ext->is_weak) {
6957 pr_warn("extern %s (strong) not resolved\n", ext->name);
6959 } else if (!ext->is_set) {
6960 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
6968 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
6970 struct bpf_object *obj;
6974 return libbpf_err(-EINVAL);
6977 return libbpf_err(-EINVAL);
6980 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
6981 return libbpf_err(-EINVAL);
6984 if (obj->gen_loader)
6985 bpf_gen__init(obj->gen_loader, attr->log_level);
6987 err = bpf_object__probe_loading(obj);
6988 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
6989 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
6990 err = err ? : bpf_object__sanitize_and_load_btf(obj);
6991 err = err ? : bpf_object__sanitize_maps(obj);
6992 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
6993 err = err ? : bpf_object__create_maps(obj);
6994 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : attr->target_btf_path);
6995 err = err ? : bpf_object__load_progs(obj, attr->log_level);
6997 if (obj->gen_loader) {
6999 btf__set_fd(obj->btf, -1);
7000 for (i = 0; i < obj->nr_maps; i++)
7001 obj->maps[i].fd = -1;
7003 err = bpf_gen__finish(obj->gen_loader);
7006 /* clean up module BTFs */
7007 for (i = 0; i < obj->btf_module_cnt; i++) {
7008 close(obj->btf_modules[i].fd);
7009 btf__free(obj->btf_modules[i].btf);
7010 free(obj->btf_modules[i].name);
7012 free(obj->btf_modules);
7014 /* clean up vmlinux BTF */
7015 btf__free(obj->btf_vmlinux);
7016 obj->btf_vmlinux = NULL;
7018 obj->loaded = true; /* doesn't matter if successfully or not */
7025 /* unpin any maps that were auto-pinned during load */
7026 for (i = 0; i < obj->nr_maps; i++)
7027 if (obj->maps[i].pinned && !obj->maps[i].reused)
7028 bpf_map__unpin(&obj->maps[i], NULL);
7030 bpf_object__unload(obj);
7031 pr_warn("failed to load object '%s'\n", obj->path);
7032 return libbpf_err(err);
7035 int bpf_object__load(struct bpf_object *obj)
7037 struct bpf_object_load_attr attr = {
7041 return bpf_object__load_xattr(&attr);
7044 static int make_parent_dir(const char *path)
7046 char *cp, errmsg[STRERR_BUFSIZE];
7050 dname = strdup(path);
7054 dir = dirname(dname);
7055 if (mkdir(dir, 0700) && errno != EEXIST)
7060 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7061 pr_warn("failed to mkdir %s: %s\n", path, cp);
7066 static int check_path(const char *path)
7068 char *cp, errmsg[STRERR_BUFSIZE];
7069 struct statfs st_fs;
7076 dname = strdup(path);
7080 dir = dirname(dname);
7081 if (statfs(dir, &st_fs)) {
7082 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7083 pr_warn("failed to statfs %s: %s\n", dir, cp);
7088 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7089 pr_warn("specified path %s is not on BPF FS\n", path);
7096 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
7099 char *cp, errmsg[STRERR_BUFSIZE];
7102 err = make_parent_dir(path);
7104 return libbpf_err(err);
7106 err = check_path(path);
7108 return libbpf_err(err);
7111 pr_warn("invalid program pointer\n");
7112 return libbpf_err(-EINVAL);
7115 if (instance < 0 || instance >= prog->instances.nr) {
7116 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7117 instance, prog->name, prog->instances.nr);
7118 return libbpf_err(-EINVAL);
7121 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
7123 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7124 pr_warn("failed to pin program: %s\n", cp);
7125 return libbpf_err(err);
7127 pr_debug("pinned program '%s'\n", path);
7132 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
7137 err = check_path(path);
7139 return libbpf_err(err);
7142 pr_warn("invalid program pointer\n");
7143 return libbpf_err(-EINVAL);
7146 if (instance < 0 || instance >= prog->instances.nr) {
7147 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7148 instance, prog->name, prog->instances.nr);
7149 return libbpf_err(-EINVAL);
7154 return libbpf_err(-errno);
7156 pr_debug("unpinned program '%s'\n", path);
7161 int bpf_program__pin(struct bpf_program *prog, const char *path)
7165 err = make_parent_dir(path);
7167 return libbpf_err(err);
7169 err = check_path(path);
7171 return libbpf_err(err);
7174 pr_warn("invalid program pointer\n");
7175 return libbpf_err(-EINVAL);
7178 if (prog->instances.nr <= 0) {
7179 pr_warn("no instances of prog %s to pin\n", prog->name);
7180 return libbpf_err(-EINVAL);
7183 if (prog->instances.nr == 1) {
7184 /* don't create subdirs when pinning single instance */
7185 return bpf_program__pin_instance(prog, path, 0);
7188 for (i = 0; i < prog->instances.nr; i++) {
7192 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7196 } else if (len >= PATH_MAX) {
7197 err = -ENAMETOOLONG;
7201 err = bpf_program__pin_instance(prog, buf, i);
7209 for (i = i - 1; i >= 0; i--) {
7213 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7216 else if (len >= PATH_MAX)
7219 bpf_program__unpin_instance(prog, buf, i);
7224 return libbpf_err(err);
7227 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7231 err = check_path(path);
7233 return libbpf_err(err);
7236 pr_warn("invalid program pointer\n");
7237 return libbpf_err(-EINVAL);
7240 if (prog->instances.nr <= 0) {
7241 pr_warn("no instances of prog %s to pin\n", prog->name);
7242 return libbpf_err(-EINVAL);
7245 if (prog->instances.nr == 1) {
7246 /* don't create subdirs when pinning single instance */
7247 return bpf_program__unpin_instance(prog, path, 0);
7250 for (i = 0; i < prog->instances.nr; i++) {
7254 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7256 return libbpf_err(-EINVAL);
7257 else if (len >= PATH_MAX)
7258 return libbpf_err(-ENAMETOOLONG);
7260 err = bpf_program__unpin_instance(prog, buf, i);
7267 return libbpf_err(-errno);
7272 int bpf_map__pin(struct bpf_map *map, const char *path)
7274 char *cp, errmsg[STRERR_BUFSIZE];
7278 pr_warn("invalid map pointer\n");
7279 return libbpf_err(-EINVAL);
7282 if (map->pin_path) {
7283 if (path && strcmp(path, map->pin_path)) {
7284 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7285 bpf_map__name(map), map->pin_path, path);
7286 return libbpf_err(-EINVAL);
7287 } else if (map->pinned) {
7288 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7289 bpf_map__name(map), map->pin_path);
7294 pr_warn("missing a path to pin map '%s' at\n",
7295 bpf_map__name(map));
7296 return libbpf_err(-EINVAL);
7297 } else if (map->pinned) {
7298 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7299 return libbpf_err(-EEXIST);
7302 map->pin_path = strdup(path);
7303 if (!map->pin_path) {
7309 err = make_parent_dir(map->pin_path);
7311 return libbpf_err(err);
7313 err = check_path(map->pin_path);
7315 return libbpf_err(err);
7317 if (bpf_obj_pin(map->fd, map->pin_path)) {
7323 pr_debug("pinned map '%s'\n", map->pin_path);
7328 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7329 pr_warn("failed to pin map: %s\n", cp);
7330 return libbpf_err(err);
7333 int bpf_map__unpin(struct bpf_map *map, const char *path)
7338 pr_warn("invalid map pointer\n");
7339 return libbpf_err(-EINVAL);
7342 if (map->pin_path) {
7343 if (path && strcmp(path, map->pin_path)) {
7344 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7345 bpf_map__name(map), map->pin_path, path);
7346 return libbpf_err(-EINVAL);
7348 path = map->pin_path;
7350 pr_warn("no path to unpin map '%s' from\n",
7351 bpf_map__name(map));
7352 return libbpf_err(-EINVAL);
7355 err = check_path(path);
7357 return libbpf_err(err);
7361 return libbpf_err(-errno);
7363 map->pinned = false;
7364 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7369 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7376 return libbpf_err(-errno);
7379 free(map->pin_path);
7380 map->pin_path = new;
7384 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7386 return map->pin_path;
7389 const char *bpf_map__pin_path(const struct bpf_map *map)
7391 return map->pin_path;
7394 bool bpf_map__is_pinned(const struct bpf_map *map)
7399 static void sanitize_pin_path(char *s)
7401 /* bpffs disallows periods in path names */
7409 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7411 struct bpf_map *map;
7415 return libbpf_err(-ENOENT);
7418 pr_warn("object not yet loaded; load it first\n");
7419 return libbpf_err(-ENOENT);
7422 bpf_object__for_each_map(map, obj) {
7423 char *pin_path = NULL;
7429 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7430 bpf_map__name(map));
7433 goto err_unpin_maps;
7434 } else if (len >= PATH_MAX) {
7435 err = -ENAMETOOLONG;
7436 goto err_unpin_maps;
7438 sanitize_pin_path(buf);
7440 } else if (!map->pin_path) {
7444 err = bpf_map__pin(map, pin_path);
7446 goto err_unpin_maps;
7452 while ((map = bpf_map__prev(map, obj))) {
7456 bpf_map__unpin(map, NULL);
7459 return libbpf_err(err);
7462 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7464 struct bpf_map *map;
7468 return libbpf_err(-ENOENT);
7470 bpf_object__for_each_map(map, obj) {
7471 char *pin_path = NULL;
7477 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7478 bpf_map__name(map));
7480 return libbpf_err(-EINVAL);
7481 else if (len >= PATH_MAX)
7482 return libbpf_err(-ENAMETOOLONG);
7483 sanitize_pin_path(buf);
7485 } else if (!map->pin_path) {
7489 err = bpf_map__unpin(map, pin_path);
7491 return libbpf_err(err);
7497 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
7499 struct bpf_program *prog;
7503 return libbpf_err(-ENOENT);
7506 pr_warn("object not yet loaded; load it first\n");
7507 return libbpf_err(-ENOENT);
7510 bpf_object__for_each_program(prog, obj) {
7514 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7518 goto err_unpin_programs;
7519 } else if (len >= PATH_MAX) {
7520 err = -ENAMETOOLONG;
7521 goto err_unpin_programs;
7524 err = bpf_program__pin(prog, buf);
7526 goto err_unpin_programs;
7532 while ((prog = bpf_program__prev(prog, obj))) {
7536 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7540 else if (len >= PATH_MAX)
7543 bpf_program__unpin(prog, buf);
7546 return libbpf_err(err);
7549 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
7551 struct bpf_program *prog;
7555 return libbpf_err(-ENOENT);
7557 bpf_object__for_each_program(prog, obj) {
7561 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7564 return libbpf_err(-EINVAL);
7565 else if (len >= PATH_MAX)
7566 return libbpf_err(-ENAMETOOLONG);
7568 err = bpf_program__unpin(prog, buf);
7570 return libbpf_err(err);
7576 int bpf_object__pin(struct bpf_object *obj, const char *path)
7580 err = bpf_object__pin_maps(obj, path);
7582 return libbpf_err(err);
7584 err = bpf_object__pin_programs(obj, path);
7586 bpf_object__unpin_maps(obj, path);
7587 return libbpf_err(err);
7593 static void bpf_map__destroy(struct bpf_map *map)
7595 if (map->clear_priv)
7596 map->clear_priv(map, map->priv);
7598 map->clear_priv = NULL;
7600 if (map->inner_map) {
7601 bpf_map__destroy(map->inner_map);
7602 zfree(&map->inner_map);
7605 zfree(&map->init_slots);
7606 map->init_slots_sz = 0;
7609 munmap(map->mmaped, bpf_map_mmap_sz(map));
7614 zfree(&map->st_ops->data);
7615 zfree(&map->st_ops->progs);
7616 zfree(&map->st_ops->kern_func_off);
7617 zfree(&map->st_ops);
7621 zfree(&map->pin_path);
7627 void bpf_object__close(struct bpf_object *obj)
7631 if (IS_ERR_OR_NULL(obj))
7634 if (obj->clear_priv)
7635 obj->clear_priv(obj, obj->priv);
7637 bpf_gen__free(obj->gen_loader);
7638 bpf_object__elf_finish(obj);
7639 bpf_object__unload(obj);
7640 btf__free(obj->btf);
7641 btf_ext__free(obj->btf_ext);
7643 for (i = 0; i < obj->nr_maps; i++)
7644 bpf_map__destroy(&obj->maps[i]);
7646 zfree(&obj->btf_custom_path);
7647 zfree(&obj->kconfig);
7648 zfree(&obj->externs);
7654 if (obj->programs && obj->nr_programs) {
7655 for (i = 0; i < obj->nr_programs; i++)
7656 bpf_program__exit(&obj->programs[i]);
7658 zfree(&obj->programs);
7660 list_del(&obj->list);
7665 bpf_object__next(struct bpf_object *prev)
7667 struct bpf_object *next;
7670 next = list_first_entry(&bpf_objects_list,
7674 next = list_next_entry(prev, list);
7676 /* Empty list is noticed here so don't need checking on entry. */
7677 if (&next->list == &bpf_objects_list)
7683 const char *bpf_object__name(const struct bpf_object *obj)
7685 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
7688 unsigned int bpf_object__kversion(const struct bpf_object *obj)
7690 return obj ? obj->kern_version : 0;
7693 struct btf *bpf_object__btf(const struct bpf_object *obj)
7695 return obj ? obj->btf : NULL;
7698 int bpf_object__btf_fd(const struct bpf_object *obj)
7700 return obj->btf ? btf__fd(obj->btf) : -1;
7703 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
7706 return libbpf_err(-EINVAL);
7708 obj->kern_version = kern_version;
7713 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
7714 bpf_object_clear_priv_t clear_priv)
7716 if (obj->priv && obj->clear_priv)
7717 obj->clear_priv(obj, obj->priv);
7720 obj->clear_priv = clear_priv;
7724 void *bpf_object__priv(const struct bpf_object *obj)
7726 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
7729 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
7731 struct bpf_gen *gen;
7735 if (!OPTS_VALID(opts, gen_loader_opts))
7737 gen = calloc(sizeof(*gen), 1);
7741 obj->gen_loader = gen;
7745 static struct bpf_program *
7746 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
7749 size_t nr_programs = obj->nr_programs;
7756 /* Iter from the beginning */
7757 return forward ? &obj->programs[0] :
7758 &obj->programs[nr_programs - 1];
7760 if (p->obj != obj) {
7761 pr_warn("error: program handler doesn't match object\n");
7762 return errno = EINVAL, NULL;
7765 idx = (p - obj->programs) + (forward ? 1 : -1);
7766 if (idx >= obj->nr_programs || idx < 0)
7768 return &obj->programs[idx];
7771 struct bpf_program *
7772 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
7774 struct bpf_program *prog = prev;
7777 prog = __bpf_program__iter(prog, obj, true);
7778 } while (prog && prog_is_subprog(obj, prog));
7783 struct bpf_program *
7784 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
7786 struct bpf_program *prog = next;
7789 prog = __bpf_program__iter(prog, obj, false);
7790 } while (prog && prog_is_subprog(obj, prog));
7795 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
7796 bpf_program_clear_priv_t clear_priv)
7798 if (prog->priv && prog->clear_priv)
7799 prog->clear_priv(prog, prog->priv);
7802 prog->clear_priv = clear_priv;
7806 void *bpf_program__priv(const struct bpf_program *prog)
7808 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
7811 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
7813 prog->prog_ifindex = ifindex;
7816 const char *bpf_program__name(const struct bpf_program *prog)
7821 const char *bpf_program__section_name(const struct bpf_program *prog)
7823 return prog->sec_name;
7826 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
7830 title = prog->sec_name;
7832 title = strdup(title);
7834 pr_warn("failed to strdup program title\n");
7835 return libbpf_err_ptr(-ENOMEM);
7842 bool bpf_program__autoload(const struct bpf_program *prog)
7847 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
7849 if (prog->obj->loaded)
7850 return libbpf_err(-EINVAL);
7852 prog->load = autoload;
7856 int bpf_program__fd(const struct bpf_program *prog)
7858 return bpf_program__nth_fd(prog, 0);
7861 size_t bpf_program__size(const struct bpf_program *prog)
7863 return prog->insns_cnt * BPF_INSN_SZ;
7866 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
7867 bpf_program_prep_t prep)
7871 if (nr_instances <= 0 || !prep)
7872 return libbpf_err(-EINVAL);
7874 if (prog->instances.nr > 0 || prog->instances.fds) {
7875 pr_warn("Can't set pre-processor after loading\n");
7876 return libbpf_err(-EINVAL);
7879 instances_fds = malloc(sizeof(int) * nr_instances);
7880 if (!instances_fds) {
7881 pr_warn("alloc memory failed for fds\n");
7882 return libbpf_err(-ENOMEM);
7885 /* fill all fd with -1 */
7886 memset(instances_fds, -1, sizeof(int) * nr_instances);
7888 prog->instances.nr = nr_instances;
7889 prog->instances.fds = instances_fds;
7890 prog->preprocessor = prep;
7894 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
7899 return libbpf_err(-EINVAL);
7901 if (n >= prog->instances.nr || n < 0) {
7902 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
7903 n, prog->name, prog->instances.nr);
7904 return libbpf_err(-EINVAL);
7907 fd = prog->instances.fds[n];
7909 pr_warn("%dth instance of program '%s' is invalid\n",
7911 return libbpf_err(-ENOENT);
7917 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
7922 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
7927 static bool bpf_program__is_type(const struct bpf_program *prog,
7928 enum bpf_prog_type type)
7930 return prog ? (prog->type == type) : false;
7933 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
7934 int bpf_program__set_##NAME(struct bpf_program *prog) \
7937 return libbpf_err(-EINVAL); \
7938 bpf_program__set_type(prog, TYPE); \
7942 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
7944 return bpf_program__is_type(prog, TYPE); \
7947 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
7948 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
7949 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7950 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
7951 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
7952 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
7953 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7954 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
7955 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
7956 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
7957 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
7958 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
7959 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
7961 enum bpf_attach_type
7962 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
7964 return prog->expected_attach_type;
7967 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
7968 enum bpf_attach_type type)
7970 prog->expected_attach_type = type;
7973 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
7974 attachable, attach_btf) \
7977 .prog_type = ptype, \
7978 .expected_attach_type = eatype, \
7979 .cookie = (long) ( \
7980 (eatype_optional ? SEC_EXP_ATTACH_OPT : 0) | \
7981 (attachable ? SEC_ATTACHABLE : 0) | \
7982 (attach_btf ? SEC_ATTACH_BTF : 0) \
7984 .preload_fn = libbpf_preload_prog, \
7987 /* Programs that can be attached. */
7988 #define BPF_APROG_SEC(string, ptype, atype) \
7989 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
7991 /* Programs that must specify expected attach type at load time. */
7992 #define BPF_EAPROG_SEC(string, ptype, eatype) \
7993 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
7995 /* Programs that use BTF to identify attach point */
7996 #define BPF_PROG_BTF(string, ptype, eatype) \
7997 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
7999 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8001 .prog_type = BPF_PROG_TYPE_##ptype, \
8002 .expected_attach_type = atype, \
8003 .cookie = (long)(flags), \
8004 .preload_fn = libbpf_preload_prog, \
8008 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie);
8009 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie);
8010 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie);
8011 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie);
8012 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie);
8013 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie);
8015 static const struct bpf_sec_def section_defs[] = {
8016 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8017 BPF_EAPROG_SEC("sk_reuseport/migrate", BPF_PROG_TYPE_SK_REUSEPORT,
8018 BPF_SK_REUSEPORT_SELECT_OR_MIGRATE),
8019 BPF_EAPROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT,
8020 BPF_SK_REUSEPORT_SELECT),
8021 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8022 SEC_DEF("uprobe/", KPROBE, 0, SEC_NONE),
8023 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8024 SEC_DEF("uretprobe/", KPROBE, 0, SEC_NONE),
8025 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE),
8026 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
8027 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE),
8028 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8029 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8030 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8031 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8032 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8033 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8034 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8035 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8036 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8037 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8038 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8039 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8040 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8041 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8042 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8043 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8044 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
8046 BPF_EAPROG_SEC("xdp_cpumap/", BPF_PROG_TYPE_XDP,
8048 BPF_APROG_SEC("xdp", BPF_PROG_TYPE_XDP,
8050 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8051 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8052 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8053 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8054 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8055 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
8056 BPF_CGROUP_INET_INGRESS),
8057 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
8058 BPF_CGROUP_INET_EGRESS),
8059 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8060 BPF_EAPROG_SEC("cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK,
8061 BPF_CGROUP_INET_SOCK_CREATE),
8062 BPF_EAPROG_SEC("cgroup/sock_release", BPF_PROG_TYPE_CGROUP_SOCK,
8063 BPF_CGROUP_INET_SOCK_RELEASE),
8064 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
8065 BPF_CGROUP_INET_SOCK_CREATE),
8066 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
8067 BPF_CGROUP_INET4_POST_BIND),
8068 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
8069 BPF_CGROUP_INET6_POST_BIND),
8070 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
8072 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
8073 BPF_CGROUP_SOCK_OPS),
8074 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
8075 BPF_SK_SKB_STREAM_PARSER),
8076 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
8077 BPF_SK_SKB_STREAM_VERDICT),
8078 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8079 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
8080 BPF_SK_MSG_VERDICT),
8081 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
8083 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
8084 BPF_FLOW_DISSECTOR),
8085 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8086 BPF_CGROUP_INET4_BIND),
8087 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8088 BPF_CGROUP_INET6_BIND),
8089 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8090 BPF_CGROUP_INET4_CONNECT),
8091 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8092 BPF_CGROUP_INET6_CONNECT),
8093 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8094 BPF_CGROUP_UDP4_SENDMSG),
8095 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8096 BPF_CGROUP_UDP6_SENDMSG),
8097 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8098 BPF_CGROUP_UDP4_RECVMSG),
8099 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8100 BPF_CGROUP_UDP6_RECVMSG),
8101 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8102 BPF_CGROUP_INET4_GETPEERNAME),
8103 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8104 BPF_CGROUP_INET6_GETPEERNAME),
8105 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8106 BPF_CGROUP_INET4_GETSOCKNAME),
8107 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8108 BPF_CGROUP_INET6_GETSOCKNAME),
8109 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
8111 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8112 BPF_CGROUP_GETSOCKOPT),
8113 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8114 BPF_CGROUP_SETSOCKOPT),
8115 SEC_DEF("struct_ops", STRUCT_OPS, 0, SEC_NONE),
8116 BPF_EAPROG_SEC("sk_lookup/", BPF_PROG_TYPE_SK_LOOKUP,
8120 #undef BPF_PROG_SEC_IMPL
8121 #undef BPF_APROG_SEC
8122 #undef BPF_EAPROG_SEC
8125 #define MAX_TYPE_NAME_SIZE 32
8127 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8129 int i, n = ARRAY_SIZE(section_defs);
8131 for (i = 0; i < n; i++) {
8132 if (str_has_pfx(sec_name, section_defs[i].sec))
8133 return §ion_defs[i];
8138 static char *libbpf_get_type_names(bool attach_type)
8140 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8148 /* Forge string buf with all available names */
8149 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8150 const struct bpf_sec_def *sec_def = §ion_defs[i];
8153 if (sec_def->preload_fn != libbpf_preload_prog)
8156 if (!(sec_def->cookie & SEC_ATTACHABLE))
8160 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8165 strcat(buf, section_defs[i].sec);
8171 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8172 enum bpf_attach_type *expected_attach_type)
8174 const struct bpf_sec_def *sec_def;
8178 return libbpf_err(-EINVAL);
8180 sec_def = find_sec_def(name);
8182 *prog_type = sec_def->prog_type;
8183 *expected_attach_type = sec_def->expected_attach_type;
8187 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8188 type_names = libbpf_get_type_names(false);
8189 if (type_names != NULL) {
8190 pr_debug("supported section(type) names are:%s\n", type_names);
8194 return libbpf_err(-ESRCH);
8197 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8200 struct bpf_map *map;
8203 for (i = 0; i < obj->nr_maps; i++) {
8204 map = &obj->maps[i];
8205 if (!bpf_map__is_struct_ops(map))
8207 if (map->sec_offset <= offset &&
8208 offset - map->sec_offset < map->def.value_size)
8215 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8216 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8217 GElf_Shdr *shdr, Elf_Data *data)
8219 const struct btf_member *member;
8220 struct bpf_struct_ops *st_ops;
8221 struct bpf_program *prog;
8222 unsigned int shdr_idx;
8223 const struct btf *btf;
8224 struct bpf_map *map;
8226 unsigned int moff, insn_idx;
8233 symbols = obj->efile.symbols;
8235 nrels = shdr->sh_size / shdr->sh_entsize;
8236 for (i = 0; i < nrels; i++) {
8237 if (!gelf_getrel(data, i, &rel)) {
8238 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8239 return -LIBBPF_ERRNO__FORMAT;
8242 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
8243 pr_warn("struct_ops reloc: symbol %zx not found\n",
8244 (size_t)GELF_R_SYM(rel.r_info));
8245 return -LIBBPF_ERRNO__FORMAT;
8248 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
8249 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
8251 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
8252 (size_t)rel.r_offset);
8256 moff = rel.r_offset - map->sec_offset;
8257 shdr_idx = sym.st_shndx;
8258 st_ops = map->st_ops;
8259 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",
8261 (long long)(rel.r_info >> 32),
8262 (long long)sym.st_value,
8263 shdr_idx, (size_t)rel.r_offset,
8264 map->sec_offset, sym.st_name, name);
8266 if (shdr_idx >= SHN_LORESERVE) {
8267 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
8268 map->name, (size_t)rel.r_offset, shdr_idx);
8269 return -LIBBPF_ERRNO__RELOC;
8271 if (sym.st_value % BPF_INSN_SZ) {
8272 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8273 map->name, (unsigned long long)sym.st_value);
8274 return -LIBBPF_ERRNO__FORMAT;
8276 insn_idx = sym.st_value / BPF_INSN_SZ;
8278 member = find_member_by_offset(st_ops->type, moff * 8);
8280 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8284 member_idx = member - btf_members(st_ops->type);
8285 name = btf__name_by_offset(btf, member->name_off);
8287 if (!resolve_func_ptr(btf, member->type, NULL)) {
8288 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8293 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8295 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8296 map->name, shdr_idx, name);
8300 /* prevent the use of BPF prog with invalid type */
8301 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8302 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8303 map->name, prog->name);
8307 /* if we haven't yet processed this BPF program, record proper
8308 * attach_btf_id and member_idx
8310 if (!prog->attach_btf_id) {
8311 prog->attach_btf_id = st_ops->type_id;
8312 prog->expected_attach_type = member_idx;
8315 /* struct_ops BPF prog can be re-used between multiple
8316 * .struct_ops as long as it's the same struct_ops struct
8317 * definition and the same function pointer field
8319 if (prog->attach_btf_id != st_ops->type_id ||
8320 prog->expected_attach_type != member_idx) {
8321 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",
8322 map->name, prog->name, prog->sec_name, prog->type,
8323 prog->attach_btf_id, prog->expected_attach_type, name);
8327 st_ops->progs[member_idx] = prog;
8333 #define BTF_TRACE_PREFIX "btf_trace_"
8334 #define BTF_LSM_PREFIX "bpf_lsm_"
8335 #define BTF_ITER_PREFIX "bpf_iter_"
8336 #define BTF_MAX_NAME_SIZE 128
8338 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8339 const char **prefix, int *kind)
8341 switch (attach_type) {
8342 case BPF_TRACE_RAW_TP:
8343 *prefix = BTF_TRACE_PREFIX;
8344 *kind = BTF_KIND_TYPEDEF;
8347 *prefix = BTF_LSM_PREFIX;
8348 *kind = BTF_KIND_FUNC;
8350 case BPF_TRACE_ITER:
8351 *prefix = BTF_ITER_PREFIX;
8352 *kind = BTF_KIND_FUNC;
8356 *kind = BTF_KIND_FUNC;
8360 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8361 const char *name, __u32 kind)
8363 char btf_type_name[BTF_MAX_NAME_SIZE];
8366 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8367 "%s%s", prefix, name);
8368 /* snprintf returns the number of characters written excluding the
8369 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8370 * indicates truncation.
8372 if (ret < 0 || ret >= sizeof(btf_type_name))
8373 return -ENAMETOOLONG;
8374 return btf__find_by_name_kind(btf, btf_type_name, kind);
8377 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8378 enum bpf_attach_type attach_type)
8383 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8384 return find_btf_by_prefix_kind(btf, prefix, name, kind);
8387 int libbpf_find_vmlinux_btf_id(const char *name,
8388 enum bpf_attach_type attach_type)
8393 btf = btf__load_vmlinux_btf();
8394 err = libbpf_get_error(btf);
8396 pr_warn("vmlinux BTF is not found\n");
8397 return libbpf_err(err);
8400 err = find_attach_btf_id(btf, name, attach_type);
8402 pr_warn("%s is not found in vmlinux BTF\n", name);
8405 return libbpf_err(err);
8408 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8410 struct bpf_prog_info_linear *info_linear;
8411 struct bpf_prog_info *info;
8415 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
8416 err = libbpf_get_error(info_linear);
8418 pr_warn("failed get_prog_info_linear for FD %d\n",
8424 info = &info_linear->info;
8425 if (!info->btf_id) {
8426 pr_warn("The target program doesn't have BTF\n");
8429 btf = btf__load_from_kernel_by_id(info->btf_id);
8430 if (libbpf_get_error(btf)) {
8431 pr_warn("Failed to get BTF of the program\n");
8434 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8437 pr_warn("%s is not found in prog's BTF\n", name);
8445 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
8446 enum bpf_attach_type attach_type,
8447 int *btf_obj_fd, int *btf_type_id)
8451 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
8453 *btf_obj_fd = 0; /* vmlinux BTF */
8460 ret = load_module_btfs(obj);
8464 for (i = 0; i < obj->btf_module_cnt; i++) {
8465 const struct module_btf *mod = &obj->btf_modules[i];
8467 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
8469 *btf_obj_fd = mod->fd;
8482 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
8483 int *btf_obj_fd, int *btf_type_id)
8485 enum bpf_attach_type attach_type = prog->expected_attach_type;
8486 __u32 attach_prog_fd = prog->attach_prog_fd;
8489 /* BPF program's BTF ID */
8490 if (attach_prog_fd) {
8491 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
8493 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
8494 attach_prog_fd, attach_name, err);
8502 /* kernel/module BTF ID */
8503 if (prog->obj->gen_loader) {
8504 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
8508 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
8511 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
8517 int libbpf_attach_type_by_name(const char *name,
8518 enum bpf_attach_type *attach_type)
8521 const struct bpf_sec_def *sec_def;
8524 return libbpf_err(-EINVAL);
8526 sec_def = find_sec_def(name);
8528 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
8529 type_names = libbpf_get_type_names(true);
8530 if (type_names != NULL) {
8531 pr_debug("attachable section(type) names are:%s\n", type_names);
8535 return libbpf_err(-EINVAL);
8538 if (sec_def->preload_fn != libbpf_preload_prog)
8539 return libbpf_err(-EINVAL);
8540 if (!(sec_def->cookie & SEC_ATTACHABLE))
8541 return libbpf_err(-EINVAL);
8543 *attach_type = sec_def->expected_attach_type;
8547 int bpf_map__fd(const struct bpf_map *map)
8549 return map ? map->fd : libbpf_err(-EINVAL);
8552 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
8554 return map ? &map->def : libbpf_err_ptr(-EINVAL);
8557 const char *bpf_map__name(const struct bpf_map *map)
8559 return map ? map->name : NULL;
8562 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
8564 return map->def.type;
8567 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
8570 return libbpf_err(-EBUSY);
8571 map->def.type = type;
8575 __u32 bpf_map__map_flags(const struct bpf_map *map)
8577 return map->def.map_flags;
8580 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
8583 return libbpf_err(-EBUSY);
8584 map->def.map_flags = flags;
8588 __u32 bpf_map__numa_node(const struct bpf_map *map)
8590 return map->numa_node;
8593 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
8596 return libbpf_err(-EBUSY);
8597 map->numa_node = numa_node;
8601 __u32 bpf_map__key_size(const struct bpf_map *map)
8603 return map->def.key_size;
8606 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
8609 return libbpf_err(-EBUSY);
8610 map->def.key_size = size;
8614 __u32 bpf_map__value_size(const struct bpf_map *map)
8616 return map->def.value_size;
8619 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
8622 return libbpf_err(-EBUSY);
8623 map->def.value_size = size;
8627 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8629 return map ? map->btf_key_type_id : 0;
8632 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8634 return map ? map->btf_value_type_id : 0;
8637 int bpf_map__set_priv(struct bpf_map *map, void *priv,
8638 bpf_map_clear_priv_t clear_priv)
8641 return libbpf_err(-EINVAL);
8644 if (map->clear_priv)
8645 map->clear_priv(map, map->priv);
8649 map->clear_priv = clear_priv;
8653 void *bpf_map__priv(const struct bpf_map *map)
8655 return map ? map->priv : libbpf_err_ptr(-EINVAL);
8658 int bpf_map__set_initial_value(struct bpf_map *map,
8659 const void *data, size_t size)
8661 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
8662 size != map->def.value_size || map->fd >= 0)
8663 return libbpf_err(-EINVAL);
8665 memcpy(map->mmaped, data, size);
8669 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
8673 *psize = map->def.value_size;
8677 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
8679 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
8682 bool bpf_map__is_internal(const struct bpf_map *map)
8684 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
8687 __u32 bpf_map__ifindex(const struct bpf_map *map)
8689 return map->map_ifindex;
8692 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
8695 return libbpf_err(-EBUSY);
8696 map->map_ifindex = ifindex;
8700 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
8702 if (!bpf_map_type__is_map_in_map(map->def.type)) {
8703 pr_warn("error: unsupported map type\n");
8704 return libbpf_err(-EINVAL);
8706 if (map->inner_map_fd != -1) {
8707 pr_warn("error: inner_map_fd already specified\n");
8708 return libbpf_err(-EINVAL);
8710 zfree(&map->inner_map);
8711 map->inner_map_fd = fd;
8715 static struct bpf_map *
8716 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
8719 struct bpf_map *s, *e;
8721 if (!obj || !obj->maps)
8722 return errno = EINVAL, NULL;
8725 e = obj->maps + obj->nr_maps;
8727 if ((m < s) || (m >= e)) {
8728 pr_warn("error in %s: map handler doesn't belong to object\n",
8730 return errno = EINVAL, NULL;
8733 idx = (m - obj->maps) + i;
8734 if (idx >= obj->nr_maps || idx < 0)
8736 return &obj->maps[idx];
8740 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
8745 return __bpf_map__iter(prev, obj, 1);
8749 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
8754 return obj->maps + obj->nr_maps - 1;
8757 return __bpf_map__iter(next, obj, -1);
8761 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
8763 struct bpf_map *pos;
8765 bpf_object__for_each_map(pos, obj) {
8766 if (pos->name && !strcmp(pos->name, name))
8769 return errno = ENOENT, NULL;
8773 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
8775 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
8779 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
8781 return libbpf_err_ptr(-ENOTSUP);
8784 long libbpf_get_error(const void *ptr)
8786 if (!IS_ERR_OR_NULL(ptr))
8790 errno = -PTR_ERR(ptr);
8792 /* If ptr == NULL, then errno should be already set by the failing
8793 * API, because libbpf never returns NULL on success and it now always
8794 * sets errno on error. So no extra errno handling for ptr == NULL
8800 int bpf_prog_load(const char *file, enum bpf_prog_type type,
8801 struct bpf_object **pobj, int *prog_fd)
8803 struct bpf_prog_load_attr attr;
8805 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
8807 attr.prog_type = type;
8808 attr.expected_attach_type = 0;
8810 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
8813 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
8814 struct bpf_object **pobj, int *prog_fd)
8816 struct bpf_object_open_attr open_attr = {};
8817 struct bpf_program *prog, *first_prog = NULL;
8818 struct bpf_object *obj;
8819 struct bpf_map *map;
8823 return libbpf_err(-EINVAL);
8825 return libbpf_err(-EINVAL);
8827 open_attr.file = attr->file;
8828 open_attr.prog_type = attr->prog_type;
8830 obj = bpf_object__open_xattr(&open_attr);
8831 err = libbpf_get_error(obj);
8833 return libbpf_err(-ENOENT);
8835 bpf_object__for_each_program(prog, obj) {
8836 enum bpf_attach_type attach_type = attr->expected_attach_type;
8838 * to preserve backwards compatibility, bpf_prog_load treats
8839 * attr->prog_type, if specified, as an override to whatever
8840 * bpf_object__open guessed
8842 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
8843 bpf_program__set_type(prog, attr->prog_type);
8844 bpf_program__set_expected_attach_type(prog,
8847 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
8849 * we haven't guessed from section name and user
8850 * didn't provide a fallback type, too bad...
8852 bpf_object__close(obj);
8853 return libbpf_err(-EINVAL);
8856 prog->prog_ifindex = attr->ifindex;
8857 prog->log_level = attr->log_level;
8858 prog->prog_flags |= attr->prog_flags;
8863 bpf_object__for_each_map(map, obj) {
8864 if (!bpf_map__is_offload_neutral(map))
8865 map->map_ifindex = attr->ifindex;
8869 pr_warn("object file doesn't contain bpf program\n");
8870 bpf_object__close(obj);
8871 return libbpf_err(-ENOENT);
8874 err = bpf_object__load(obj);
8876 bpf_object__close(obj);
8877 return libbpf_err(err);
8881 *prog_fd = bpf_program__fd(first_prog);
8886 int (*detach)(struct bpf_link *link);
8887 void (*dealloc)(struct bpf_link *link);
8888 char *pin_path; /* NULL, if not pinned */
8889 int fd; /* hook FD, -1 if not applicable */
8893 /* Replace link's underlying BPF program with the new one */
8894 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
8898 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
8899 return libbpf_err_errno(ret);
8902 /* Release "ownership" of underlying BPF resource (typically, BPF program
8903 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
8904 * link, when destructed through bpf_link__destroy() call won't attempt to
8905 * detach/unregisted that BPF resource. This is useful in situations where,
8906 * say, attached BPF program has to outlive userspace program that attached it
8907 * in the system. Depending on type of BPF program, though, there might be
8908 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
8909 * exit of userspace program doesn't trigger automatic detachment and clean up
8910 * inside the kernel.
8912 void bpf_link__disconnect(struct bpf_link *link)
8914 link->disconnected = true;
8917 int bpf_link__destroy(struct bpf_link *link)
8921 if (IS_ERR_OR_NULL(link))
8924 if (!link->disconnected && link->detach)
8925 err = link->detach(link);
8927 free(link->pin_path);
8929 link->dealloc(link);
8933 return libbpf_err(err);
8936 int bpf_link__fd(const struct bpf_link *link)
8941 const char *bpf_link__pin_path(const struct bpf_link *link)
8943 return link->pin_path;
8946 static int bpf_link__detach_fd(struct bpf_link *link)
8948 return libbpf_err_errno(close(link->fd));
8951 struct bpf_link *bpf_link__open(const char *path)
8953 struct bpf_link *link;
8956 fd = bpf_obj_get(path);
8959 pr_warn("failed to open link at %s: %d\n", path, fd);
8960 return libbpf_err_ptr(fd);
8963 link = calloc(1, sizeof(*link));
8966 return libbpf_err_ptr(-ENOMEM);
8968 link->detach = &bpf_link__detach_fd;
8971 link->pin_path = strdup(path);
8972 if (!link->pin_path) {
8973 bpf_link__destroy(link);
8974 return libbpf_err_ptr(-ENOMEM);
8980 int bpf_link__detach(struct bpf_link *link)
8982 return bpf_link_detach(link->fd) ? -errno : 0;
8985 int bpf_link__pin(struct bpf_link *link, const char *path)
8990 return libbpf_err(-EBUSY);
8991 err = make_parent_dir(path);
8993 return libbpf_err(err);
8994 err = check_path(path);
8996 return libbpf_err(err);
8998 link->pin_path = strdup(path);
8999 if (!link->pin_path)
9000 return libbpf_err(-ENOMEM);
9002 if (bpf_obj_pin(link->fd, link->pin_path)) {
9004 zfree(&link->pin_path);
9005 return libbpf_err(err);
9008 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9012 int bpf_link__unpin(struct bpf_link *link)
9016 if (!link->pin_path)
9017 return libbpf_err(-EINVAL);
9019 err = unlink(link->pin_path);
9023 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9024 zfree(&link->pin_path);
9028 struct bpf_link_perf {
9029 struct bpf_link link;
9031 /* legacy kprobe support: keep track of probe identifier and type */
9032 char *legacy_probe_name;
9033 bool legacy_is_kprobe;
9034 bool legacy_is_retprobe;
9037 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9038 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9040 static int bpf_link_perf_detach(struct bpf_link *link)
9042 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9045 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9048 if (perf_link->perf_event_fd != link->fd)
9049 close(perf_link->perf_event_fd);
9052 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9053 if (perf_link->legacy_probe_name) {
9054 if (perf_link->legacy_is_kprobe) {
9055 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9056 perf_link->legacy_is_retprobe);
9058 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9059 perf_link->legacy_is_retprobe);
9066 static void bpf_link_perf_dealloc(struct bpf_link *link)
9068 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9070 free(perf_link->legacy_probe_name);
9074 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9075 const struct bpf_perf_event_opts *opts)
9077 char errmsg[STRERR_BUFSIZE];
9078 struct bpf_link_perf *link;
9079 int prog_fd, link_fd = -1, err;
9081 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9082 return libbpf_err_ptr(-EINVAL);
9085 pr_warn("prog '%s': invalid perf event FD %d\n",
9087 return libbpf_err_ptr(-EINVAL);
9089 prog_fd = bpf_program__fd(prog);
9091 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9093 return libbpf_err_ptr(-EINVAL);
9096 link = calloc(1, sizeof(*link));
9098 return libbpf_err_ptr(-ENOMEM);
9099 link->link.detach = &bpf_link_perf_detach;
9100 link->link.dealloc = &bpf_link_perf_dealloc;
9101 link->perf_event_fd = pfd;
9103 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9104 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9105 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9107 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9110 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9112 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9115 link->link.fd = link_fd;
9117 if (OPTS_GET(opts, bpf_cookie, 0)) {
9118 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9123 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9125 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9126 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9128 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9132 link->link.fd = pfd;
9134 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9136 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9137 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9146 return libbpf_err_ptr(err);
9149 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9151 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9155 * this function is expected to parse integer in the range of [0, 2^31-1] from
9156 * given file using scanf format string fmt. If actual parsed value is
9157 * negative, the result might be indistinguishable from error
9159 static int parse_uint_from_file(const char *file, const char *fmt)
9161 char buf[STRERR_BUFSIZE];
9165 f = fopen(file, "r");
9168 pr_debug("failed to open '%s': %s\n", file,
9169 libbpf_strerror_r(err, buf, sizeof(buf)));
9172 err = fscanf(f, fmt, &ret);
9174 err = err == EOF ? -EIO : -errno;
9175 pr_debug("failed to parse '%s': %s\n", file,
9176 libbpf_strerror_r(err, buf, sizeof(buf)));
9184 static int determine_kprobe_perf_type(void)
9186 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9188 return parse_uint_from_file(file, "%d\n");
9191 static int determine_uprobe_perf_type(void)
9193 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9195 return parse_uint_from_file(file, "%d\n");
9198 static int determine_kprobe_retprobe_bit(void)
9200 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9202 return parse_uint_from_file(file, "config:%d\n");
9205 static int determine_uprobe_retprobe_bit(void)
9207 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9209 return parse_uint_from_file(file, "config:%d\n");
9212 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9213 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9215 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9216 uint64_t offset, int pid, size_t ref_ctr_off)
9218 struct perf_event_attr attr = {};
9219 char errmsg[STRERR_BUFSIZE];
9222 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9225 type = uprobe ? determine_uprobe_perf_type()
9226 : determine_kprobe_perf_type();
9228 pr_warn("failed to determine %s perf type: %s\n",
9229 uprobe ? "uprobe" : "kprobe",
9230 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9234 int bit = uprobe ? determine_uprobe_retprobe_bit()
9235 : determine_kprobe_retprobe_bit();
9238 pr_warn("failed to determine %s retprobe bit: %s\n",
9239 uprobe ? "uprobe" : "kprobe",
9240 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9243 attr.config |= 1 << bit;
9245 attr.size = sizeof(attr);
9247 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9248 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9249 attr.config2 = offset; /* kprobe_addr or probe_offset */
9251 /* pid filter is meaningful only for uprobes */
9252 pfd = syscall(__NR_perf_event_open, &attr,
9253 pid < 0 ? -1 : pid /* pid */,
9254 pid == -1 ? 0 : -1 /* cpu */,
9255 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9258 pr_warn("%s perf_event_open() failed: %s\n",
9259 uprobe ? "uprobe" : "kprobe",
9260 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9266 static int append_to_file(const char *file, const char *fmt, ...)
9271 fd = open(file, O_WRONLY | O_APPEND, 0);
9276 n = vdprintf(fd, fmt, ap);
9286 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9287 const char *kfunc_name, size_t offset)
9289 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), kfunc_name, offset);
9292 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9293 const char *kfunc_name, size_t offset)
9295 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9297 return append_to_file(file, "%c:%s/%s %s+0x%zx",
9298 retprobe ? 'r' : 'p',
9299 retprobe ? "kretprobes" : "kprobes",
9300 probe_name, kfunc_name, offset);
9303 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9305 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9307 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
9310 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9314 snprintf(file, sizeof(file),
9315 "/sys/kernel/debug/tracing/events/%s/%s/id",
9316 retprobe ? "kretprobes" : "kprobes", probe_name);
9318 return parse_uint_from_file(file, "%d\n");
9321 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9322 const char *kfunc_name, size_t offset, int pid)
9324 struct perf_event_attr attr = {};
9325 char errmsg[STRERR_BUFSIZE];
9328 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9330 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9332 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9335 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
9337 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9339 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9342 attr.size = sizeof(attr);
9344 attr.type = PERF_TYPE_TRACEPOINT;
9346 pfd = syscall(__NR_perf_event_open, &attr,
9347 pid < 0 ? -1 : pid, /* pid */
9348 pid == -1 ? 0 : -1, /* cpu */
9349 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9352 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
9353 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9360 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
9361 const char *func_name,
9362 const struct bpf_kprobe_opts *opts)
9364 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9365 char errmsg[STRERR_BUFSIZE];
9366 char *legacy_probe = NULL;
9367 struct bpf_link *link;
9369 bool retprobe, legacy;
9372 if (!OPTS_VALID(opts, bpf_kprobe_opts))
9373 return libbpf_err_ptr(-EINVAL);
9375 retprobe = OPTS_GET(opts, retprobe, false);
9376 offset = OPTS_GET(opts, offset, 0);
9377 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9379 legacy = determine_kprobe_perf_type() < 0;
9381 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
9383 -1 /* pid */, 0 /* ref_ctr_off */);
9385 char probe_name[256];
9387 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
9390 legacy_probe = strdup(func_name);
9392 return libbpf_err_ptr(-ENOMEM);
9394 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
9395 offset, -1 /* pid */);
9399 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
9400 prog->name, retprobe ? "kretprobe" : "kprobe",
9402 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9405 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9406 err = libbpf_get_error(link);
9409 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
9410 prog->name, retprobe ? "kretprobe" : "kprobe",
9412 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9416 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9418 perf_link->legacy_probe_name = legacy_probe;
9419 perf_link->legacy_is_kprobe = true;
9420 perf_link->legacy_is_retprobe = retprobe;
9426 return libbpf_err_ptr(err);
9429 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
9431 const char *func_name)
9433 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
9434 .retprobe = retprobe,
9437 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
9440 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie)
9442 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
9443 unsigned long offset = 0;
9444 struct bpf_link *link;
9445 const char *func_name;
9449 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
9451 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
9453 func_name = prog->sec_name + sizeof("kprobe/") - 1;
9455 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
9458 pr_warn("kprobe name is invalid: %s\n", func_name);
9459 return libbpf_err_ptr(err);
9461 if (opts.retprobe && offset != 0) {
9464 pr_warn("kretprobes do not support offset specification\n");
9465 return libbpf_err_ptr(err);
9468 opts.offset = offset;
9469 link = bpf_program__attach_kprobe_opts(prog, func, &opts);
9474 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
9475 const char *binary_path, uint64_t offset)
9479 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
9481 /* sanitize binary_path in the probe name */
9482 for (i = 0; buf[i]; i++) {
9483 if (!isalnum(buf[i]))
9488 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
9489 const char *binary_path, size_t offset)
9491 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
9493 return append_to_file(file, "%c:%s/%s %s:0x%zx",
9494 retprobe ? 'r' : 'p',
9495 retprobe ? "uretprobes" : "uprobes",
9496 probe_name, binary_path, offset);
9499 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
9501 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
9503 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
9506 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9510 snprintf(file, sizeof(file),
9511 "/sys/kernel/debug/tracing/events/%s/%s/id",
9512 retprobe ? "uretprobes" : "uprobes", probe_name);
9514 return parse_uint_from_file(file, "%d\n");
9517 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
9518 const char *binary_path, size_t offset, int pid)
9520 struct perf_event_attr attr;
9523 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
9525 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
9526 binary_path, (size_t)offset, err);
9529 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
9531 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
9532 binary_path, offset, err);
9536 memset(&attr, 0, sizeof(attr));
9537 attr.size = sizeof(attr);
9539 attr.type = PERF_TYPE_TRACEPOINT;
9541 pfd = syscall(__NR_perf_event_open, &attr,
9542 pid < 0 ? -1 : pid, /* pid */
9543 pid == -1 ? 0 : -1, /* cpu */
9544 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9547 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
9553 LIBBPF_API struct bpf_link *
9554 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
9555 const char *binary_path, size_t func_offset,
9556 const struct bpf_uprobe_opts *opts)
9558 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9559 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
9560 struct bpf_link *link;
9563 bool retprobe, legacy;
9565 if (!OPTS_VALID(opts, bpf_uprobe_opts))
9566 return libbpf_err_ptr(-EINVAL);
9568 retprobe = OPTS_GET(opts, retprobe, false);
9569 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
9570 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9572 legacy = determine_uprobe_perf_type() < 0;
9574 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
9575 func_offset, pid, ref_ctr_off);
9577 char probe_name[512];
9580 return libbpf_err_ptr(-EINVAL);
9582 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
9583 binary_path, func_offset);
9585 legacy_probe = strdup(probe_name);
9587 return libbpf_err_ptr(-ENOMEM);
9589 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
9590 binary_path, func_offset, pid);
9594 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
9595 prog->name, retprobe ? "uretprobe" : "uprobe",
9596 binary_path, func_offset,
9597 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9601 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9602 err = libbpf_get_error(link);
9605 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
9606 prog->name, retprobe ? "uretprobe" : "uprobe",
9607 binary_path, func_offset,
9608 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9612 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9614 perf_link->legacy_probe_name = legacy_probe;
9615 perf_link->legacy_is_kprobe = false;
9616 perf_link->legacy_is_retprobe = retprobe;
9621 return libbpf_err_ptr(err);
9625 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
9626 bool retprobe, pid_t pid,
9627 const char *binary_path,
9630 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
9632 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
9635 static int determine_tracepoint_id(const char *tp_category,
9636 const char *tp_name)
9638 char file[PATH_MAX];
9641 ret = snprintf(file, sizeof(file),
9642 "/sys/kernel/debug/tracing/events/%s/%s/id",
9643 tp_category, tp_name);
9646 if (ret >= sizeof(file)) {
9647 pr_debug("tracepoint %s/%s path is too long\n",
9648 tp_category, tp_name);
9651 return parse_uint_from_file(file, "%d\n");
9654 static int perf_event_open_tracepoint(const char *tp_category,
9655 const char *tp_name)
9657 struct perf_event_attr attr = {};
9658 char errmsg[STRERR_BUFSIZE];
9659 int tp_id, pfd, err;
9661 tp_id = determine_tracepoint_id(tp_category, tp_name);
9663 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
9664 tp_category, tp_name,
9665 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
9669 attr.type = PERF_TYPE_TRACEPOINT;
9670 attr.size = sizeof(attr);
9671 attr.config = tp_id;
9673 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
9674 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9677 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
9678 tp_category, tp_name,
9679 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9685 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
9686 const char *tp_category,
9687 const char *tp_name,
9688 const struct bpf_tracepoint_opts *opts)
9690 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9691 char errmsg[STRERR_BUFSIZE];
9692 struct bpf_link *link;
9695 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
9696 return libbpf_err_ptr(-EINVAL);
9698 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9700 pfd = perf_event_open_tracepoint(tp_category, tp_name);
9702 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
9703 prog->name, tp_category, tp_name,
9704 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9705 return libbpf_err_ptr(pfd);
9707 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9708 err = libbpf_get_error(link);
9711 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
9712 prog->name, tp_category, tp_name,
9713 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9714 return libbpf_err_ptr(err);
9719 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
9720 const char *tp_category,
9721 const char *tp_name)
9723 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
9726 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie)
9728 char *sec_name, *tp_cat, *tp_name;
9729 struct bpf_link *link;
9731 sec_name = strdup(prog->sec_name);
9733 return libbpf_err_ptr(-ENOMEM);
9735 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
9736 if (str_has_pfx(prog->sec_name, "tp/"))
9737 tp_cat = sec_name + sizeof("tp/") - 1;
9739 tp_cat = sec_name + sizeof("tracepoint/") - 1;
9740 tp_name = strchr(tp_cat, '/');
9743 return libbpf_err_ptr(-EINVAL);
9748 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
9753 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
9754 const char *tp_name)
9756 char errmsg[STRERR_BUFSIZE];
9757 struct bpf_link *link;
9760 prog_fd = bpf_program__fd(prog);
9762 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9763 return libbpf_err_ptr(-EINVAL);
9766 link = calloc(1, sizeof(*link));
9768 return libbpf_err_ptr(-ENOMEM);
9769 link->detach = &bpf_link__detach_fd;
9771 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
9775 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
9776 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9777 return libbpf_err_ptr(pfd);
9783 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie)
9785 const char *tp_name;
9787 if (str_has_pfx(prog->sec_name, "raw_tp/"))
9788 tp_name = prog->sec_name + sizeof("raw_tp/") - 1;
9790 tp_name = prog->sec_name + sizeof("raw_tracepoint/") - 1;
9792 return bpf_program__attach_raw_tracepoint(prog, tp_name);
9795 /* Common logic for all BPF program types that attach to a btf_id */
9796 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
9798 char errmsg[STRERR_BUFSIZE];
9799 struct bpf_link *link;
9802 prog_fd = bpf_program__fd(prog);
9804 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9805 return libbpf_err_ptr(-EINVAL);
9808 link = calloc(1, sizeof(*link));
9810 return libbpf_err_ptr(-ENOMEM);
9811 link->detach = &bpf_link__detach_fd;
9813 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
9817 pr_warn("prog '%s': failed to attach: %s\n",
9818 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9819 return libbpf_err_ptr(pfd);
9822 return (struct bpf_link *)link;
9825 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
9827 return bpf_program__attach_btf_id(prog);
9830 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
9832 return bpf_program__attach_btf_id(prog);
9835 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie)
9837 return bpf_program__attach_trace(prog);
9840 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie)
9842 return bpf_program__attach_lsm(prog);
9845 static struct bpf_link *
9846 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
9847 const char *target_name)
9849 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
9850 .target_btf_id = btf_id);
9851 enum bpf_attach_type attach_type;
9852 char errmsg[STRERR_BUFSIZE];
9853 struct bpf_link *link;
9854 int prog_fd, link_fd;
9856 prog_fd = bpf_program__fd(prog);
9858 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9859 return libbpf_err_ptr(-EINVAL);
9862 link = calloc(1, sizeof(*link));
9864 return libbpf_err_ptr(-ENOMEM);
9865 link->detach = &bpf_link__detach_fd;
9867 attach_type = bpf_program__get_expected_attach_type(prog);
9868 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
9872 pr_warn("prog '%s': failed to attach to %s: %s\n",
9873 prog->name, target_name,
9874 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9875 return libbpf_err_ptr(link_fd);
9882 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
9884 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
9888 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
9890 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
9893 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
9895 /* target_fd/target_ifindex use the same field in LINK_CREATE */
9896 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
9899 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
9901 const char *attach_func_name)
9905 if (!!target_fd != !!attach_func_name) {
9906 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
9908 return libbpf_err_ptr(-EINVAL);
9911 if (prog->type != BPF_PROG_TYPE_EXT) {
9912 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
9914 return libbpf_err_ptr(-EINVAL);
9918 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
9920 return libbpf_err_ptr(btf_id);
9922 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
9924 /* no target, so use raw_tracepoint_open for compatibility
9927 return bpf_program__attach_trace(prog);
9932 bpf_program__attach_iter(const struct bpf_program *prog,
9933 const struct bpf_iter_attach_opts *opts)
9935 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
9936 char errmsg[STRERR_BUFSIZE];
9937 struct bpf_link *link;
9938 int prog_fd, link_fd;
9939 __u32 target_fd = 0;
9941 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
9942 return libbpf_err_ptr(-EINVAL);
9944 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
9945 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
9947 prog_fd = bpf_program__fd(prog);
9949 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9950 return libbpf_err_ptr(-EINVAL);
9953 link = calloc(1, sizeof(*link));
9955 return libbpf_err_ptr(-ENOMEM);
9956 link->detach = &bpf_link__detach_fd;
9958 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
9963 pr_warn("prog '%s': failed to attach to iterator: %s\n",
9964 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9965 return libbpf_err_ptr(link_fd);
9971 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)
9973 return bpf_program__attach_iter(prog, NULL);
9976 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
9978 if (!prog->sec_def || !prog->sec_def->attach_fn)
9979 return libbpf_err_ptr(-ESRCH);
9981 return prog->sec_def->attach_fn(prog, prog->sec_def->cookie);
9984 static int bpf_link__detach_struct_ops(struct bpf_link *link)
9988 if (bpf_map_delete_elem(link->fd, &zero))
9994 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
9996 struct bpf_struct_ops *st_ops;
9997 struct bpf_link *link;
10001 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
10002 return libbpf_err_ptr(-EINVAL);
10004 link = calloc(1, sizeof(*link));
10006 return libbpf_err_ptr(-EINVAL);
10008 st_ops = map->st_ops;
10009 for (i = 0; i < btf_vlen(st_ops->type); i++) {
10010 struct bpf_program *prog = st_ops->progs[i];
10017 prog_fd = bpf_program__fd(prog);
10018 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10019 *(unsigned long *)kern_data = prog_fd;
10022 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10026 return libbpf_err_ptr(err);
10029 link->detach = bpf_link__detach_struct_ops;
10030 link->fd = map->fd;
10035 enum bpf_perf_event_ret
10036 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10037 void **copy_mem, size_t *copy_size,
10038 bpf_perf_event_print_t fn, void *private_data)
10040 struct perf_event_mmap_page *header = mmap_mem;
10041 __u64 data_head = ring_buffer_read_head(header);
10042 __u64 data_tail = header->data_tail;
10043 void *base = ((__u8 *)header) + page_size;
10044 int ret = LIBBPF_PERF_EVENT_CONT;
10045 struct perf_event_header *ehdr;
10048 while (data_head != data_tail) {
10049 ehdr = base + (data_tail & (mmap_size - 1));
10050 ehdr_size = ehdr->size;
10052 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10053 void *copy_start = ehdr;
10054 size_t len_first = base + mmap_size - copy_start;
10055 size_t len_secnd = ehdr_size - len_first;
10057 if (*copy_size < ehdr_size) {
10059 *copy_mem = malloc(ehdr_size);
10062 ret = LIBBPF_PERF_EVENT_ERROR;
10065 *copy_size = ehdr_size;
10068 memcpy(*copy_mem, copy_start, len_first);
10069 memcpy(*copy_mem + len_first, base, len_secnd);
10073 ret = fn(ehdr, private_data);
10074 data_tail += ehdr_size;
10075 if (ret != LIBBPF_PERF_EVENT_CONT)
10079 ring_buffer_write_tail(header, data_tail);
10080 return libbpf_err(ret);
10083 struct perf_buffer;
10085 struct perf_buffer_params {
10086 struct perf_event_attr *attr;
10087 /* if event_cb is specified, it takes precendence */
10088 perf_buffer_event_fn event_cb;
10089 /* sample_cb and lost_cb are higher-level common-case callbacks */
10090 perf_buffer_sample_fn sample_cb;
10091 perf_buffer_lost_fn lost_cb;
10098 struct perf_cpu_buf {
10099 struct perf_buffer *pb;
10100 void *base; /* mmap()'ed memory */
10101 void *buf; /* for reconstructing segmented data */
10108 struct perf_buffer {
10109 perf_buffer_event_fn event_cb;
10110 perf_buffer_sample_fn sample_cb;
10111 perf_buffer_lost_fn lost_cb;
10112 void *ctx; /* passed into callbacks */
10116 struct perf_cpu_buf **cpu_bufs;
10117 struct epoll_event *events;
10118 int cpu_cnt; /* number of allocated CPU buffers */
10119 int epoll_fd; /* perf event FD */
10120 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10123 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10124 struct perf_cpu_buf *cpu_buf)
10128 if (cpu_buf->base &&
10129 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
10130 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
10131 if (cpu_buf->fd >= 0) {
10132 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10133 close(cpu_buf->fd);
10135 free(cpu_buf->buf);
10139 void perf_buffer__free(struct perf_buffer *pb)
10143 if (IS_ERR_OR_NULL(pb))
10145 if (pb->cpu_bufs) {
10146 for (i = 0; i < pb->cpu_cnt; i++) {
10147 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10152 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10153 perf_buffer__free_cpu_buf(pb, cpu_buf);
10155 free(pb->cpu_bufs);
10157 if (pb->epoll_fd >= 0)
10158 close(pb->epoll_fd);
10163 static struct perf_cpu_buf *
10164 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10165 int cpu, int map_key)
10167 struct perf_cpu_buf *cpu_buf;
10168 char msg[STRERR_BUFSIZE];
10171 cpu_buf = calloc(1, sizeof(*cpu_buf));
10173 return ERR_PTR(-ENOMEM);
10176 cpu_buf->cpu = cpu;
10177 cpu_buf->map_key = map_key;
10179 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10180 -1, PERF_FLAG_FD_CLOEXEC);
10181 if (cpu_buf->fd < 0) {
10183 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10184 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10188 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10189 PROT_READ | PROT_WRITE, MAP_SHARED,
10191 if (cpu_buf->base == MAP_FAILED) {
10192 cpu_buf->base = NULL;
10194 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
10195 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10199 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10201 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
10202 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10209 perf_buffer__free_cpu_buf(pb, cpu_buf);
10210 return (struct perf_cpu_buf *)ERR_PTR(err);
10213 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10214 struct perf_buffer_params *p);
10216 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
10217 const struct perf_buffer_opts *opts)
10219 struct perf_buffer_params p = {};
10220 struct perf_event_attr attr = { 0, };
10222 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
10223 attr.type = PERF_TYPE_SOFTWARE;
10224 attr.sample_type = PERF_SAMPLE_RAW;
10225 attr.sample_period = 1;
10226 attr.wakeup_events = 1;
10229 p.sample_cb = opts ? opts->sample_cb : NULL;
10230 p.lost_cb = opts ? opts->lost_cb : NULL;
10231 p.ctx = opts ? opts->ctx : NULL;
10233 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10236 struct perf_buffer *
10237 perf_buffer__new_raw(int map_fd, size_t page_cnt,
10238 const struct perf_buffer_raw_opts *opts)
10240 struct perf_buffer_params p = {};
10242 p.attr = opts->attr;
10243 p.event_cb = opts->event_cb;
10245 p.cpu_cnt = opts->cpu_cnt;
10246 p.cpus = opts->cpus;
10247 p.map_keys = opts->map_keys;
10249 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10252 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10253 struct perf_buffer_params *p)
10255 const char *online_cpus_file = "/sys/devices/system/cpu/online";
10256 struct bpf_map_info map;
10257 char msg[STRERR_BUFSIZE];
10258 struct perf_buffer *pb;
10259 bool *online = NULL;
10260 __u32 map_info_len;
10263 if (page_cnt & (page_cnt - 1)) {
10264 pr_warn("page count should be power of two, but is %zu\n",
10266 return ERR_PTR(-EINVAL);
10269 /* best-effort sanity checks */
10270 memset(&map, 0, sizeof(map));
10271 map_info_len = sizeof(map);
10272 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
10275 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
10276 * -EBADFD, -EFAULT, or -E2BIG on real error
10278 if (err != -EINVAL) {
10279 pr_warn("failed to get map info for map FD %d: %s\n",
10280 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
10281 return ERR_PTR(err);
10283 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
10286 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
10287 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
10289 return ERR_PTR(-EINVAL);
10293 pb = calloc(1, sizeof(*pb));
10295 return ERR_PTR(-ENOMEM);
10297 pb->event_cb = p->event_cb;
10298 pb->sample_cb = p->sample_cb;
10299 pb->lost_cb = p->lost_cb;
10302 pb->page_size = getpagesize();
10303 pb->mmap_size = pb->page_size * page_cnt;
10304 pb->map_fd = map_fd;
10306 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
10307 if (pb->epoll_fd < 0) {
10309 pr_warn("failed to create epoll instance: %s\n",
10310 libbpf_strerror_r(err, msg, sizeof(msg)));
10314 if (p->cpu_cnt > 0) {
10315 pb->cpu_cnt = p->cpu_cnt;
10317 pb->cpu_cnt = libbpf_num_possible_cpus();
10318 if (pb->cpu_cnt < 0) {
10322 if (map.max_entries && map.max_entries < pb->cpu_cnt)
10323 pb->cpu_cnt = map.max_entries;
10326 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
10329 pr_warn("failed to allocate events: out of memory\n");
10332 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
10333 if (!pb->cpu_bufs) {
10335 pr_warn("failed to allocate buffers: out of memory\n");
10339 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
10341 pr_warn("failed to get online CPU mask: %d\n", err);
10345 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
10346 struct perf_cpu_buf *cpu_buf;
10349 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
10350 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
10352 /* in case user didn't explicitly requested particular CPUs to
10353 * be attached to, skip offline/not present CPUs
10355 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
10358 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
10359 if (IS_ERR(cpu_buf)) {
10360 err = PTR_ERR(cpu_buf);
10364 pb->cpu_bufs[j] = cpu_buf;
10366 err = bpf_map_update_elem(pb->map_fd, &map_key,
10370 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
10371 cpu, map_key, cpu_buf->fd,
10372 libbpf_strerror_r(err, msg, sizeof(msg)));
10376 pb->events[j].events = EPOLLIN;
10377 pb->events[j].data.ptr = cpu_buf;
10378 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
10379 &pb->events[j]) < 0) {
10381 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
10383 libbpf_strerror_r(err, msg, sizeof(msg)));
10396 perf_buffer__free(pb);
10397 return ERR_PTR(err);
10400 struct perf_sample_raw {
10401 struct perf_event_header header;
10406 struct perf_sample_lost {
10407 struct perf_event_header header;
10410 uint64_t sample_id;
10413 static enum bpf_perf_event_ret
10414 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
10416 struct perf_cpu_buf *cpu_buf = ctx;
10417 struct perf_buffer *pb = cpu_buf->pb;
10420 /* user wants full control over parsing perf event */
10422 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
10425 case PERF_RECORD_SAMPLE: {
10426 struct perf_sample_raw *s = data;
10429 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
10432 case PERF_RECORD_LOST: {
10433 struct perf_sample_lost *s = data;
10436 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
10440 pr_warn("unknown perf sample type %d\n", e->type);
10441 return LIBBPF_PERF_EVENT_ERROR;
10443 return LIBBPF_PERF_EVENT_CONT;
10446 static int perf_buffer__process_records(struct perf_buffer *pb,
10447 struct perf_cpu_buf *cpu_buf)
10449 enum bpf_perf_event_ret ret;
10451 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
10452 pb->page_size, &cpu_buf->buf,
10453 &cpu_buf->buf_size,
10454 perf_buffer__process_record, cpu_buf);
10455 if (ret != LIBBPF_PERF_EVENT_CONT)
10460 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
10462 return pb->epoll_fd;
10465 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
10469 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
10473 for (i = 0; i < cnt; i++) {
10474 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
10476 err = perf_buffer__process_records(pb, cpu_buf);
10478 pr_warn("error while processing records: %d\n", err);
10479 return libbpf_err(err);
10485 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
10488 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
10490 return pb->cpu_cnt;
10494 * Return perf_event FD of a ring buffer in *buf_idx* slot of
10495 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
10496 * select()/poll()/epoll() Linux syscalls.
10498 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
10500 struct perf_cpu_buf *cpu_buf;
10502 if (buf_idx >= pb->cpu_cnt)
10503 return libbpf_err(-EINVAL);
10505 cpu_buf = pb->cpu_bufs[buf_idx];
10507 return libbpf_err(-ENOENT);
10509 return cpu_buf->fd;
10513 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
10514 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
10515 * consume, do nothing and return success.
10520 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
10522 struct perf_cpu_buf *cpu_buf;
10524 if (buf_idx >= pb->cpu_cnt)
10525 return libbpf_err(-EINVAL);
10527 cpu_buf = pb->cpu_bufs[buf_idx];
10529 return libbpf_err(-ENOENT);
10531 return perf_buffer__process_records(pb, cpu_buf);
10534 int perf_buffer__consume(struct perf_buffer *pb)
10538 for (i = 0; i < pb->cpu_cnt; i++) {
10539 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10544 err = perf_buffer__process_records(pb, cpu_buf);
10546 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
10547 return libbpf_err(err);
10553 struct bpf_prog_info_array_desc {
10554 int array_offset; /* e.g. offset of jited_prog_insns */
10555 int count_offset; /* e.g. offset of jited_prog_len */
10556 int size_offset; /* > 0: offset of rec size,
10557 * < 0: fix size of -size_offset
10561 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
10562 [BPF_PROG_INFO_JITED_INSNS] = {
10563 offsetof(struct bpf_prog_info, jited_prog_insns),
10564 offsetof(struct bpf_prog_info, jited_prog_len),
10567 [BPF_PROG_INFO_XLATED_INSNS] = {
10568 offsetof(struct bpf_prog_info, xlated_prog_insns),
10569 offsetof(struct bpf_prog_info, xlated_prog_len),
10572 [BPF_PROG_INFO_MAP_IDS] = {
10573 offsetof(struct bpf_prog_info, map_ids),
10574 offsetof(struct bpf_prog_info, nr_map_ids),
10575 -(int)sizeof(__u32),
10577 [BPF_PROG_INFO_JITED_KSYMS] = {
10578 offsetof(struct bpf_prog_info, jited_ksyms),
10579 offsetof(struct bpf_prog_info, nr_jited_ksyms),
10580 -(int)sizeof(__u64),
10582 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
10583 offsetof(struct bpf_prog_info, jited_func_lens),
10584 offsetof(struct bpf_prog_info, nr_jited_func_lens),
10585 -(int)sizeof(__u32),
10587 [BPF_PROG_INFO_FUNC_INFO] = {
10588 offsetof(struct bpf_prog_info, func_info),
10589 offsetof(struct bpf_prog_info, nr_func_info),
10590 offsetof(struct bpf_prog_info, func_info_rec_size),
10592 [BPF_PROG_INFO_LINE_INFO] = {
10593 offsetof(struct bpf_prog_info, line_info),
10594 offsetof(struct bpf_prog_info, nr_line_info),
10595 offsetof(struct bpf_prog_info, line_info_rec_size),
10597 [BPF_PROG_INFO_JITED_LINE_INFO] = {
10598 offsetof(struct bpf_prog_info, jited_line_info),
10599 offsetof(struct bpf_prog_info, nr_jited_line_info),
10600 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
10602 [BPF_PROG_INFO_PROG_TAGS] = {
10603 offsetof(struct bpf_prog_info, prog_tags),
10604 offsetof(struct bpf_prog_info, nr_prog_tags),
10605 -(int)sizeof(__u8) * BPF_TAG_SIZE,
10610 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
10613 __u32 *array = (__u32 *)info;
10616 return array[offset / sizeof(__u32)];
10617 return -(int)offset;
10620 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
10623 __u64 *array = (__u64 *)info;
10626 return array[offset / sizeof(__u64)];
10627 return -(int)offset;
10630 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
10633 __u32 *array = (__u32 *)info;
10636 array[offset / sizeof(__u32)] = val;
10639 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
10642 __u64 *array = (__u64 *)info;
10645 array[offset / sizeof(__u64)] = val;
10648 struct bpf_prog_info_linear *
10649 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
10651 struct bpf_prog_info_linear *info_linear;
10652 struct bpf_prog_info info = {};
10653 __u32 info_len = sizeof(info);
10654 __u32 data_len = 0;
10658 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
10659 return libbpf_err_ptr(-EINVAL);
10661 /* step 1: get array dimensions */
10662 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
10664 pr_debug("can't get prog info: %s", strerror(errno));
10665 return libbpf_err_ptr(-EFAULT);
10668 /* step 2: calculate total size of all arrays */
10669 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10670 bool include_array = (arrays & (1UL << i)) > 0;
10671 struct bpf_prog_info_array_desc *desc;
10674 desc = bpf_prog_info_array_desc + i;
10676 /* kernel is too old to support this field */
10677 if (info_len < desc->array_offset + sizeof(__u32) ||
10678 info_len < desc->count_offset + sizeof(__u32) ||
10679 (desc->size_offset > 0 && info_len < desc->size_offset))
10680 include_array = false;
10682 if (!include_array) {
10683 arrays &= ~(1UL << i); /* clear the bit */
10687 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10688 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10690 data_len += count * size;
10693 /* step 3: allocate continuous memory */
10694 data_len = roundup(data_len, sizeof(__u64));
10695 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
10697 return libbpf_err_ptr(-ENOMEM);
10699 /* step 4: fill data to info_linear->info */
10700 info_linear->arrays = arrays;
10701 memset(&info_linear->info, 0, sizeof(info));
10702 ptr = info_linear->data;
10704 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10705 struct bpf_prog_info_array_desc *desc;
10708 if ((arrays & (1UL << i)) == 0)
10711 desc = bpf_prog_info_array_desc + i;
10712 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10713 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10714 bpf_prog_info_set_offset_u32(&info_linear->info,
10715 desc->count_offset, count);
10716 bpf_prog_info_set_offset_u32(&info_linear->info,
10717 desc->size_offset, size);
10718 bpf_prog_info_set_offset_u64(&info_linear->info,
10719 desc->array_offset,
10721 ptr += count * size;
10724 /* step 5: call syscall again to get required arrays */
10725 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
10727 pr_debug("can't get prog info: %s", strerror(errno));
10729 return libbpf_err_ptr(-EFAULT);
10732 /* step 6: verify the data */
10733 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10734 struct bpf_prog_info_array_desc *desc;
10737 if ((arrays & (1UL << i)) == 0)
10740 desc = bpf_prog_info_array_desc + i;
10741 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10742 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10743 desc->count_offset);
10745 pr_warn("%s: mismatch in element count\n", __func__);
10747 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10748 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10749 desc->size_offset);
10751 pr_warn("%s: mismatch in rec size\n", __func__);
10754 /* step 7: update info_len and data_len */
10755 info_linear->info_len = sizeof(struct bpf_prog_info);
10756 info_linear->data_len = data_len;
10758 return info_linear;
10761 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
10765 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10766 struct bpf_prog_info_array_desc *desc;
10769 if ((info_linear->arrays & (1UL << i)) == 0)
10772 desc = bpf_prog_info_array_desc + i;
10773 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
10774 desc->array_offset);
10775 offs = addr - ptr_to_u64(info_linear->data);
10776 bpf_prog_info_set_offset_u64(&info_linear->info,
10777 desc->array_offset, offs);
10781 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
10785 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10786 struct bpf_prog_info_array_desc *desc;
10789 if ((info_linear->arrays & (1UL << i)) == 0)
10792 desc = bpf_prog_info_array_desc + i;
10793 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
10794 desc->array_offset);
10795 addr = offs + ptr_to_u64(info_linear->data);
10796 bpf_prog_info_set_offset_u64(&info_linear->info,
10797 desc->array_offset, addr);
10801 int bpf_program__set_attach_target(struct bpf_program *prog,
10802 int attach_prog_fd,
10803 const char *attach_func_name)
10805 int btf_obj_fd = 0, btf_id = 0, err;
10807 if (!prog || attach_prog_fd < 0)
10808 return libbpf_err(-EINVAL);
10810 if (prog->obj->loaded)
10811 return libbpf_err(-EINVAL);
10813 if (attach_prog_fd && !attach_func_name) {
10814 /* remember attach_prog_fd and let bpf_program__load() find
10815 * BTF ID during the program load
10817 prog->attach_prog_fd = attach_prog_fd;
10821 if (attach_prog_fd) {
10822 btf_id = libbpf_find_prog_btf_id(attach_func_name,
10825 return libbpf_err(btf_id);
10827 if (!attach_func_name)
10828 return libbpf_err(-EINVAL);
10830 /* load btf_vmlinux, if not yet */
10831 err = bpf_object__load_vmlinux_btf(prog->obj, true);
10833 return libbpf_err(err);
10834 err = find_kernel_btf_id(prog->obj, attach_func_name,
10835 prog->expected_attach_type,
10836 &btf_obj_fd, &btf_id);
10838 return libbpf_err(err);
10841 prog->attach_btf_id = btf_id;
10842 prog->attach_btf_obj_fd = btf_obj_fd;
10843 prog->attach_prog_fd = attach_prog_fd;
10847 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
10849 int err = 0, n, len, start, end = -1;
10855 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
10857 if (*s == ',' || *s == '\n') {
10861 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
10862 if (n <= 0 || n > 2) {
10863 pr_warn("Failed to get CPU range %s: %d\n", s, n);
10866 } else if (n == 1) {
10869 if (start < 0 || start > end) {
10870 pr_warn("Invalid CPU range [%d,%d] in %s\n",
10875 tmp = realloc(*mask, end + 1);
10881 memset(tmp + *mask_sz, 0, start - *mask_sz);
10882 memset(tmp + start, 1, end - start + 1);
10883 *mask_sz = end + 1;
10887 pr_warn("Empty CPU range\n");
10897 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
10899 int fd, err = 0, len;
10902 fd = open(fcpu, O_RDONLY);
10905 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
10908 len = read(fd, buf, sizeof(buf));
10911 err = len ? -errno : -EINVAL;
10912 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
10915 if (len >= sizeof(buf)) {
10916 pr_warn("CPU mask is too big in file %s\n", fcpu);
10921 return parse_cpu_mask_str(buf, mask, mask_sz);
10924 int libbpf_num_possible_cpus(void)
10926 static const char *fcpu = "/sys/devices/system/cpu/possible";
10928 int err, n, i, tmp_cpus;
10931 tmp_cpus = READ_ONCE(cpus);
10935 err = parse_cpu_mask_file(fcpu, &mask, &n);
10937 return libbpf_err(err);
10940 for (i = 0; i < n; i++) {
10946 WRITE_ONCE(cpus, tmp_cpus);
10950 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
10951 const struct bpf_object_open_opts *opts)
10953 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
10954 .object_name = s->name,
10956 struct bpf_object *obj;
10959 /* Attempt to preserve opts->object_name, unless overriden by user
10960 * explicitly. Overwriting object name for skeletons is discouraged,
10961 * as it breaks global data maps, because they contain object name
10962 * prefix as their own map name prefix. When skeleton is generated,
10963 * bpftool is making an assumption that this name will stay the same.
10966 memcpy(&skel_opts, opts, sizeof(*opts));
10967 if (!opts->object_name)
10968 skel_opts.object_name = s->name;
10971 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
10972 err = libbpf_get_error(obj);
10974 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
10976 return libbpf_err(err);
10981 for (i = 0; i < s->map_cnt; i++) {
10982 struct bpf_map **map = s->maps[i].map;
10983 const char *name = s->maps[i].name;
10984 void **mmaped = s->maps[i].mmaped;
10986 *map = bpf_object__find_map_by_name(obj, name);
10988 pr_warn("failed to find skeleton map '%s'\n", name);
10989 return libbpf_err(-ESRCH);
10992 /* externs shouldn't be pre-setup from user code */
10993 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
10994 *mmaped = (*map)->mmaped;
10997 for (i = 0; i < s->prog_cnt; i++) {
10998 struct bpf_program **prog = s->progs[i].prog;
10999 const char *name = s->progs[i].name;
11001 *prog = bpf_object__find_program_by_name(obj, name);
11003 pr_warn("failed to find skeleton program '%s'\n", name);
11004 return libbpf_err(-ESRCH);
11011 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11015 err = bpf_object__load(*s->obj);
11017 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
11018 return libbpf_err(err);
11021 for (i = 0; i < s->map_cnt; i++) {
11022 struct bpf_map *map = *s->maps[i].map;
11023 size_t mmap_sz = bpf_map_mmap_sz(map);
11024 int prot, map_fd = bpf_map__fd(map);
11025 void **mmaped = s->maps[i].mmaped;
11030 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11035 if (map->def.map_flags & BPF_F_RDONLY_PROG)
11038 prot = PROT_READ | PROT_WRITE;
11040 /* Remap anonymous mmap()-ed "map initialization image" as
11041 * a BPF map-backed mmap()-ed memory, but preserving the same
11042 * memory address. This will cause kernel to change process'
11043 * page table to point to a different piece of kernel memory,
11044 * but from userspace point of view memory address (and its
11045 * contents, being identical at this point) will stay the
11046 * same. This mapping will be released by bpf_object__close()
11047 * as per normal clean up procedure, so we don't need to worry
11048 * about it from skeleton's clean up perspective.
11050 *mmaped = mmap(map->mmaped, mmap_sz, prot,
11051 MAP_SHARED | MAP_FIXED, map_fd, 0);
11052 if (*mmaped == MAP_FAILED) {
11055 pr_warn("failed to re-mmap() map '%s': %d\n",
11056 bpf_map__name(map), err);
11057 return libbpf_err(err);
11064 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11068 for (i = 0; i < s->prog_cnt; i++) {
11069 struct bpf_program *prog = *s->progs[i].prog;
11070 struct bpf_link **link = s->progs[i].link;
11075 /* auto-attaching not supported for this program */
11076 if (!prog->sec_def || !prog->sec_def->attach_fn)
11079 *link = bpf_program__attach(prog);
11080 err = libbpf_get_error(*link);
11082 pr_warn("failed to auto-attach program '%s': %d\n",
11083 bpf_program__name(prog), err);
11084 return libbpf_err(err);
11091 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11095 for (i = 0; i < s->prog_cnt; i++) {
11096 struct bpf_link **link = s->progs[i].link;
11098 bpf_link__destroy(*link);
11103 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11106 bpf_object__detach_skeleton(s);
11108 bpf_object__close(*s->obj);