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/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
42 #include <sys/types.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
53 #include "str_error.h"
54 #include "libbpf_internal.h"
56 #include "bpf_gen_internal.h"
59 #define BPF_FS_MAGIC 0xcafe4a11
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65 * compilation if user enables corresponding warning. Disable it explicitly.
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
69 #define __printf(a, b) __attribute__((format(printf, a, b)))
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
74 static const char * const attach_type_name[] = {
75 [BPF_CGROUP_INET_INGRESS] = "cgroup_inet_ingress",
76 [BPF_CGROUP_INET_EGRESS] = "cgroup_inet_egress",
77 [BPF_CGROUP_INET_SOCK_CREATE] = "cgroup_inet_sock_create",
78 [BPF_CGROUP_INET_SOCK_RELEASE] = "cgroup_inet_sock_release",
79 [BPF_CGROUP_SOCK_OPS] = "cgroup_sock_ops",
80 [BPF_CGROUP_DEVICE] = "cgroup_device",
81 [BPF_CGROUP_INET4_BIND] = "cgroup_inet4_bind",
82 [BPF_CGROUP_INET6_BIND] = "cgroup_inet6_bind",
83 [BPF_CGROUP_INET4_CONNECT] = "cgroup_inet4_connect",
84 [BPF_CGROUP_INET6_CONNECT] = "cgroup_inet6_connect",
85 [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
86 [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
87 [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
88 [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
89 [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
90 [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
91 [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
92 [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
93 [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
94 [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
95 [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
96 [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
97 [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
98 [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
99 [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
100 [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
101 [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
102 [BPF_LIRC_MODE2] = "lirc_mode2",
103 [BPF_FLOW_DISSECTOR] = "flow_dissector",
104 [BPF_TRACE_RAW_TP] = "trace_raw_tp",
105 [BPF_TRACE_FENTRY] = "trace_fentry",
106 [BPF_TRACE_FEXIT] = "trace_fexit",
107 [BPF_MODIFY_RETURN] = "modify_return",
108 [BPF_LSM_MAC] = "lsm_mac",
109 [BPF_LSM_CGROUP] = "lsm_cgroup",
110 [BPF_SK_LOOKUP] = "sk_lookup",
111 [BPF_TRACE_ITER] = "trace_iter",
112 [BPF_XDP_DEVMAP] = "xdp_devmap",
113 [BPF_XDP_CPUMAP] = "xdp_cpumap",
115 [BPF_SK_REUSEPORT_SELECT] = "sk_reuseport_select",
116 [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE] = "sk_reuseport_select_or_migrate",
117 [BPF_PERF_EVENT] = "perf_event",
118 [BPF_TRACE_KPROBE_MULTI] = "trace_kprobe_multi",
121 static const char * const link_type_name[] = {
122 [BPF_LINK_TYPE_UNSPEC] = "unspec",
123 [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
124 [BPF_LINK_TYPE_TRACING] = "tracing",
125 [BPF_LINK_TYPE_CGROUP] = "cgroup",
126 [BPF_LINK_TYPE_ITER] = "iter",
127 [BPF_LINK_TYPE_NETNS] = "netns",
128 [BPF_LINK_TYPE_XDP] = "xdp",
129 [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
130 [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
131 [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
134 static const char * const map_type_name[] = {
135 [BPF_MAP_TYPE_UNSPEC] = "unspec",
136 [BPF_MAP_TYPE_HASH] = "hash",
137 [BPF_MAP_TYPE_ARRAY] = "array",
138 [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
139 [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
140 [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
141 [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
142 [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
143 [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
144 [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
145 [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
146 [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
147 [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
148 [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
149 [BPF_MAP_TYPE_DEVMAP] = "devmap",
150 [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
151 [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
152 [BPF_MAP_TYPE_CPUMAP] = "cpumap",
153 [BPF_MAP_TYPE_XSKMAP] = "xskmap",
154 [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
155 [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
156 [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
157 [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
158 [BPF_MAP_TYPE_QUEUE] = "queue",
159 [BPF_MAP_TYPE_STACK] = "stack",
160 [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
161 [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
162 [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
163 [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
164 [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
165 [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
168 static const char * const prog_type_name[] = {
169 [BPF_PROG_TYPE_UNSPEC] = "unspec",
170 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
171 [BPF_PROG_TYPE_KPROBE] = "kprobe",
172 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
173 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
174 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
175 [BPF_PROG_TYPE_XDP] = "xdp",
176 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
177 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
178 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
179 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
180 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
181 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
182 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
183 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
184 [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
185 [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
186 [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
187 [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
188 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
189 [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
190 [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
191 [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
192 [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
193 [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
194 [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
195 [BPF_PROG_TYPE_TRACING] = "tracing",
196 [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
197 [BPF_PROG_TYPE_EXT] = "ext",
198 [BPF_PROG_TYPE_LSM] = "lsm",
199 [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
200 [BPF_PROG_TYPE_SYSCALL] = "syscall",
203 static int __base_pr(enum libbpf_print_level level, const char *format,
206 if (level == LIBBPF_DEBUG)
209 return vfprintf(stderr, format, args);
212 static libbpf_print_fn_t __libbpf_pr = __base_pr;
214 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
216 libbpf_print_fn_t old_print_fn = __libbpf_pr;
223 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
233 va_start(args, format);
234 __libbpf_pr(level, format, args);
240 static void pr_perm_msg(int err)
245 if (err != -EPERM || geteuid() != 0)
248 err = getrlimit(RLIMIT_MEMLOCK, &limit);
252 if (limit.rlim_cur == RLIM_INFINITY)
255 if (limit.rlim_cur < 1024)
256 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
257 else if (limit.rlim_cur < 1024*1024)
258 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
260 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
262 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
266 #define STRERR_BUFSIZE 128
268 /* Copied from tools/perf/util/util.h */
270 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
274 # define zclose(fd) ({ \
277 ___err = close((fd)); \
282 static inline __u64 ptr_to_u64(const void *ptr)
284 return (__u64) (unsigned long) ptr;
287 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
289 /* as of v1.0 libbpf_set_strict_mode() is a no-op */
293 __u32 libbpf_major_version(void)
295 return LIBBPF_MAJOR_VERSION;
298 __u32 libbpf_minor_version(void)
300 return LIBBPF_MINOR_VERSION;
303 const char *libbpf_version_string(void)
307 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
323 enum reloc_type type;
326 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
334 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
337 /* expected_attach_type is optional, if kernel doesn't support that */
338 SEC_EXP_ATTACH_OPT = 1,
339 /* legacy, only used by libbpf_get_type_names() and
340 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
341 * This used to be associated with cgroup (and few other) BPF programs
342 * that were attachable through BPF_PROG_ATTACH command. Pretty
343 * meaningless nowadays, though.
346 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
347 /* attachment target is specified through BTF ID in either kernel or
348 * other BPF program's BTF object */
350 /* BPF program type allows sleeping/blocking in kernel */
352 /* BPF program support non-linear XDP buffer */
358 enum bpf_prog_type prog_type;
359 enum bpf_attach_type expected_attach_type;
363 libbpf_prog_setup_fn_t prog_setup_fn;
364 libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
365 libbpf_prog_attach_fn_t prog_attach_fn;
369 * bpf_prog should be a better name but it has been used in
376 const struct bpf_sec_def *sec_def;
377 /* this program's instruction offset (in number of instructions)
378 * within its containing ELF section
381 /* number of original instructions in ELF section belonging to this
382 * program, not taking into account subprogram instructions possible
383 * appended later during relocation
386 /* Offset (in number of instructions) of the start of instruction
387 * belonging to this BPF program within its containing main BPF
388 * program. For the entry-point (main) BPF program, this is always
389 * zero. For a sub-program, this gets reset before each of main BPF
390 * programs are processed and relocated and is used to determined
391 * whether sub-program was already appended to the main program, and
392 * if yes, at which instruction offset.
396 /* instructions that belong to BPF program; insns[0] is located at
397 * sec_insn_off instruction within its ELF section in ELF file, so
398 * when mapping ELF file instruction index to the local instruction,
399 * one needs to subtract sec_insn_off; and vice versa.
401 struct bpf_insn *insns;
402 /* actual number of instruction in this BPF program's image; for
403 * entry-point BPF programs this includes the size of main program
404 * itself plus all the used sub-programs, appended at the end
408 struct reloc_desc *reloc_desc;
411 /* BPF verifier log settings */
416 struct bpf_object *obj;
420 bool mark_btf_static;
421 enum bpf_prog_type type;
422 enum bpf_attach_type expected_attach_type;
425 __u32 attach_btf_obj_fd;
427 __u32 attach_prog_fd;
430 __u32 func_info_rec_size;
434 __u32 line_info_rec_size;
439 struct bpf_struct_ops {
441 const struct btf_type *type;
442 struct bpf_program **progs;
443 __u32 *kern_func_off;
444 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
446 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
447 * btf_vmlinux's format.
448 * struct bpf_struct_ops_tcp_congestion_ops {
449 * [... some other kernel fields ...]
450 * struct tcp_congestion_ops data;
452 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
453 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
460 #define DATA_SEC ".data"
461 #define BSS_SEC ".bss"
462 #define RODATA_SEC ".rodata"
463 #define KCONFIG_SEC ".kconfig"
464 #define KSYMS_SEC ".ksyms"
465 #define STRUCT_OPS_SEC ".struct_ops"
467 enum libbpf_map_type {
477 unsigned int key_size;
478 unsigned int value_size;
479 unsigned int max_entries;
480 unsigned int map_flags;
484 struct bpf_object *obj;
486 /* real_name is defined for special internal maps (.rodata*,
487 * .data*, .bss, .kconfig) and preserves their original ELF section
488 * name. This is important to be be able to find corresponding BTF
489 * DATASEC information.
497 struct bpf_map_def def;
500 __u32 btf_key_type_id;
501 __u32 btf_value_type_id;
502 __u32 btf_vmlinux_value_type_id;
503 enum libbpf_map_type libbpf_type;
505 struct bpf_struct_ops *st_ops;
506 struct bpf_map *inner_map;
532 enum extern_type type;
548 unsigned long long addr;
550 /* target btf_id of the corresponding kernel var. */
551 int kernel_btf_obj_fd;
554 /* local btf_id of the ksym extern's type. */
556 /* BTF fd index to be patched in for insn->off, this is
557 * 0 for vmlinux BTF, index in obj->fd_array for module
581 struct elf_sec_desc {
582 enum sec_type sec_type;
594 Elf_Data *st_ops_data;
595 size_t shstrndx; /* section index for section name strings */
597 struct elf_sec_desc *secs;
600 __u32 btf_maps_sec_btf_id;
609 char name[BPF_OBJ_NAME_LEN];
613 struct bpf_program *programs;
615 struct bpf_map *maps;
620 struct extern_desc *externs;
628 struct bpf_gen *gen_loader;
630 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
631 struct elf_state efile;
634 struct btf_ext *btf_ext;
636 /* Parse and load BTF vmlinux if any of the programs in the object need
639 struct btf *btf_vmlinux;
640 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
641 * override for vmlinux BTF.
643 char *btf_custom_path;
644 /* vmlinux BTF override for CO-RE relocations */
645 struct btf *btf_vmlinux_override;
646 /* Lazily initialized kernel module BTFs */
647 struct module_btf *btf_modules;
648 bool btf_modules_loaded;
649 size_t btf_module_cnt;
650 size_t btf_module_cap;
652 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
661 struct usdt_manager *usdt_man;
666 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
667 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
668 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
669 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
670 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
671 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
672 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
673 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
674 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
676 void bpf_program__unload(struct bpf_program *prog)
683 zfree(&prog->func_info);
684 zfree(&prog->line_info);
687 static void bpf_program__exit(struct bpf_program *prog)
692 bpf_program__unload(prog);
694 zfree(&prog->sec_name);
696 zfree(&prog->reloc_desc);
703 static bool insn_is_subprog_call(const struct bpf_insn *insn)
705 return BPF_CLASS(insn->code) == BPF_JMP &&
706 BPF_OP(insn->code) == BPF_CALL &&
707 BPF_SRC(insn->code) == BPF_K &&
708 insn->src_reg == BPF_PSEUDO_CALL &&
709 insn->dst_reg == 0 &&
713 static bool is_call_insn(const struct bpf_insn *insn)
715 return insn->code == (BPF_JMP | BPF_CALL);
718 static bool insn_is_pseudo_func(struct bpf_insn *insn)
720 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
724 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
725 const char *name, size_t sec_idx, const char *sec_name,
726 size_t sec_off, void *insn_data, size_t insn_data_sz)
728 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
729 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
730 sec_name, name, sec_off, insn_data_sz);
734 memset(prog, 0, sizeof(*prog));
737 prog->sec_idx = sec_idx;
738 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
739 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
740 /* insns_cnt can later be increased by appending used subprograms */
741 prog->insns_cnt = prog->sec_insn_cnt;
743 prog->type = BPF_PROG_TYPE_UNSPEC;
746 /* libbpf's convention for SEC("?abc...") is that it's just like
747 * SEC("abc...") but the corresponding bpf_program starts out with
748 * autoload set to false.
750 if (sec_name[0] == '?') {
751 prog->autoload = false;
752 /* from now on forget there was ? in section name */
755 prog->autoload = true;
758 /* inherit object's log_level */
759 prog->log_level = obj->log_level;
761 prog->sec_name = strdup(sec_name);
765 prog->name = strdup(name);
769 prog->insns = malloc(insn_data_sz);
772 memcpy(prog->insns, insn_data, insn_data_sz);
776 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
777 bpf_program__exit(prog);
782 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
783 const char *sec_name, int sec_idx)
785 Elf_Data *symbols = obj->efile.symbols;
786 struct bpf_program *prog, *progs;
787 void *data = sec_data->d_buf;
788 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
789 int nr_progs, err, i;
793 progs = obj->programs;
794 nr_progs = obj->nr_programs;
795 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
798 for (i = 0; i < nr_syms; i++) {
799 sym = elf_sym_by_idx(obj, i);
801 if (sym->st_shndx != sec_idx)
803 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
806 prog_sz = sym->st_size;
807 sec_off = sym->st_value;
809 name = elf_sym_str(obj, sym->st_name);
811 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
813 return -LIBBPF_ERRNO__FORMAT;
816 if (sec_off + prog_sz > sec_sz) {
817 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
819 return -LIBBPF_ERRNO__FORMAT;
822 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
823 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
827 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
828 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
830 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
833 * In this case the original obj->programs
834 * is still valid, so don't need special treat for
835 * bpf_close_object().
837 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
841 obj->programs = progs;
843 prog = &progs[nr_progs];
845 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
846 sec_off, data + sec_off, prog_sz);
850 /* if function is a global/weak symbol, but has restricted
851 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
852 * as static to enable more permissive BPF verification mode
853 * with more outside context available to BPF verifier
855 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
856 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
857 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
858 prog->mark_btf_static = true;
861 obj->nr_programs = nr_progs;
867 __u32 get_kernel_version(void)
869 /* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
870 * but Ubuntu provides /proc/version_signature file, as described at
871 * https://ubuntu.com/kernel, with an example contents below, which we
872 * can use to get a proper LINUX_VERSION_CODE.
874 * Ubuntu 5.4.0-12.15-generic 5.4.8
876 * In the above, 5.4.8 is what kernel is actually expecting, while
877 * uname() call will return 5.4.0 in info.release.
879 const char *ubuntu_kver_file = "/proc/version_signature";
880 __u32 major, minor, patch;
883 if (access(ubuntu_kver_file, R_OK) == 0) {
886 f = fopen(ubuntu_kver_file, "r");
888 if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
890 return KERNEL_VERSION(major, minor, patch);
894 /* something went wrong, fall back to uname() approach */
898 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
900 return KERNEL_VERSION(major, minor, patch);
903 static const struct btf_member *
904 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
906 struct btf_member *m;
909 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
910 if (btf_member_bit_offset(t, i) == bit_offset)
917 static const struct btf_member *
918 find_member_by_name(const struct btf *btf, const struct btf_type *t,
921 struct btf_member *m;
924 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
925 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
932 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
933 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
934 const char *name, __u32 kind);
937 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
938 const struct btf_type **type, __u32 *type_id,
939 const struct btf_type **vtype, __u32 *vtype_id,
940 const struct btf_member **data_member)
942 const struct btf_type *kern_type, *kern_vtype;
943 const struct btf_member *kern_data_member;
944 __s32 kern_vtype_id, kern_type_id;
947 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
948 if (kern_type_id < 0) {
949 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
953 kern_type = btf__type_by_id(btf, kern_type_id);
955 /* Find the corresponding "map_value" type that will be used
956 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
957 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
960 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
961 tname, BTF_KIND_STRUCT);
962 if (kern_vtype_id < 0) {
963 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
964 STRUCT_OPS_VALUE_PREFIX, tname);
965 return kern_vtype_id;
967 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
969 /* Find "struct tcp_congestion_ops" from
970 * struct bpf_struct_ops_tcp_congestion_ops {
972 * struct tcp_congestion_ops data;
975 kern_data_member = btf_members(kern_vtype);
976 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
977 if (kern_data_member->type == kern_type_id)
980 if (i == btf_vlen(kern_vtype)) {
981 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
982 tname, STRUCT_OPS_VALUE_PREFIX, tname);
987 *type_id = kern_type_id;
989 *vtype_id = kern_vtype_id;
990 *data_member = kern_data_member;
995 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
997 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1000 /* Init the map's fields that depend on kern_btf */
1001 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1002 const struct btf *btf,
1003 const struct btf *kern_btf)
1005 const struct btf_member *member, *kern_member, *kern_data_member;
1006 const struct btf_type *type, *kern_type, *kern_vtype;
1007 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1008 struct bpf_struct_ops *st_ops;
1009 void *data, *kern_data;
1013 st_ops = map->st_ops;
1014 type = st_ops->type;
1015 tname = st_ops->tname;
1016 err = find_struct_ops_kern_types(kern_btf, tname,
1017 &kern_type, &kern_type_id,
1018 &kern_vtype, &kern_vtype_id,
1023 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1024 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1026 map->def.value_size = kern_vtype->size;
1027 map->btf_vmlinux_value_type_id = kern_vtype_id;
1029 st_ops->kern_vdata = calloc(1, kern_vtype->size);
1030 if (!st_ops->kern_vdata)
1033 data = st_ops->data;
1034 kern_data_off = kern_data_member->offset / 8;
1035 kern_data = st_ops->kern_vdata + kern_data_off;
1037 member = btf_members(type);
1038 for (i = 0; i < btf_vlen(type); i++, member++) {
1039 const struct btf_type *mtype, *kern_mtype;
1040 __u32 mtype_id, kern_mtype_id;
1041 void *mdata, *kern_mdata;
1042 __s64 msize, kern_msize;
1043 __u32 moff, kern_moff;
1044 __u32 kern_member_idx;
1047 mname = btf__name_by_offset(btf, member->name_off);
1048 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1050 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1055 kern_member_idx = kern_member - btf_members(kern_type);
1056 if (btf_member_bitfield_size(type, i) ||
1057 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1058 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1063 moff = member->offset / 8;
1064 kern_moff = kern_member->offset / 8;
1066 mdata = data + moff;
1067 kern_mdata = kern_data + kern_moff;
1069 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1070 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1072 if (BTF_INFO_KIND(mtype->info) !=
1073 BTF_INFO_KIND(kern_mtype->info)) {
1074 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1075 map->name, mname, BTF_INFO_KIND(mtype->info),
1076 BTF_INFO_KIND(kern_mtype->info));
1080 if (btf_is_ptr(mtype)) {
1081 struct bpf_program *prog;
1083 prog = st_ops->progs[i];
1087 kern_mtype = skip_mods_and_typedefs(kern_btf,
1091 /* mtype->type must be a func_proto which was
1092 * guaranteed in bpf_object__collect_st_ops_relos(),
1093 * so only check kern_mtype for func_proto here.
1095 if (!btf_is_func_proto(kern_mtype)) {
1096 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1101 prog->attach_btf_id = kern_type_id;
1102 prog->expected_attach_type = kern_member_idx;
1104 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1106 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1107 map->name, mname, prog->name, moff,
1113 msize = btf__resolve_size(btf, mtype_id);
1114 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1115 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1116 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1117 map->name, mname, (ssize_t)msize,
1118 (ssize_t)kern_msize);
1122 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1123 map->name, mname, (unsigned int)msize,
1125 memcpy(kern_mdata, mdata, msize);
1131 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1133 struct bpf_map *map;
1137 for (i = 0; i < obj->nr_maps; i++) {
1138 map = &obj->maps[i];
1140 if (!bpf_map__is_struct_ops(map))
1143 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1152 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1154 const struct btf_type *type, *datasec;
1155 const struct btf_var_secinfo *vsi;
1156 struct bpf_struct_ops *st_ops;
1157 const char *tname, *var_name;
1158 __s32 type_id, datasec_id;
1159 const struct btf *btf;
1160 struct bpf_map *map;
1163 if (obj->efile.st_ops_shndx == -1)
1167 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1169 if (datasec_id < 0) {
1170 pr_warn("struct_ops init: DATASEC %s not found\n",
1175 datasec = btf__type_by_id(btf, datasec_id);
1176 vsi = btf_var_secinfos(datasec);
1177 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1178 type = btf__type_by_id(obj->btf, vsi->type);
1179 var_name = btf__name_by_offset(obj->btf, type->name_off);
1181 type_id = btf__resolve_type(obj->btf, vsi->type);
1183 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1184 vsi->type, STRUCT_OPS_SEC);
1188 type = btf__type_by_id(obj->btf, type_id);
1189 tname = btf__name_by_offset(obj->btf, type->name_off);
1191 pr_warn("struct_ops init: anonymous type is not supported\n");
1194 if (!btf_is_struct(type)) {
1195 pr_warn("struct_ops init: %s is not a struct\n", tname);
1199 map = bpf_object__add_map(obj);
1201 return PTR_ERR(map);
1203 map->sec_idx = obj->efile.st_ops_shndx;
1204 map->sec_offset = vsi->offset;
1205 map->name = strdup(var_name);
1209 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1210 map->def.key_size = sizeof(int);
1211 map->def.value_size = type->size;
1212 map->def.max_entries = 1;
1214 map->st_ops = calloc(1, sizeof(*map->st_ops));
1217 st_ops = map->st_ops;
1218 st_ops->data = malloc(type->size);
1219 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1220 st_ops->kern_func_off = malloc(btf_vlen(type) *
1221 sizeof(*st_ops->kern_func_off));
1222 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1225 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1226 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1227 var_name, STRUCT_OPS_SEC);
1231 memcpy(st_ops->data,
1232 obj->efile.st_ops_data->d_buf + vsi->offset,
1234 st_ops->tname = tname;
1235 st_ops->type = type;
1236 st_ops->type_id = type_id;
1238 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1239 tname, type_id, var_name, vsi->offset);
1245 static struct bpf_object *bpf_object__new(const char *path,
1246 const void *obj_buf,
1248 const char *obj_name)
1250 struct bpf_object *obj;
1253 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1255 pr_warn("alloc memory failed for %s\n", path);
1256 return ERR_PTR(-ENOMEM);
1259 strcpy(obj->path, path);
1261 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1263 /* Using basename() GNU version which doesn't modify arg. */
1264 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1265 end = strchr(obj->name, '.');
1272 * Caller of this function should also call
1273 * bpf_object__elf_finish() after data collection to return
1274 * obj_buf to user. If not, we should duplicate the buffer to
1275 * avoid user freeing them before elf finish.
1277 obj->efile.obj_buf = obj_buf;
1278 obj->efile.obj_buf_sz = obj_buf_sz;
1279 obj->efile.btf_maps_shndx = -1;
1280 obj->efile.st_ops_shndx = -1;
1281 obj->kconfig_map_idx = -1;
1283 obj->kern_version = get_kernel_version();
1284 obj->loaded = false;
1289 static void bpf_object__elf_finish(struct bpf_object *obj)
1291 if (!obj->efile.elf)
1294 elf_end(obj->efile.elf);
1295 obj->efile.elf = NULL;
1296 obj->efile.symbols = NULL;
1297 obj->efile.st_ops_data = NULL;
1299 zfree(&obj->efile.secs);
1300 obj->efile.sec_cnt = 0;
1301 zclose(obj->efile.fd);
1302 obj->efile.obj_buf = NULL;
1303 obj->efile.obj_buf_sz = 0;
1306 static int bpf_object__elf_init(struct bpf_object *obj)
1312 if (obj->efile.elf) {
1313 pr_warn("elf: init internal error\n");
1314 return -LIBBPF_ERRNO__LIBELF;
1317 if (obj->efile.obj_buf_sz > 0) {
1318 /* obj_buf should have been validated by bpf_object__open_mem(). */
1319 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1321 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1322 if (obj->efile.fd < 0) {
1323 char errmsg[STRERR_BUFSIZE], *cp;
1326 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1327 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1331 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1335 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1336 err = -LIBBPF_ERRNO__LIBELF;
1340 obj->efile.elf = elf;
1342 if (elf_kind(elf) != ELF_K_ELF) {
1343 err = -LIBBPF_ERRNO__FORMAT;
1344 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1348 if (gelf_getclass(elf) != ELFCLASS64) {
1349 err = -LIBBPF_ERRNO__FORMAT;
1350 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1354 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1355 if (!obj->efile.ehdr) {
1356 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1357 err = -LIBBPF_ERRNO__FORMAT;
1361 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1362 pr_warn("elf: failed to get section names section index for %s: %s\n",
1363 obj->path, elf_errmsg(-1));
1364 err = -LIBBPF_ERRNO__FORMAT;
1368 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1369 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1370 pr_warn("elf: failed to get section names strings from %s: %s\n",
1371 obj->path, elf_errmsg(-1));
1372 err = -LIBBPF_ERRNO__FORMAT;
1376 /* Old LLVM set e_machine to EM_NONE */
1377 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1378 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1379 err = -LIBBPF_ERRNO__FORMAT;
1385 bpf_object__elf_finish(obj);
1389 static int bpf_object__check_endianness(struct bpf_object *obj)
1391 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1392 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1394 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1395 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1398 # error "Unrecognized __BYTE_ORDER__"
1400 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1401 return -LIBBPF_ERRNO__ENDIAN;
1405 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1407 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1408 * go over allowed ELF data section buffer
1410 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1411 pr_debug("license of %s is %s\n", obj->path, obj->license);
1416 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1420 if (size != sizeof(kver)) {
1421 pr_warn("invalid kver section in %s\n", obj->path);
1422 return -LIBBPF_ERRNO__FORMAT;
1424 memcpy(&kver, data, sizeof(kver));
1425 obj->kern_version = kver;
1426 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1430 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1432 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1433 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1438 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1446 scn = elf_sec_by_name(obj, name);
1447 data = elf_sec_data(obj, scn);
1449 *size = data->d_size;
1450 return 0; /* found it */
1456 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1458 Elf_Data *symbols = obj->efile.symbols;
1465 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1466 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1468 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1471 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1472 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1475 sname = elf_sym_str(obj, sym->st_name);
1477 pr_warn("failed to get sym name string for var %s\n", name);
1480 if (strcmp(name, sname) == 0) {
1481 *off = sym->st_value;
1489 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1491 struct bpf_map *map;
1494 err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1495 sizeof(*obj->maps), obj->nr_maps + 1);
1497 return ERR_PTR(err);
1499 map = &obj->maps[obj->nr_maps++];
1502 map->inner_map_fd = -1;
1503 map->autocreate = true;
1508 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1510 long page_sz = sysconf(_SC_PAGE_SIZE);
1513 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1514 map_sz = roundup(map_sz, page_sz);
1518 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1520 char map_name[BPF_OBJ_NAME_LEN], *p;
1521 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1523 /* This is one of the more confusing parts of libbpf for various
1524 * reasons, some of which are historical. The original idea for naming
1525 * internal names was to include as much of BPF object name prefix as
1526 * possible, so that it can be distinguished from similar internal
1527 * maps of a different BPF object.
1528 * As an example, let's say we have bpf_object named 'my_object_name'
1529 * and internal map corresponding to '.rodata' ELF section. The final
1530 * map name advertised to user and to the kernel will be
1531 * 'my_objec.rodata', taking first 8 characters of object name and
1532 * entire 7 characters of '.rodata'.
1533 * Somewhat confusingly, if internal map ELF section name is shorter
1534 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1535 * for the suffix, even though we only have 4 actual characters, and
1536 * resulting map will be called 'my_objec.bss', not even using all 15
1537 * characters allowed by the kernel. Oh well, at least the truncated
1538 * object name is somewhat consistent in this case. But if the map
1539 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1540 * (8 chars) and thus will be left with only first 7 characters of the
1541 * object name ('my_obje'). Happy guessing, user, that the final map
1542 * name will be "my_obje.kconfig".
1543 * Now, with libbpf starting to support arbitrarily named .rodata.*
1544 * and .data.* data sections, it's possible that ELF section name is
1545 * longer than allowed 15 chars, so we now need to be careful to take
1546 * only up to 15 first characters of ELF name, taking no BPF object
1547 * name characters at all. So '.rodata.abracadabra' will result in
1548 * '.rodata.abracad' kernel and user-visible name.
1549 * We need to keep this convoluted logic intact for .data, .bss and
1550 * .rodata maps, but for new custom .data.custom and .rodata.custom
1551 * maps we use their ELF names as is, not prepending bpf_object name
1552 * in front. We still need to truncate them to 15 characters for the
1553 * kernel. Full name can be recovered for such maps by using DATASEC
1554 * BTF type associated with such map's value type, though.
1556 if (sfx_len >= BPF_OBJ_NAME_LEN)
1557 sfx_len = BPF_OBJ_NAME_LEN - 1;
1559 /* if there are two or more dots in map name, it's a custom dot map */
1560 if (strchr(real_name + 1, '.') != NULL)
1563 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1565 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1566 sfx_len, real_name);
1568 /* sanitise map name to characters allowed by kernel */
1569 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1570 if (!isalnum(*p) && *p != '_' && *p != '.')
1573 return strdup(map_name);
1577 bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1580 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1581 const char *real_name, int sec_idx, void *data, size_t data_sz)
1583 struct bpf_map_def *def;
1584 struct bpf_map *map;
1587 map = bpf_object__add_map(obj);
1589 return PTR_ERR(map);
1591 map->libbpf_type = type;
1592 map->sec_idx = sec_idx;
1593 map->sec_offset = 0;
1594 map->real_name = strdup(real_name);
1595 map->name = internal_map_name(obj, real_name);
1596 if (!map->real_name || !map->name) {
1597 zfree(&map->real_name);
1603 def->type = BPF_MAP_TYPE_ARRAY;
1604 def->key_size = sizeof(int);
1605 def->value_size = data_sz;
1606 def->max_entries = 1;
1607 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1608 ? BPF_F_RDONLY_PROG : 0;
1609 def->map_flags |= BPF_F_MMAPABLE;
1611 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1612 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1614 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1615 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1616 if (map->mmaped == MAP_FAILED) {
1619 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1621 zfree(&map->real_name);
1626 /* failures are fine because of maps like .rodata.str1.1 */
1627 (void) bpf_map_find_btf_info(obj, map);
1630 memcpy(map->mmaped, data, data_sz);
1632 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1636 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1638 struct elf_sec_desc *sec_desc;
1639 const char *sec_name;
1640 int err = 0, sec_idx;
1643 * Populate obj->maps with libbpf internal maps.
1645 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1646 sec_desc = &obj->efile.secs[sec_idx];
1648 /* Skip recognized sections with size 0. */
1649 if (sec_desc->data && sec_desc->data->d_size == 0)
1652 switch (sec_desc->sec_type) {
1654 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1655 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1657 sec_desc->data->d_buf,
1658 sec_desc->data->d_size);
1661 obj->has_rodata = true;
1662 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1663 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1665 sec_desc->data->d_buf,
1666 sec_desc->data->d_size);
1669 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1670 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1673 sec_desc->data->d_size);
1686 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1691 for (i = 0; i < obj->nr_extern; i++) {
1692 if (strcmp(obj->externs[i].name, name) == 0)
1693 return &obj->externs[i];
1698 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1701 switch (ext->kcfg.type) {
1704 pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1708 *(bool *)ext_val = value == 'y' ? true : false;
1712 *(enum libbpf_tristate *)ext_val = TRI_YES;
1713 else if (value == 'm')
1714 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1715 else /* value == 'n' */
1716 *(enum libbpf_tristate *)ext_val = TRI_NO;
1719 *(char *)ext_val = value;
1725 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1733 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1738 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1739 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1744 len = strlen(value);
1745 if (value[len - 1] != '"') {
1746 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1753 if (len >= ext->kcfg.sz) {
1754 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1755 ext->name, value, len, ext->kcfg.sz - 1);
1756 len = ext->kcfg.sz - 1;
1758 memcpy(ext_val, value + 1, len);
1759 ext_val[len] = '\0';
1764 static int parse_u64(const char *value, __u64 *res)
1770 *res = strtoull(value, &value_end, 0);
1773 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1777 pr_warn("failed to parse '%s' as integer completely\n", value);
1783 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1785 int bit_sz = ext->kcfg.sz * 8;
1787 if (ext->kcfg.sz == 8)
1790 /* Validate that value stored in u64 fits in integer of `ext->sz`
1791 * bytes size without any loss of information. If the target integer
1792 * is signed, we rely on the following limits of integer type of
1793 * Y bits and subsequent transformation:
1795 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1796 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1797 * 0 <= X + 2^(Y-1) < 2^Y
1799 * For unsigned target integer, check that all the (64 - Y) bits are
1802 if (ext->kcfg.is_signed)
1803 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1805 return (v >> bit_sz) == 0;
1808 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1811 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1812 ext->kcfg.type != KCFG_BOOL) {
1813 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1814 ext->name, (unsigned long long)value);
1817 if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1818 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1819 ext->name, (unsigned long long)value);
1823 if (!is_kcfg_value_in_range(ext, value)) {
1824 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1825 ext->name, (unsigned long long)value, ext->kcfg.sz);
1828 switch (ext->kcfg.sz) {
1829 case 1: *(__u8 *)ext_val = value; break;
1830 case 2: *(__u16 *)ext_val = value; break;
1831 case 4: *(__u32 *)ext_val = value; break;
1832 case 8: *(__u64 *)ext_val = value; break;
1840 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1841 char *buf, void *data)
1843 struct extern_desc *ext;
1849 if (!str_has_pfx(buf, "CONFIG_"))
1852 sep = strchr(buf, '=');
1854 pr_warn("failed to parse '%s': no separator\n", buf);
1858 /* Trim ending '\n' */
1860 if (buf[len - 1] == '\n')
1861 buf[len - 1] = '\0';
1862 /* Split on '=' and ensure that a value is present. */
1866 pr_warn("failed to parse '%s': no value\n", buf);
1870 ext = find_extern_by_name(obj, buf);
1871 if (!ext || ext->is_set)
1874 ext_val = data + ext->kcfg.data_off;
1878 case 'y': case 'n': case 'm':
1879 err = set_kcfg_value_tri(ext, ext_val, *value);
1882 err = set_kcfg_value_str(ext, ext_val, value);
1885 /* assume integer */
1886 err = parse_u64(value, &num);
1888 pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1891 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1892 pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1895 err = set_kcfg_value_num(ext, ext_val, num);
1900 pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1904 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1912 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1915 else if (len >= PATH_MAX)
1916 return -ENAMETOOLONG;
1918 /* gzopen also accepts uncompressed files. */
1919 file = gzopen(buf, "r");
1921 file = gzopen("/proc/config.gz", "r");
1924 pr_warn("failed to open system Kconfig\n");
1928 while (gzgets(file, buf, sizeof(buf))) {
1929 err = bpf_object__process_kconfig_line(obj, buf, data);
1931 pr_warn("error parsing system Kconfig line '%s': %d\n",
1942 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1943 const char *config, void *data)
1949 file = fmemopen((void *)config, strlen(config), "r");
1952 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1956 while (fgets(buf, sizeof(buf), file)) {
1957 err = bpf_object__process_kconfig_line(obj, buf, data);
1959 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1969 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1971 struct extern_desc *last_ext = NULL, *ext;
1975 for (i = 0; i < obj->nr_extern; i++) {
1976 ext = &obj->externs[i];
1977 if (ext->type == EXT_KCFG)
1984 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1985 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1986 ".kconfig", obj->efile.symbols_shndx,
1991 obj->kconfig_map_idx = obj->nr_maps - 1;
1996 const struct btf_type *
1997 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1999 const struct btf_type *t = btf__type_by_id(btf, id);
2004 while (btf_is_mod(t) || btf_is_typedef(t)) {
2007 t = btf__type_by_id(btf, t->type);
2013 static const struct btf_type *
2014 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2016 const struct btf_type *t;
2018 t = skip_mods_and_typedefs(btf, id, NULL);
2022 t = skip_mods_and_typedefs(btf, t->type, res_id);
2024 return btf_is_func_proto(t) ? t : NULL;
2027 static const char *__btf_kind_str(__u16 kind)
2030 case BTF_KIND_UNKN: return "void";
2031 case BTF_KIND_INT: return "int";
2032 case BTF_KIND_PTR: return "ptr";
2033 case BTF_KIND_ARRAY: return "array";
2034 case BTF_KIND_STRUCT: return "struct";
2035 case BTF_KIND_UNION: return "union";
2036 case BTF_KIND_ENUM: return "enum";
2037 case BTF_KIND_FWD: return "fwd";
2038 case BTF_KIND_TYPEDEF: return "typedef";
2039 case BTF_KIND_VOLATILE: return "volatile";
2040 case BTF_KIND_CONST: return "const";
2041 case BTF_KIND_RESTRICT: return "restrict";
2042 case BTF_KIND_FUNC: return "func";
2043 case BTF_KIND_FUNC_PROTO: return "func_proto";
2044 case BTF_KIND_VAR: return "var";
2045 case BTF_KIND_DATASEC: return "datasec";
2046 case BTF_KIND_FLOAT: return "float";
2047 case BTF_KIND_DECL_TAG: return "decl_tag";
2048 case BTF_KIND_TYPE_TAG: return "type_tag";
2049 case BTF_KIND_ENUM64: return "enum64";
2050 default: return "unknown";
2054 const char *btf_kind_str(const struct btf_type *t)
2056 return __btf_kind_str(btf_kind(t));
2060 * Fetch integer attribute of BTF map definition. Such attributes are
2061 * represented using a pointer to an array, in which dimensionality of array
2062 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2063 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2064 * type definition, while using only sizeof(void *) space in ELF data section.
2066 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2067 const struct btf_member *m, __u32 *res)
2069 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2070 const char *name = btf__name_by_offset(btf, m->name_off);
2071 const struct btf_array *arr_info;
2072 const struct btf_type *arr_t;
2074 if (!btf_is_ptr(t)) {
2075 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2076 map_name, name, btf_kind_str(t));
2080 arr_t = btf__type_by_id(btf, t->type);
2082 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2083 map_name, name, t->type);
2086 if (!btf_is_array(arr_t)) {
2087 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2088 map_name, name, btf_kind_str(arr_t));
2091 arr_info = btf_array(arr_t);
2092 *res = arr_info->nelems;
2096 static int build_map_pin_path(struct bpf_map *map, const char *path)
2102 path = "/sys/fs/bpf";
2104 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2107 else if (len >= PATH_MAX)
2108 return -ENAMETOOLONG;
2110 return bpf_map__set_pin_path(map, buf);
2113 /* should match definition in bpf_helpers.h */
2114 enum libbpf_pin_type {
2116 /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2120 int parse_btf_map_def(const char *map_name, struct btf *btf,
2121 const struct btf_type *def_t, bool strict,
2122 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2124 const struct btf_type *t;
2125 const struct btf_member *m;
2126 bool is_inner = inner_def == NULL;
2129 vlen = btf_vlen(def_t);
2130 m = btf_members(def_t);
2131 for (i = 0; i < vlen; i++, m++) {
2132 const char *name = btf__name_by_offset(btf, m->name_off);
2135 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2138 if (strcmp(name, "type") == 0) {
2139 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2141 map_def->parts |= MAP_DEF_MAP_TYPE;
2142 } else if (strcmp(name, "max_entries") == 0) {
2143 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2145 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2146 } else if (strcmp(name, "map_flags") == 0) {
2147 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2149 map_def->parts |= MAP_DEF_MAP_FLAGS;
2150 } else if (strcmp(name, "numa_node") == 0) {
2151 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2153 map_def->parts |= MAP_DEF_NUMA_NODE;
2154 } else if (strcmp(name, "key_size") == 0) {
2157 if (!get_map_field_int(map_name, btf, m, &sz))
2159 if (map_def->key_size && map_def->key_size != sz) {
2160 pr_warn("map '%s': conflicting key size %u != %u.\n",
2161 map_name, map_def->key_size, sz);
2164 map_def->key_size = sz;
2165 map_def->parts |= MAP_DEF_KEY_SIZE;
2166 } else if (strcmp(name, "key") == 0) {
2169 t = btf__type_by_id(btf, m->type);
2171 pr_warn("map '%s': key type [%d] not found.\n",
2175 if (!btf_is_ptr(t)) {
2176 pr_warn("map '%s': key spec is not PTR: %s.\n",
2177 map_name, btf_kind_str(t));
2180 sz = btf__resolve_size(btf, t->type);
2182 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2183 map_name, t->type, (ssize_t)sz);
2186 if (map_def->key_size && map_def->key_size != sz) {
2187 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2188 map_name, map_def->key_size, (ssize_t)sz);
2191 map_def->key_size = sz;
2192 map_def->key_type_id = t->type;
2193 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2194 } else if (strcmp(name, "value_size") == 0) {
2197 if (!get_map_field_int(map_name, btf, m, &sz))
2199 if (map_def->value_size && map_def->value_size != sz) {
2200 pr_warn("map '%s': conflicting value size %u != %u.\n",
2201 map_name, map_def->value_size, sz);
2204 map_def->value_size = sz;
2205 map_def->parts |= MAP_DEF_VALUE_SIZE;
2206 } else if (strcmp(name, "value") == 0) {
2209 t = btf__type_by_id(btf, m->type);
2211 pr_warn("map '%s': value type [%d] not found.\n",
2215 if (!btf_is_ptr(t)) {
2216 pr_warn("map '%s': value spec is not PTR: %s.\n",
2217 map_name, btf_kind_str(t));
2220 sz = btf__resolve_size(btf, t->type);
2222 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2223 map_name, t->type, (ssize_t)sz);
2226 if (map_def->value_size && map_def->value_size != sz) {
2227 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2228 map_name, map_def->value_size, (ssize_t)sz);
2231 map_def->value_size = sz;
2232 map_def->value_type_id = t->type;
2233 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2235 else if (strcmp(name, "values") == 0) {
2236 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2237 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2238 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2239 char inner_map_name[128];
2243 pr_warn("map '%s': multi-level inner maps not supported.\n",
2247 if (i != vlen - 1) {
2248 pr_warn("map '%s': '%s' member should be last.\n",
2252 if (!is_map_in_map && !is_prog_array) {
2253 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2257 if (map_def->value_size && map_def->value_size != 4) {
2258 pr_warn("map '%s': conflicting value size %u != 4.\n",
2259 map_name, map_def->value_size);
2262 map_def->value_size = 4;
2263 t = btf__type_by_id(btf, m->type);
2265 pr_warn("map '%s': %s type [%d] not found.\n",
2266 map_name, desc, m->type);
2269 if (!btf_is_array(t) || btf_array(t)->nelems) {
2270 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2274 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2275 if (!btf_is_ptr(t)) {
2276 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2277 map_name, desc, btf_kind_str(t));
2280 t = skip_mods_and_typedefs(btf, t->type, NULL);
2281 if (is_prog_array) {
2282 if (!btf_is_func_proto(t)) {
2283 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2284 map_name, btf_kind_str(t));
2289 if (!btf_is_struct(t)) {
2290 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2291 map_name, btf_kind_str(t));
2295 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2296 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2300 map_def->parts |= MAP_DEF_INNER_MAP;
2301 } else if (strcmp(name, "pinning") == 0) {
2305 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2308 if (!get_map_field_int(map_name, btf, m, &val))
2310 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2311 pr_warn("map '%s': invalid pinning value %u.\n",
2315 map_def->pinning = val;
2316 map_def->parts |= MAP_DEF_PINNING;
2317 } else if (strcmp(name, "map_extra") == 0) {
2320 if (!get_map_field_int(map_name, btf, m, &map_extra))
2322 map_def->map_extra = map_extra;
2323 map_def->parts |= MAP_DEF_MAP_EXTRA;
2326 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2329 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2333 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2334 pr_warn("map '%s': map type isn't specified.\n", map_name);
2341 static size_t adjust_ringbuf_sz(size_t sz)
2343 __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2346 /* if user forgot to set any size, make sure they see error */
2349 /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2350 * a power-of-2 multiple of kernel's page size. If user diligently
2351 * satisified these conditions, pass the size through.
2353 if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2356 /* Otherwise find closest (page_sz * power_of_2) product bigger than
2357 * user-set size to satisfy both user size request and kernel
2358 * requirements and substitute correct max_entries for map creation.
2360 for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2361 if (mul * page_sz > sz)
2362 return mul * page_sz;
2365 /* if it's impossible to satisfy the conditions (i.e., user size is
2366 * very close to UINT_MAX but is not a power-of-2 multiple of
2367 * page_size) then just return original size and let kernel reject it
2372 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2374 map->def.type = def->map_type;
2375 map->def.key_size = def->key_size;
2376 map->def.value_size = def->value_size;
2377 map->def.max_entries = def->max_entries;
2378 map->def.map_flags = def->map_flags;
2379 map->map_extra = def->map_extra;
2381 map->numa_node = def->numa_node;
2382 map->btf_key_type_id = def->key_type_id;
2383 map->btf_value_type_id = def->value_type_id;
2385 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2386 if (map->def.type == BPF_MAP_TYPE_RINGBUF)
2387 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2389 if (def->parts & MAP_DEF_MAP_TYPE)
2390 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2392 if (def->parts & MAP_DEF_KEY_TYPE)
2393 pr_debug("map '%s': found key [%u], sz = %u.\n",
2394 map->name, def->key_type_id, def->key_size);
2395 else if (def->parts & MAP_DEF_KEY_SIZE)
2396 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2398 if (def->parts & MAP_DEF_VALUE_TYPE)
2399 pr_debug("map '%s': found value [%u], sz = %u.\n",
2400 map->name, def->value_type_id, def->value_size);
2401 else if (def->parts & MAP_DEF_VALUE_SIZE)
2402 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2404 if (def->parts & MAP_DEF_MAX_ENTRIES)
2405 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2406 if (def->parts & MAP_DEF_MAP_FLAGS)
2407 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2408 if (def->parts & MAP_DEF_MAP_EXTRA)
2409 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2410 (unsigned long long)def->map_extra);
2411 if (def->parts & MAP_DEF_PINNING)
2412 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2413 if (def->parts & MAP_DEF_NUMA_NODE)
2414 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2416 if (def->parts & MAP_DEF_INNER_MAP)
2417 pr_debug("map '%s': found inner map definition.\n", map->name);
2420 static const char *btf_var_linkage_str(__u32 linkage)
2423 case BTF_VAR_STATIC: return "static";
2424 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2425 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2426 default: return "unknown";
2430 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2431 const struct btf_type *sec,
2432 int var_idx, int sec_idx,
2433 const Elf_Data *data, bool strict,
2434 const char *pin_root_path)
2436 struct btf_map_def map_def = {}, inner_def = {};
2437 const struct btf_type *var, *def;
2438 const struct btf_var_secinfo *vi;
2439 const struct btf_var *var_extra;
2440 const char *map_name;
2441 struct bpf_map *map;
2444 vi = btf_var_secinfos(sec) + var_idx;
2445 var = btf__type_by_id(obj->btf, vi->type);
2446 var_extra = btf_var(var);
2447 map_name = btf__name_by_offset(obj->btf, var->name_off);
2449 if (map_name == NULL || map_name[0] == '\0') {
2450 pr_warn("map #%d: empty name.\n", var_idx);
2453 if ((__u64)vi->offset + vi->size > data->d_size) {
2454 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2457 if (!btf_is_var(var)) {
2458 pr_warn("map '%s': unexpected var kind %s.\n",
2459 map_name, btf_kind_str(var));
2462 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2463 pr_warn("map '%s': unsupported map linkage %s.\n",
2464 map_name, btf_var_linkage_str(var_extra->linkage));
2468 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2469 if (!btf_is_struct(def)) {
2470 pr_warn("map '%s': unexpected def kind %s.\n",
2471 map_name, btf_kind_str(var));
2474 if (def->size > vi->size) {
2475 pr_warn("map '%s': invalid def size.\n", map_name);
2479 map = bpf_object__add_map(obj);
2481 return PTR_ERR(map);
2482 map->name = strdup(map_name);
2484 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2487 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2488 map->def.type = BPF_MAP_TYPE_UNSPEC;
2489 map->sec_idx = sec_idx;
2490 map->sec_offset = vi->offset;
2491 map->btf_var_idx = var_idx;
2492 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2493 map_name, map->sec_idx, map->sec_offset);
2495 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2499 fill_map_from_def(map, &map_def);
2501 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2502 err = build_map_pin_path(map, pin_root_path);
2504 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2509 if (map_def.parts & MAP_DEF_INNER_MAP) {
2510 map->inner_map = calloc(1, sizeof(*map->inner_map));
2511 if (!map->inner_map)
2513 map->inner_map->fd = -1;
2514 map->inner_map->sec_idx = sec_idx;
2515 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2516 if (!map->inner_map->name)
2518 sprintf(map->inner_map->name, "%s.inner", map_name);
2520 fill_map_from_def(map->inner_map, &inner_def);
2523 err = bpf_map_find_btf_info(obj, map);
2530 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2531 const char *pin_root_path)
2533 const struct btf_type *sec = NULL;
2534 int nr_types, i, vlen, err;
2535 const struct btf_type *t;
2540 if (obj->efile.btf_maps_shndx < 0)
2543 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2544 data = elf_sec_data(obj, scn);
2545 if (!scn || !data) {
2546 pr_warn("elf: failed to get %s map definitions for %s\n",
2547 MAPS_ELF_SEC, obj->path);
2551 nr_types = btf__type_cnt(obj->btf);
2552 for (i = 1; i < nr_types; i++) {
2553 t = btf__type_by_id(obj->btf, i);
2554 if (!btf_is_datasec(t))
2556 name = btf__name_by_offset(obj->btf, t->name_off);
2557 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2559 obj->efile.btf_maps_sec_btf_id = i;
2565 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2569 vlen = btf_vlen(sec);
2570 for (i = 0; i < vlen; i++) {
2571 err = bpf_object__init_user_btf_map(obj, sec, i,
2572 obj->efile.btf_maps_shndx,
2582 static int bpf_object__init_maps(struct bpf_object *obj,
2583 const struct bpf_object_open_opts *opts)
2585 const char *pin_root_path;
2589 strict = !OPTS_GET(opts, relaxed_maps, false);
2590 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2592 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2593 err = err ?: bpf_object__init_global_data_maps(obj);
2594 err = err ?: bpf_object__init_kconfig_map(obj);
2595 err = err ?: bpf_object__init_struct_ops_maps(obj);
2600 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2604 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2608 return sh->sh_flags & SHF_EXECINSTR;
2611 static bool btf_needs_sanitization(struct bpf_object *obj)
2613 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2614 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2615 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2616 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2617 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2618 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2619 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2621 return !has_func || !has_datasec || !has_func_global || !has_float ||
2622 !has_decl_tag || !has_type_tag || !has_enum64;
2625 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2627 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2628 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2629 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2630 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2631 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2632 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2633 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2634 int enum64_placeholder_id = 0;
2638 for (i = 1; i < btf__type_cnt(btf); i++) {
2639 t = (struct btf_type *)btf__type_by_id(btf, i);
2641 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2642 /* replace VAR/DECL_TAG with INT */
2643 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2645 * using size = 1 is the safest choice, 4 will be too
2646 * big and cause kernel BTF validation failure if
2647 * original variable took less than 4 bytes
2650 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2651 } else if (!has_datasec && btf_is_datasec(t)) {
2652 /* replace DATASEC with STRUCT */
2653 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2654 struct btf_member *m = btf_members(t);
2655 struct btf_type *vt;
2658 name = (char *)btf__name_by_offset(btf, t->name_off);
2666 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2667 for (j = 0; j < vlen; j++, v++, m++) {
2668 /* order of field assignments is important */
2669 m->offset = v->offset * 8;
2671 /* preserve variable name as member name */
2672 vt = (void *)btf__type_by_id(btf, v->type);
2673 m->name_off = vt->name_off;
2675 } else if (!has_func && btf_is_func_proto(t)) {
2676 /* replace FUNC_PROTO with ENUM */
2678 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2679 t->size = sizeof(__u32); /* kernel enforced */
2680 } else if (!has_func && btf_is_func(t)) {
2681 /* replace FUNC with TYPEDEF */
2682 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2683 } else if (!has_func_global && btf_is_func(t)) {
2684 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2685 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2686 } else if (!has_float && btf_is_float(t)) {
2687 /* replace FLOAT with an equally-sized empty STRUCT;
2688 * since C compilers do not accept e.g. "float" as a
2689 * valid struct name, make it anonymous
2692 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2693 } else if (!has_type_tag && btf_is_type_tag(t)) {
2694 /* replace TYPE_TAG with a CONST */
2696 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2697 } else if (!has_enum64 && btf_is_enum(t)) {
2698 /* clear the kflag */
2699 t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2700 } else if (!has_enum64 && btf_is_enum64(t)) {
2701 /* replace ENUM64 with a union */
2702 struct btf_member *m;
2704 if (enum64_placeholder_id == 0) {
2705 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2706 if (enum64_placeholder_id < 0)
2707 return enum64_placeholder_id;
2709 t = (struct btf_type *)btf__type_by_id(btf, i);
2714 t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2715 for (j = 0; j < vlen; j++, m++) {
2716 m->type = enum64_placeholder_id;
2725 static bool libbpf_needs_btf(const struct bpf_object *obj)
2727 return obj->efile.btf_maps_shndx >= 0 ||
2728 obj->efile.st_ops_shndx >= 0 ||
2732 static bool kernel_needs_btf(const struct bpf_object *obj)
2734 return obj->efile.st_ops_shndx >= 0;
2737 static int bpf_object__init_btf(struct bpf_object *obj,
2739 Elf_Data *btf_ext_data)
2744 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2745 err = libbpf_get_error(obj->btf);
2748 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2751 /* enforce 8-byte pointers for BPF-targeted BTFs */
2752 btf__set_pointer_size(obj->btf, 8);
2755 struct btf_ext_info *ext_segs[3];
2756 int seg_num, sec_num;
2759 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2760 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2763 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2764 err = libbpf_get_error(obj->btf_ext);
2766 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2767 BTF_EXT_ELF_SEC, err);
2768 obj->btf_ext = NULL;
2772 /* setup .BTF.ext to ELF section mapping */
2773 ext_segs[0] = &obj->btf_ext->func_info;
2774 ext_segs[1] = &obj->btf_ext->line_info;
2775 ext_segs[2] = &obj->btf_ext->core_relo_info;
2776 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2777 struct btf_ext_info *seg = ext_segs[seg_num];
2778 const struct btf_ext_info_sec *sec;
2779 const char *sec_name;
2782 if (seg->sec_cnt == 0)
2785 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2786 if (!seg->sec_idxs) {
2792 for_each_btf_ext_sec(seg, sec) {
2793 /* preventively increment index to avoid doing
2794 * this before every continue below
2798 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2799 if (str_is_empty(sec_name))
2801 scn = elf_sec_by_name(obj, sec_name);
2805 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2810 if (err && libbpf_needs_btf(obj)) {
2811 pr_warn("BTF is required, but is missing or corrupted.\n");
2817 static int compare_vsi_off(const void *_a, const void *_b)
2819 const struct btf_var_secinfo *a = _a;
2820 const struct btf_var_secinfo *b = _b;
2822 return a->offset - b->offset;
2825 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2828 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
2829 const char *name = btf__name_by_offset(btf, t->name_off);
2830 const struct btf_type *t_var;
2831 struct btf_var_secinfo *vsi;
2832 const struct btf_var *var;
2836 pr_debug("No name found in string section for DATASEC kind.\n");
2840 /* .extern datasec size and var offsets were set correctly during
2841 * extern collection step, so just skip straight to sorting variables
2846 ret = find_elf_sec_sz(obj, name, &size);
2848 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2854 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2855 t_var = btf__type_by_id(btf, vsi->type);
2856 if (!t_var || !btf_is_var(t_var)) {
2857 pr_debug("Non-VAR type seen in section %s\n", name);
2861 var = btf_var(t_var);
2862 if (var->linkage == BTF_VAR_STATIC)
2865 name = btf__name_by_offset(btf, t_var->name_off);
2867 pr_debug("No name found in string section for VAR kind\n");
2871 ret = find_elf_var_offset(obj, name, &off);
2873 pr_debug("No offset found in symbol table for VAR %s\n",
2882 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2886 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2889 __u32 i, n = btf__type_cnt(btf);
2891 for (i = 1; i < n; i++) {
2892 struct btf_type *t = btf_type_by_id(btf, i);
2894 /* Loader needs to fix up some of the things compiler
2895 * couldn't get its hands on while emitting BTF. This
2896 * is section size and global variable offset. We use
2897 * the info from the ELF itself for this purpose.
2899 if (btf_is_datasec(t)) {
2900 err = btf_fixup_datasec(obj, btf, t);
2906 return libbpf_err(err);
2909 static int bpf_object__finalize_btf(struct bpf_object *obj)
2916 err = btf_finalize_data(obj, obj->btf);
2918 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2925 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2927 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2928 prog->type == BPF_PROG_TYPE_LSM)
2931 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2932 * also need vmlinux BTF
2934 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2940 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2942 struct bpf_program *prog;
2945 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2948 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2951 /* Support for typed ksyms needs kernel BTF */
2952 for (i = 0; i < obj->nr_extern; i++) {
2953 const struct extern_desc *ext;
2955 ext = &obj->externs[i];
2956 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2960 bpf_object__for_each_program(prog, obj) {
2961 if (!prog->autoload)
2963 if (prog_needs_vmlinux_btf(prog))
2970 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2974 /* btf_vmlinux could be loaded earlier */
2975 if (obj->btf_vmlinux || obj->gen_loader)
2978 if (!force && !obj_needs_vmlinux_btf(obj))
2981 obj->btf_vmlinux = btf__load_vmlinux_btf();
2982 err = libbpf_get_error(obj->btf_vmlinux);
2984 pr_warn("Error loading vmlinux BTF: %d\n", err);
2985 obj->btf_vmlinux = NULL;
2991 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2993 struct btf *kern_btf = obj->btf;
2994 bool btf_mandatory, sanitize;
3000 if (!kernel_supports(obj, FEAT_BTF)) {
3001 if (kernel_needs_btf(obj)) {
3005 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3009 /* Even though some subprogs are global/weak, user might prefer more
3010 * permissive BPF verification process that BPF verifier performs for
3011 * static functions, taking into account more context from the caller
3012 * functions. In such case, they need to mark such subprogs with
3013 * __attribute__((visibility("hidden"))) and libbpf will adjust
3014 * corresponding FUNC BTF type to be marked as static and trigger more
3015 * involved BPF verification process.
3017 for (i = 0; i < obj->nr_programs; i++) {
3018 struct bpf_program *prog = &obj->programs[i];
3023 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3026 n = btf__type_cnt(obj->btf);
3027 for (j = 1; j < n; j++) {
3028 t = btf_type_by_id(obj->btf, j);
3029 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3032 name = btf__str_by_offset(obj->btf, t->name_off);
3033 if (strcmp(name, prog->name) != 0)
3036 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3041 sanitize = btf_needs_sanitization(obj);
3043 const void *raw_data;
3046 /* clone BTF to sanitize a copy and leave the original intact */
3047 raw_data = btf__raw_data(obj->btf, &sz);
3048 kern_btf = btf__new(raw_data, sz);
3049 err = libbpf_get_error(kern_btf);
3053 /* enforce 8-byte pointers for BPF-targeted BTFs */
3054 btf__set_pointer_size(obj->btf, 8);
3055 err = bpf_object__sanitize_btf(obj, kern_btf);
3060 if (obj->gen_loader) {
3062 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3066 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3067 /* Pretend to have valid FD to pass various fd >= 0 checks.
3068 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3070 btf__set_fd(kern_btf, 0);
3072 /* currently BPF_BTF_LOAD only supports log_level 1 */
3073 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3074 obj->log_level ? 1 : 0);
3078 /* move fd to libbpf's BTF */
3079 btf__set_fd(obj->btf, btf__fd(kern_btf));
3080 btf__set_fd(kern_btf, -1);
3082 btf__free(kern_btf);
3086 btf_mandatory = kernel_needs_btf(obj);
3087 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3088 btf_mandatory ? "BTF is mandatory, can't proceed."
3089 : "BTF is optional, ignoring.");
3096 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3100 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3102 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3103 off, obj->path, elf_errmsg(-1));
3110 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3114 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3116 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3117 off, obj->path, elf_errmsg(-1));
3124 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3128 scn = elf_getscn(obj->efile.elf, idx);
3130 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3131 idx, obj->path, elf_errmsg(-1));
3137 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3139 Elf_Scn *scn = NULL;
3140 Elf *elf = obj->efile.elf;
3141 const char *sec_name;
3143 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3144 sec_name = elf_sec_name(obj, scn);
3148 if (strcmp(sec_name, name) != 0)
3156 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3163 shdr = elf64_getshdr(scn);
3165 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3166 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3173 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3181 sh = elf_sec_hdr(obj, scn);
3185 name = elf_sec_str(obj, sh->sh_name);
3187 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3188 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3195 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3202 data = elf_getdata(scn, 0);
3204 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3205 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3206 obj->path, elf_errmsg(-1));
3213 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3215 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3218 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3221 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3223 if (idx >= data->d_size / sizeof(Elf64_Rel))
3226 return (Elf64_Rel *)data->d_buf + idx;
3229 static bool is_sec_name_dwarf(const char *name)
3231 /* approximation, but the actual list is too long */
3232 return str_has_pfx(name, ".debug_");
3235 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3237 /* no special handling of .strtab */
3238 if (hdr->sh_type == SHT_STRTAB)
3241 /* ignore .llvm_addrsig section as well */
3242 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3245 /* no subprograms will lead to an empty .text section, ignore it */
3246 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3247 strcmp(name, ".text") == 0)
3250 /* DWARF sections */
3251 if (is_sec_name_dwarf(name))
3254 if (str_has_pfx(name, ".rel")) {
3255 name += sizeof(".rel") - 1;
3256 /* DWARF section relocations */
3257 if (is_sec_name_dwarf(name))
3260 /* .BTF and .BTF.ext don't need relocations */
3261 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3262 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3269 static int cmp_progs(const void *_a, const void *_b)
3271 const struct bpf_program *a = _a;
3272 const struct bpf_program *b = _b;
3274 if (a->sec_idx != b->sec_idx)
3275 return a->sec_idx < b->sec_idx ? -1 : 1;
3277 /* sec_insn_off can't be the same within the section */
3278 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3281 static int bpf_object__elf_collect(struct bpf_object *obj)
3283 struct elf_sec_desc *sec_desc;
3284 Elf *elf = obj->efile.elf;
3285 Elf_Data *btf_ext_data = NULL;
3286 Elf_Data *btf_data = NULL;
3287 int idx = 0, err = 0;
3293 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3294 * section. e_shnum does include sec #0, so e_shnum is the necessary
3295 * size of an array to keep all the sections.
3297 obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3298 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3299 if (!obj->efile.secs)
3302 /* a bunch of ELF parsing functionality depends on processing symbols,
3303 * so do the first pass and find the symbol table
3306 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3307 sh = elf_sec_hdr(obj, scn);
3309 return -LIBBPF_ERRNO__FORMAT;
3311 if (sh->sh_type == SHT_SYMTAB) {
3312 if (obj->efile.symbols) {
3313 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3314 return -LIBBPF_ERRNO__FORMAT;
3317 data = elf_sec_data(obj, scn);
3319 return -LIBBPF_ERRNO__FORMAT;
3321 idx = elf_ndxscn(scn);
3323 obj->efile.symbols = data;
3324 obj->efile.symbols_shndx = idx;
3325 obj->efile.strtabidx = sh->sh_link;
3329 if (!obj->efile.symbols) {
3330 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3336 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3337 idx = elf_ndxscn(scn);
3338 sec_desc = &obj->efile.secs[idx];
3340 sh = elf_sec_hdr(obj, scn);
3342 return -LIBBPF_ERRNO__FORMAT;
3344 name = elf_sec_str(obj, sh->sh_name);
3346 return -LIBBPF_ERRNO__FORMAT;
3348 if (ignore_elf_section(sh, name))
3351 data = elf_sec_data(obj, scn);
3353 return -LIBBPF_ERRNO__FORMAT;
3355 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3356 idx, name, (unsigned long)data->d_size,
3357 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3360 if (strcmp(name, "license") == 0) {
3361 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3364 } else if (strcmp(name, "version") == 0) {
3365 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3368 } else if (strcmp(name, "maps") == 0) {
3369 pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3371 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3372 obj->efile.btf_maps_shndx = idx;
3373 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3374 if (sh->sh_type != SHT_PROGBITS)
3375 return -LIBBPF_ERRNO__FORMAT;
3377 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3378 if (sh->sh_type != SHT_PROGBITS)
3379 return -LIBBPF_ERRNO__FORMAT;
3380 btf_ext_data = data;
3381 } else if (sh->sh_type == SHT_SYMTAB) {
3382 /* already processed during the first pass above */
3383 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3384 if (sh->sh_flags & SHF_EXECINSTR) {
3385 if (strcmp(name, ".text") == 0)
3386 obj->efile.text_shndx = idx;
3387 err = bpf_object__add_programs(obj, data, name, idx);
3390 } else if (strcmp(name, DATA_SEC) == 0 ||
3391 str_has_pfx(name, DATA_SEC ".")) {
3392 sec_desc->sec_type = SEC_DATA;
3393 sec_desc->shdr = sh;
3394 sec_desc->data = data;
3395 } else if (strcmp(name, RODATA_SEC) == 0 ||
3396 str_has_pfx(name, RODATA_SEC ".")) {
3397 sec_desc->sec_type = SEC_RODATA;
3398 sec_desc->shdr = sh;
3399 sec_desc->data = data;
3400 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3401 obj->efile.st_ops_data = data;
3402 obj->efile.st_ops_shndx = idx;
3404 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3407 } else if (sh->sh_type == SHT_REL) {
3408 int targ_sec_idx = sh->sh_info; /* points to other section */
3410 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3411 targ_sec_idx >= obj->efile.sec_cnt)
3412 return -LIBBPF_ERRNO__FORMAT;
3414 /* Only do relo for section with exec instructions */
3415 if (!section_have_execinstr(obj, targ_sec_idx) &&
3416 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3417 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3418 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3419 idx, name, targ_sec_idx,
3420 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3424 sec_desc->sec_type = SEC_RELO;
3425 sec_desc->shdr = sh;
3426 sec_desc->data = data;
3427 } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3428 sec_desc->sec_type = SEC_BSS;
3429 sec_desc->shdr = sh;
3430 sec_desc->data = data;
3432 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3433 (size_t)sh->sh_size);
3437 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3438 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3439 return -LIBBPF_ERRNO__FORMAT;
3442 /* sort BPF programs by section name and in-section instruction offset
3443 * for faster search */
3444 if (obj->nr_programs)
3445 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3447 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3450 static bool sym_is_extern(const Elf64_Sym *sym)
3452 int bind = ELF64_ST_BIND(sym->st_info);
3453 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3454 return sym->st_shndx == SHN_UNDEF &&
3455 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3456 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3459 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3461 int bind = ELF64_ST_BIND(sym->st_info);
3462 int type = ELF64_ST_TYPE(sym->st_info);
3464 /* in .text section */
3465 if (sym->st_shndx != text_shndx)
3468 /* local function */
3469 if (bind == STB_LOCAL && type == STT_SECTION)
3472 /* global function */
3473 return bind == STB_GLOBAL && type == STT_FUNC;
3476 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3478 const struct btf_type *t;
3485 n = btf__type_cnt(btf);
3486 for (i = 1; i < n; i++) {
3487 t = btf__type_by_id(btf, i);
3489 if (!btf_is_var(t) && !btf_is_func(t))
3492 tname = btf__name_by_offset(btf, t->name_off);
3493 if (strcmp(tname, ext_name))
3496 if (btf_is_var(t) &&
3497 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3500 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3509 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3510 const struct btf_var_secinfo *vs;
3511 const struct btf_type *t;
3517 n = btf__type_cnt(btf);
3518 for (i = 1; i < n; i++) {
3519 t = btf__type_by_id(btf, i);
3521 if (!btf_is_datasec(t))
3524 vs = btf_var_secinfos(t);
3525 for (j = 0; j < btf_vlen(t); j++, vs++) {
3526 if (vs->type == ext_btf_id)
3534 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3537 const struct btf_type *t;
3540 t = skip_mods_and_typedefs(btf, id, NULL);
3541 name = btf__name_by_offset(btf, t->name_off);
3545 switch (btf_kind(t)) {
3546 case BTF_KIND_INT: {
3547 int enc = btf_int_encoding(t);
3549 if (enc & BTF_INT_BOOL)
3550 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3552 *is_signed = enc & BTF_INT_SIGNED;
3555 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3556 return KCFG_UNKNOWN;
3561 return KCFG_UNKNOWN;
3562 if (strcmp(name, "libbpf_tristate"))
3563 return KCFG_UNKNOWN;
3564 return KCFG_TRISTATE;
3565 case BTF_KIND_ENUM64:
3566 if (strcmp(name, "libbpf_tristate"))
3567 return KCFG_UNKNOWN;
3568 return KCFG_TRISTATE;
3569 case BTF_KIND_ARRAY:
3570 if (btf_array(t)->nelems == 0)
3571 return KCFG_UNKNOWN;
3572 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3573 return KCFG_UNKNOWN;
3574 return KCFG_CHAR_ARR;
3576 return KCFG_UNKNOWN;
3580 static int cmp_externs(const void *_a, const void *_b)
3582 const struct extern_desc *a = _a;
3583 const struct extern_desc *b = _b;
3585 if (a->type != b->type)
3586 return a->type < b->type ? -1 : 1;
3588 if (a->type == EXT_KCFG) {
3589 /* descending order by alignment requirements */
3590 if (a->kcfg.align != b->kcfg.align)
3591 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3592 /* ascending order by size, within same alignment class */
3593 if (a->kcfg.sz != b->kcfg.sz)
3594 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3597 /* resolve ties by name */
3598 return strcmp(a->name, b->name);
3601 static int find_int_btf_id(const struct btf *btf)
3603 const struct btf_type *t;
3606 n = btf__type_cnt(btf);
3607 for (i = 1; i < n; i++) {
3608 t = btf__type_by_id(btf, i);
3610 if (btf_is_int(t) && btf_int_bits(t) == 32)
3617 static int add_dummy_ksym_var(struct btf *btf)
3619 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3620 const struct btf_var_secinfo *vs;
3621 const struct btf_type *sec;
3626 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3631 sec = btf__type_by_id(btf, sec_btf_id);
3632 vs = btf_var_secinfos(sec);
3633 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3634 const struct btf_type *vt;
3636 vt = btf__type_by_id(btf, vs->type);
3637 if (btf_is_func(vt))
3641 /* No func in ksyms sec. No need to add dummy var. */
3642 if (i == btf_vlen(sec))
3645 int_btf_id = find_int_btf_id(btf);
3646 dummy_var_btf_id = btf__add_var(btf,
3648 BTF_VAR_GLOBAL_ALLOCATED,
3650 if (dummy_var_btf_id < 0)
3651 pr_warn("cannot create a dummy_ksym var\n");
3653 return dummy_var_btf_id;
3656 static int bpf_object__collect_externs(struct bpf_object *obj)
3658 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3659 const struct btf_type *t;
3660 struct extern_desc *ext;
3661 int i, n, off, dummy_var_btf_id;
3662 const char *ext_name, *sec_name;
3666 if (!obj->efile.symbols)
3669 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3670 sh = elf_sec_hdr(obj, scn);
3671 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3672 return -LIBBPF_ERRNO__FORMAT;
3674 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3675 if (dummy_var_btf_id < 0)
3676 return dummy_var_btf_id;
3678 n = sh->sh_size / sh->sh_entsize;
3679 pr_debug("looking for externs among %d symbols...\n", n);
3681 for (i = 0; i < n; i++) {
3682 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3685 return -LIBBPF_ERRNO__FORMAT;
3686 if (!sym_is_extern(sym))
3688 ext_name = elf_sym_str(obj, sym->st_name);
3689 if (!ext_name || !ext_name[0])
3693 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3697 ext = &ext[obj->nr_extern];
3698 memset(ext, 0, sizeof(*ext));
3701 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3702 if (ext->btf_id <= 0) {
3703 pr_warn("failed to find BTF for extern '%s': %d\n",
3704 ext_name, ext->btf_id);
3707 t = btf__type_by_id(obj->btf, ext->btf_id);
3708 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3710 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3712 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3713 if (ext->sec_btf_id <= 0) {
3714 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3715 ext_name, ext->btf_id, ext->sec_btf_id);
3716 return ext->sec_btf_id;
3718 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3719 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3721 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3722 if (btf_is_func(t)) {
3723 pr_warn("extern function %s is unsupported under %s section\n",
3724 ext->name, KCONFIG_SEC);
3728 ext->type = EXT_KCFG;
3729 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3730 if (ext->kcfg.sz <= 0) {
3731 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3732 ext_name, ext->kcfg.sz);
3733 return ext->kcfg.sz;
3735 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3736 if (ext->kcfg.align <= 0) {
3737 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3738 ext_name, ext->kcfg.align);
3741 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3742 &ext->kcfg.is_signed);
3743 if (ext->kcfg.type == KCFG_UNKNOWN) {
3744 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3747 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3749 ext->type = EXT_KSYM;
3750 skip_mods_and_typedefs(obj->btf, t->type,
3751 &ext->ksym.type_id);
3753 pr_warn("unrecognized extern section '%s'\n", sec_name);
3757 pr_debug("collected %d externs total\n", obj->nr_extern);
3759 if (!obj->nr_extern)
3762 /* sort externs by type, for kcfg ones also by (align, size, name) */
3763 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3765 /* for .ksyms section, we need to turn all externs into allocated
3766 * variables in BTF to pass kernel verification; we do this by
3767 * pretending that each extern is a 8-byte variable
3770 /* find existing 4-byte integer type in BTF to use for fake
3771 * extern variables in DATASEC
3773 int int_btf_id = find_int_btf_id(obj->btf);
3774 /* For extern function, a dummy_var added earlier
3775 * will be used to replace the vs->type and
3776 * its name string will be used to refill
3777 * the missing param's name.
3779 const struct btf_type *dummy_var;
3781 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3782 for (i = 0; i < obj->nr_extern; i++) {
3783 ext = &obj->externs[i];
3784 if (ext->type != EXT_KSYM)
3786 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3787 i, ext->sym_idx, ext->name);
3792 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3793 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3794 struct btf_type *vt;
3796 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3797 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3798 ext = find_extern_by_name(obj, ext_name);
3800 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3801 btf_kind_str(vt), ext_name);
3804 if (btf_is_func(vt)) {
3805 const struct btf_type *func_proto;
3806 struct btf_param *param;
3809 func_proto = btf__type_by_id(obj->btf,
3811 param = btf_params(func_proto);
3812 /* Reuse the dummy_var string if the
3813 * func proto does not have param name.
3815 for (j = 0; j < btf_vlen(func_proto); j++)
3816 if (param[j].type && !param[j].name_off)
3818 dummy_var->name_off;
3819 vs->type = dummy_var_btf_id;
3820 vt->info &= ~0xffff;
3821 vt->info |= BTF_FUNC_GLOBAL;
3823 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3824 vt->type = int_btf_id;
3827 vs->size = sizeof(int);
3834 /* for kcfg externs calculate their offsets within a .kconfig map */
3836 for (i = 0; i < obj->nr_extern; i++) {
3837 ext = &obj->externs[i];
3838 if (ext->type != EXT_KCFG)
3841 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3842 off = ext->kcfg.data_off + ext->kcfg.sz;
3843 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3844 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3848 for (i = 0; i < n; i++) {
3849 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3851 t = btf__type_by_id(obj->btf, vs->type);
3852 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3853 ext = find_extern_by_name(obj, ext_name);
3855 pr_warn("failed to find extern definition for BTF var '%s'\n",
3859 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3860 vs->offset = ext->kcfg.data_off;
3866 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3868 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3871 struct bpf_program *
3872 bpf_object__find_program_by_name(const struct bpf_object *obj,
3875 struct bpf_program *prog;
3877 bpf_object__for_each_program(prog, obj) {
3878 if (prog_is_subprog(obj, prog))
3880 if (!strcmp(prog->name, name))
3883 return errno = ENOENT, NULL;
3886 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3889 switch (obj->efile.secs[shndx].sec_type) {
3899 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3902 return shndx == obj->efile.btf_maps_shndx;
3905 static enum libbpf_map_type
3906 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3908 if (shndx == obj->efile.symbols_shndx)
3909 return LIBBPF_MAP_KCONFIG;
3911 switch (obj->efile.secs[shndx].sec_type) {
3913 return LIBBPF_MAP_BSS;
3915 return LIBBPF_MAP_DATA;
3917 return LIBBPF_MAP_RODATA;
3919 return LIBBPF_MAP_UNSPEC;
3923 static int bpf_program__record_reloc(struct bpf_program *prog,
3924 struct reloc_desc *reloc_desc,
3925 __u32 insn_idx, const char *sym_name,
3926 const Elf64_Sym *sym, const Elf64_Rel *rel)
3928 struct bpf_insn *insn = &prog->insns[insn_idx];
3929 size_t map_idx, nr_maps = prog->obj->nr_maps;
3930 struct bpf_object *obj = prog->obj;
3931 __u32 shdr_idx = sym->st_shndx;
3932 enum libbpf_map_type type;
3933 const char *sym_sec_name;
3934 struct bpf_map *map;
3936 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3937 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3938 prog->name, sym_name, insn_idx, insn->code);
3939 return -LIBBPF_ERRNO__RELOC;
3942 if (sym_is_extern(sym)) {
3943 int sym_idx = ELF64_R_SYM(rel->r_info);
3944 int i, n = obj->nr_extern;
3945 struct extern_desc *ext;
3947 for (i = 0; i < n; i++) {
3948 ext = &obj->externs[i];
3949 if (ext->sym_idx == sym_idx)
3953 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3954 prog->name, sym_name, sym_idx);
3955 return -LIBBPF_ERRNO__RELOC;
3957 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3958 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3959 if (insn->code == (BPF_JMP | BPF_CALL))
3960 reloc_desc->type = RELO_EXTERN_FUNC;
3962 reloc_desc->type = RELO_EXTERN_VAR;
3963 reloc_desc->insn_idx = insn_idx;
3964 reloc_desc->sym_off = i; /* sym_off stores extern index */
3968 /* sub-program call relocation */
3969 if (is_call_insn(insn)) {
3970 if (insn->src_reg != BPF_PSEUDO_CALL) {
3971 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3972 return -LIBBPF_ERRNO__RELOC;
3974 /* text_shndx can be 0, if no default "main" program exists */
3975 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3976 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3977 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3978 prog->name, sym_name, sym_sec_name);
3979 return -LIBBPF_ERRNO__RELOC;
3981 if (sym->st_value % BPF_INSN_SZ) {
3982 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3983 prog->name, sym_name, (size_t)sym->st_value);
3984 return -LIBBPF_ERRNO__RELOC;
3986 reloc_desc->type = RELO_CALL;
3987 reloc_desc->insn_idx = insn_idx;
3988 reloc_desc->sym_off = sym->st_value;
3992 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3993 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3994 prog->name, sym_name, shdr_idx);
3995 return -LIBBPF_ERRNO__RELOC;
3998 /* loading subprog addresses */
3999 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4000 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4001 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4003 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4004 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4005 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4006 return -LIBBPF_ERRNO__RELOC;
4009 reloc_desc->type = RELO_SUBPROG_ADDR;
4010 reloc_desc->insn_idx = insn_idx;
4011 reloc_desc->sym_off = sym->st_value;
4015 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4016 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4018 /* generic map reference relocation */
4019 if (type == LIBBPF_MAP_UNSPEC) {
4020 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4021 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4022 prog->name, sym_name, sym_sec_name);
4023 return -LIBBPF_ERRNO__RELOC;
4025 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4026 map = &obj->maps[map_idx];
4027 if (map->libbpf_type != type ||
4028 map->sec_idx != sym->st_shndx ||
4029 map->sec_offset != sym->st_value)
4031 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4032 prog->name, map_idx, map->name, map->sec_idx,
4033 map->sec_offset, insn_idx);
4036 if (map_idx >= nr_maps) {
4037 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4038 prog->name, sym_sec_name, (size_t)sym->st_value);
4039 return -LIBBPF_ERRNO__RELOC;
4041 reloc_desc->type = RELO_LD64;
4042 reloc_desc->insn_idx = insn_idx;
4043 reloc_desc->map_idx = map_idx;
4044 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4048 /* global data map relocation */
4049 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4050 pr_warn("prog '%s': bad data relo against section '%s'\n",
4051 prog->name, sym_sec_name);
4052 return -LIBBPF_ERRNO__RELOC;
4054 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4055 map = &obj->maps[map_idx];
4056 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4058 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4059 prog->name, map_idx, map->name, map->sec_idx,
4060 map->sec_offset, insn_idx);
4063 if (map_idx >= nr_maps) {
4064 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4065 prog->name, sym_sec_name);
4066 return -LIBBPF_ERRNO__RELOC;
4069 reloc_desc->type = RELO_DATA;
4070 reloc_desc->insn_idx = insn_idx;
4071 reloc_desc->map_idx = map_idx;
4072 reloc_desc->sym_off = sym->st_value;
4076 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4078 return insn_idx >= prog->sec_insn_off &&
4079 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4082 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4083 size_t sec_idx, size_t insn_idx)
4085 int l = 0, r = obj->nr_programs - 1, m;
4086 struct bpf_program *prog;
4089 m = l + (r - l + 1) / 2;
4090 prog = &obj->programs[m];
4092 if (prog->sec_idx < sec_idx ||
4093 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4098 /* matching program could be at index l, but it still might be the
4099 * wrong one, so we need to double check conditions for the last time
4101 prog = &obj->programs[l];
4102 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4108 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4110 const char *relo_sec_name, *sec_name;
4111 size_t sec_idx = shdr->sh_info, sym_idx;
4112 struct bpf_program *prog;
4113 struct reloc_desc *relos;
4115 const char *sym_name;
4122 if (sec_idx >= obj->efile.sec_cnt)
4125 scn = elf_sec_by_idx(obj, sec_idx);
4126 scn_data = elf_sec_data(obj, scn);
4128 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4129 sec_name = elf_sec_name(obj, scn);
4130 if (!relo_sec_name || !sec_name)
4133 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4134 relo_sec_name, sec_idx, sec_name);
4135 nrels = shdr->sh_size / shdr->sh_entsize;
4137 for (i = 0; i < nrels; i++) {
4138 rel = elf_rel_by_idx(data, i);
4140 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4141 return -LIBBPF_ERRNO__FORMAT;
4144 sym_idx = ELF64_R_SYM(rel->r_info);
4145 sym = elf_sym_by_idx(obj, sym_idx);
4147 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4148 relo_sec_name, sym_idx, i);
4149 return -LIBBPF_ERRNO__FORMAT;
4152 if (sym->st_shndx >= obj->efile.sec_cnt) {
4153 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4154 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4155 return -LIBBPF_ERRNO__FORMAT;
4158 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4159 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4160 relo_sec_name, (size_t)rel->r_offset, i);
4161 return -LIBBPF_ERRNO__FORMAT;
4164 insn_idx = rel->r_offset / BPF_INSN_SZ;
4165 /* relocations against static functions are recorded as
4166 * relocations against the section that contains a function;
4167 * in such case, symbol will be STT_SECTION and sym.st_name
4168 * will point to empty string (0), so fetch section name
4171 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4172 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4174 sym_name = elf_sym_str(obj, sym->st_name);
4175 sym_name = sym_name ?: "<?";
4177 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4178 relo_sec_name, i, insn_idx, sym_name);
4180 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4182 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4183 relo_sec_name, i, sec_name, insn_idx);
4187 relos = libbpf_reallocarray(prog->reloc_desc,
4188 prog->nr_reloc + 1, sizeof(*relos));
4191 prog->reloc_desc = relos;
4193 /* adjust insn_idx to local BPF program frame of reference */
4194 insn_idx -= prog->sec_insn_off;
4195 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4196 insn_idx, sym_name, sym, rel);
4205 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4212 /* if it's BTF-defined map, we don't need to search for type IDs.
4213 * For struct_ops map, it does not need btf_key_type_id and
4214 * btf_value_type_id.
4216 if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4220 * LLVM annotates global data differently in BTF, that is,
4221 * only as '.data', '.bss' or '.rodata'.
4223 if (!bpf_map__is_internal(map))
4226 id = btf__find_by_name(obj->btf, map->real_name);
4230 map->btf_key_type_id = 0;
4231 map->btf_value_type_id = id;
4235 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4237 char file[PATH_MAX], buff[4096];
4242 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4243 memset(info, 0, sizeof(*info));
4245 fp = fopen(file, "r");
4248 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4253 while (fgets(buff, sizeof(buff), fp)) {
4254 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4256 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4257 info->key_size = val;
4258 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4259 info->value_size = val;
4260 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4261 info->max_entries = val;
4262 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4263 info->map_flags = val;
4271 bool bpf_map__autocreate(const struct bpf_map *map)
4273 return map->autocreate;
4276 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4278 if (map->obj->loaded)
4279 return libbpf_err(-EBUSY);
4281 map->autocreate = autocreate;
4285 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4287 struct bpf_map_info info = {};
4288 __u32 len = sizeof(info), name_len;
4292 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4293 if (err && errno == EINVAL)
4294 err = bpf_get_map_info_from_fdinfo(fd, &info);
4296 return libbpf_err(err);
4298 name_len = strlen(info.name);
4299 if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4300 new_name = strdup(map->name);
4302 new_name = strdup(info.name);
4305 return libbpf_err(-errno);
4307 new_fd = open("/", O_RDONLY | O_CLOEXEC);
4310 goto err_free_new_name;
4313 new_fd = dup3(fd, new_fd, O_CLOEXEC);
4316 goto err_close_new_fd;
4319 err = zclose(map->fd);
4322 goto err_close_new_fd;
4327 map->name = new_name;
4328 map->def.type = info.type;
4329 map->def.key_size = info.key_size;
4330 map->def.value_size = info.value_size;
4331 map->def.max_entries = info.max_entries;
4332 map->def.map_flags = info.map_flags;
4333 map->btf_key_type_id = info.btf_key_type_id;
4334 map->btf_value_type_id = info.btf_value_type_id;
4336 map->map_extra = info.map_extra;
4344 return libbpf_err(err);
4347 __u32 bpf_map__max_entries(const struct bpf_map *map)
4349 return map->def.max_entries;
4352 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4354 if (!bpf_map_type__is_map_in_map(map->def.type))
4355 return errno = EINVAL, NULL;
4357 return map->inner_map;
4360 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4362 if (map->obj->loaded)
4363 return libbpf_err(-EBUSY);
4365 map->def.max_entries = max_entries;
4367 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4368 if (map->def.type == BPF_MAP_TYPE_RINGBUF)
4369 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4375 bpf_object__probe_loading(struct bpf_object *obj)
4377 char *cp, errmsg[STRERR_BUFSIZE];
4378 struct bpf_insn insns[] = {
4379 BPF_MOV64_IMM(BPF_REG_0, 0),
4382 int ret, insn_cnt = ARRAY_SIZE(insns);
4384 if (obj->gen_loader)
4387 ret = bump_rlimit_memlock();
4389 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4391 /* make sure basic loading works */
4392 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4394 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4397 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4398 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4399 "program. Make sure your kernel supports BPF "
4400 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4401 "set to big enough value.\n", __func__, cp, ret);
4409 static int probe_fd(int fd)
4416 static int probe_kern_prog_name(void)
4418 const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4419 struct bpf_insn insns[] = {
4420 BPF_MOV64_IMM(BPF_REG_0, 0),
4423 union bpf_attr attr;
4426 memset(&attr, 0, attr_sz);
4427 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4428 attr.license = ptr_to_u64("GPL");
4429 attr.insns = ptr_to_u64(insns);
4430 attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4431 libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4433 /* make sure loading with name works */
4434 ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4435 return probe_fd(ret);
4438 static int probe_kern_global_data(void)
4440 char *cp, errmsg[STRERR_BUFSIZE];
4441 struct bpf_insn insns[] = {
4442 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4443 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4444 BPF_MOV64_IMM(BPF_REG_0, 0),
4447 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4449 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4452 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4453 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4454 __func__, cp, -ret);
4460 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4462 return probe_fd(ret);
4465 static int probe_kern_btf(void)
4467 static const char strs[] = "\0int";
4470 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4473 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4474 strs, sizeof(strs)));
4477 static int probe_kern_btf_func(void)
4479 static const char strs[] = "\0int\0x\0a";
4480 /* void x(int a) {} */
4483 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4484 /* FUNC_PROTO */ /* [2] */
4485 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4486 BTF_PARAM_ENC(7, 1),
4487 /* FUNC x */ /* [3] */
4488 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4491 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4492 strs, sizeof(strs)));
4495 static int probe_kern_btf_func_global(void)
4497 static const char strs[] = "\0int\0x\0a";
4498 /* static void x(int a) {} */
4501 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4502 /* FUNC_PROTO */ /* [2] */
4503 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4504 BTF_PARAM_ENC(7, 1),
4505 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4506 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4509 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4510 strs, sizeof(strs)));
4513 static int probe_kern_btf_datasec(void)
4515 static const char strs[] = "\0x\0.data";
4519 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4520 /* VAR x */ /* [2] */
4521 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4523 /* DATASEC val */ /* [3] */
4524 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4525 BTF_VAR_SECINFO_ENC(2, 0, 4),
4528 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4529 strs, sizeof(strs)));
4532 static int probe_kern_btf_float(void)
4534 static const char strs[] = "\0float";
4537 BTF_TYPE_FLOAT_ENC(1, 4),
4540 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4541 strs, sizeof(strs)));
4544 static int probe_kern_btf_decl_tag(void)
4546 static const char strs[] = "\0tag";
4549 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4550 /* VAR x */ /* [2] */
4551 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4554 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4557 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4558 strs, sizeof(strs)));
4561 static int probe_kern_btf_type_tag(void)
4563 static const char strs[] = "\0tag";
4566 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4568 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4570 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4573 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4574 strs, sizeof(strs)));
4577 static int probe_kern_array_mmap(void)
4579 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4582 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4583 return probe_fd(fd);
4586 static int probe_kern_exp_attach_type(void)
4588 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4589 struct bpf_insn insns[] = {
4590 BPF_MOV64_IMM(BPF_REG_0, 0),
4593 int fd, insn_cnt = ARRAY_SIZE(insns);
4595 /* use any valid combination of program type and (optional)
4596 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4597 * to see if kernel supports expected_attach_type field for
4598 * BPF_PROG_LOAD command
4600 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4601 return probe_fd(fd);
4604 static int probe_kern_probe_read_kernel(void)
4606 struct bpf_insn insns[] = {
4607 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4608 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4609 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4610 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4611 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4614 int fd, insn_cnt = ARRAY_SIZE(insns);
4616 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4617 return probe_fd(fd);
4620 static int probe_prog_bind_map(void)
4622 char *cp, errmsg[STRERR_BUFSIZE];
4623 struct bpf_insn insns[] = {
4624 BPF_MOV64_IMM(BPF_REG_0, 0),
4627 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4629 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4632 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4633 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4634 __func__, cp, -ret);
4638 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4644 ret = bpf_prog_bind_map(prog, map, NULL);
4652 static int probe_module_btf(void)
4654 static const char strs[] = "\0int";
4657 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4659 struct bpf_btf_info info;
4660 __u32 len = sizeof(info);
4664 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4666 return 0; /* BTF not supported at all */
4668 memset(&info, 0, sizeof(info));
4669 info.name = ptr_to_u64(name);
4670 info.name_len = sizeof(name);
4672 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4673 * kernel's module BTF support coincides with support for
4674 * name/name_len fields in struct bpf_btf_info.
4676 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4681 static int probe_perf_link(void)
4683 struct bpf_insn insns[] = {
4684 BPF_MOV64_IMM(BPF_REG_0, 0),
4687 int prog_fd, link_fd, err;
4689 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4690 insns, ARRAY_SIZE(insns), NULL);
4694 /* use invalid perf_event FD to get EBADF, if link is supported;
4695 * otherwise EINVAL should be returned
4697 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4698 err = -errno; /* close() can clobber errno */
4704 return link_fd < 0 && err == -EBADF;
4707 static int probe_kern_bpf_cookie(void)
4709 struct bpf_insn insns[] = {
4710 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4713 int ret, insn_cnt = ARRAY_SIZE(insns);
4715 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4716 return probe_fd(ret);
4719 static int probe_kern_btf_enum64(void)
4721 static const char strs[] = "\0enum64";
4723 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4726 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4727 strs, sizeof(strs)));
4730 static int probe_kern_syscall_wrapper(void);
4732 enum kern_feature_result {
4738 typedef int (*feature_probe_fn)(void);
4740 static struct kern_feature_desc {
4742 feature_probe_fn probe;
4743 enum kern_feature_result res;
4744 } feature_probes[__FEAT_CNT] = {
4745 [FEAT_PROG_NAME] = {
4746 "BPF program name", probe_kern_prog_name,
4748 [FEAT_GLOBAL_DATA] = {
4749 "global variables", probe_kern_global_data,
4752 "minimal BTF", probe_kern_btf,
4755 "BTF functions", probe_kern_btf_func,
4757 [FEAT_BTF_GLOBAL_FUNC] = {
4758 "BTF global function", probe_kern_btf_func_global,
4760 [FEAT_BTF_DATASEC] = {
4761 "BTF data section and variable", probe_kern_btf_datasec,
4763 [FEAT_ARRAY_MMAP] = {
4764 "ARRAY map mmap()", probe_kern_array_mmap,
4766 [FEAT_EXP_ATTACH_TYPE] = {
4767 "BPF_PROG_LOAD expected_attach_type attribute",
4768 probe_kern_exp_attach_type,
4770 [FEAT_PROBE_READ_KERN] = {
4771 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4773 [FEAT_PROG_BIND_MAP] = {
4774 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4776 [FEAT_MODULE_BTF] = {
4777 "module BTF support", probe_module_btf,
4779 [FEAT_BTF_FLOAT] = {
4780 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4782 [FEAT_PERF_LINK] = {
4783 "BPF perf link support", probe_perf_link,
4785 [FEAT_BTF_DECL_TAG] = {
4786 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4788 [FEAT_BTF_TYPE_TAG] = {
4789 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4791 [FEAT_MEMCG_ACCOUNT] = {
4792 "memcg-based memory accounting", probe_memcg_account,
4794 [FEAT_BPF_COOKIE] = {
4795 "BPF cookie support", probe_kern_bpf_cookie,
4797 [FEAT_BTF_ENUM64] = {
4798 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4800 [FEAT_SYSCALL_WRAPPER] = {
4801 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4805 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4807 struct kern_feature_desc *feat = &feature_probes[feat_id];
4810 if (obj && obj->gen_loader)
4811 /* To generate loader program assume the latest kernel
4812 * to avoid doing extra prog_load, map_create syscalls.
4816 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4817 ret = feat->probe();
4819 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4820 } else if (ret == 0) {
4821 WRITE_ONCE(feat->res, FEAT_MISSING);
4823 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4824 WRITE_ONCE(feat->res, FEAT_MISSING);
4828 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4831 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4833 struct bpf_map_info map_info = {};
4834 char msg[STRERR_BUFSIZE];
4838 map_info_len = sizeof(map_info);
4840 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4841 if (err && errno == EINVAL)
4842 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4844 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4845 libbpf_strerror_r(errno, msg, sizeof(msg)));
4849 return (map_info.type == map->def.type &&
4850 map_info.key_size == map->def.key_size &&
4851 map_info.value_size == map->def.value_size &&
4852 map_info.max_entries == map->def.max_entries &&
4853 map_info.map_flags == map->def.map_flags &&
4854 map_info.map_extra == map->map_extra);
4858 bpf_object__reuse_map(struct bpf_map *map)
4860 char *cp, errmsg[STRERR_BUFSIZE];
4863 pin_fd = bpf_obj_get(map->pin_path);
4866 if (err == -ENOENT) {
4867 pr_debug("found no pinned map to reuse at '%s'\n",
4872 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4873 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4878 if (!map_is_reuse_compat(map, pin_fd)) {
4879 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4885 err = bpf_map__reuse_fd(map, pin_fd);
4891 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4897 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4899 enum libbpf_map_type map_type = map->libbpf_type;
4900 char *cp, errmsg[STRERR_BUFSIZE];
4903 if (obj->gen_loader) {
4904 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4905 map->mmaped, map->def.value_size);
4906 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4907 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4910 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4913 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4914 pr_warn("Error setting initial map(%s) contents: %s\n",
4919 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4920 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4921 err = bpf_map_freeze(map->fd);
4924 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4925 pr_warn("Error freezing map(%s) as read-only: %s\n",
4933 static void bpf_map__destroy(struct bpf_map *map);
4935 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4937 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4938 struct bpf_map_def *def = &map->def;
4939 const char *map_name = NULL;
4942 if (kernel_supports(obj, FEAT_PROG_NAME))
4943 map_name = map->name;
4944 create_attr.map_ifindex = map->map_ifindex;
4945 create_attr.map_flags = def->map_flags;
4946 create_attr.numa_node = map->numa_node;
4947 create_attr.map_extra = map->map_extra;
4949 if (bpf_map__is_struct_ops(map))
4950 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4952 if (obj->btf && btf__fd(obj->btf) >= 0) {
4953 create_attr.btf_fd = btf__fd(obj->btf);
4954 create_attr.btf_key_type_id = map->btf_key_type_id;
4955 create_attr.btf_value_type_id = map->btf_value_type_id;
4958 if (bpf_map_type__is_map_in_map(def->type)) {
4959 if (map->inner_map) {
4960 err = bpf_object__create_map(obj, map->inner_map, true);
4962 pr_warn("map '%s': failed to create inner map: %d\n",
4966 map->inner_map_fd = bpf_map__fd(map->inner_map);
4968 if (map->inner_map_fd >= 0)
4969 create_attr.inner_map_fd = map->inner_map_fd;
4972 switch (def->type) {
4973 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4974 case BPF_MAP_TYPE_CGROUP_ARRAY:
4975 case BPF_MAP_TYPE_STACK_TRACE:
4976 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4977 case BPF_MAP_TYPE_HASH_OF_MAPS:
4978 case BPF_MAP_TYPE_DEVMAP:
4979 case BPF_MAP_TYPE_DEVMAP_HASH:
4980 case BPF_MAP_TYPE_CPUMAP:
4981 case BPF_MAP_TYPE_XSKMAP:
4982 case BPF_MAP_TYPE_SOCKMAP:
4983 case BPF_MAP_TYPE_SOCKHASH:
4984 case BPF_MAP_TYPE_QUEUE:
4985 case BPF_MAP_TYPE_STACK:
4986 create_attr.btf_fd = 0;
4987 create_attr.btf_key_type_id = 0;
4988 create_attr.btf_value_type_id = 0;
4989 map->btf_key_type_id = 0;
4990 map->btf_value_type_id = 0;
4995 if (obj->gen_loader) {
4996 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
4997 def->key_size, def->value_size, def->max_entries,
4998 &create_attr, is_inner ? -1 : map - obj->maps);
4999 /* Pretend to have valid FD to pass various fd >= 0 checks.
5000 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5004 map->fd = bpf_map_create(def->type, map_name,
5005 def->key_size, def->value_size,
5006 def->max_entries, &create_attr);
5008 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5009 create_attr.btf_value_type_id)) {
5010 char *cp, errmsg[STRERR_BUFSIZE];
5013 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5014 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5015 map->name, cp, err);
5016 create_attr.btf_fd = 0;
5017 create_attr.btf_key_type_id = 0;
5018 create_attr.btf_value_type_id = 0;
5019 map->btf_key_type_id = 0;
5020 map->btf_value_type_id = 0;
5021 map->fd = bpf_map_create(def->type, map_name,
5022 def->key_size, def->value_size,
5023 def->max_entries, &create_attr);
5026 err = map->fd < 0 ? -errno : 0;
5028 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5029 if (obj->gen_loader)
5030 map->inner_map->fd = -1;
5031 bpf_map__destroy(map->inner_map);
5032 zfree(&map->inner_map);
5038 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5040 const struct bpf_map *targ_map;
5044 for (i = 0; i < map->init_slots_sz; i++) {
5045 if (!map->init_slots[i])
5048 targ_map = map->init_slots[i];
5049 fd = bpf_map__fd(targ_map);
5051 if (obj->gen_loader) {
5052 bpf_gen__populate_outer_map(obj->gen_loader,
5054 targ_map - obj->maps);
5056 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5060 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5061 map->name, i, targ_map->name, fd, err);
5064 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5065 map->name, i, targ_map->name, fd);
5068 zfree(&map->init_slots);
5069 map->init_slots_sz = 0;
5074 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5076 const struct bpf_program *targ_prog;
5080 if (obj->gen_loader)
5083 for (i = 0; i < map->init_slots_sz; i++) {
5084 if (!map->init_slots[i])
5087 targ_prog = map->init_slots[i];
5088 fd = bpf_program__fd(targ_prog);
5090 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5093 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5094 map->name, i, targ_prog->name, fd, err);
5097 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5098 map->name, i, targ_prog->name, fd);
5101 zfree(&map->init_slots);
5102 map->init_slots_sz = 0;
5107 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5109 struct bpf_map *map;
5112 for (i = 0; i < obj->nr_maps; i++) {
5113 map = &obj->maps[i];
5115 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5118 err = init_prog_array_slots(obj, map);
5127 static int map_set_def_max_entries(struct bpf_map *map)
5129 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5132 nr_cpus = libbpf_num_possible_cpus();
5134 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5135 map->name, nr_cpus);
5138 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5139 map->def.max_entries = nr_cpus;
5146 bpf_object__create_maps(struct bpf_object *obj)
5148 struct bpf_map *map;
5149 char *cp, errmsg[STRERR_BUFSIZE];
5154 for (i = 0; i < obj->nr_maps; i++) {
5155 map = &obj->maps[i];
5157 /* To support old kernels, we skip creating global data maps
5158 * (.rodata, .data, .kconfig, etc); later on, during program
5159 * loading, if we detect that at least one of the to-be-loaded
5160 * programs is referencing any global data map, we'll error
5161 * out with program name and relocation index logged.
5162 * This approach allows to accommodate Clang emitting
5163 * unnecessary .rodata.str1.1 sections for string literals,
5164 * but also it allows to have CO-RE applications that use
5165 * global variables in some of BPF programs, but not others.
5166 * If those global variable-using programs are not loaded at
5167 * runtime due to bpf_program__set_autoload(prog, false),
5168 * bpf_object loading will succeed just fine even on old
5171 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5172 map->autocreate = false;
5174 if (!map->autocreate) {
5175 pr_debug("map '%s': skipped auto-creating...\n", map->name);
5179 err = map_set_def_max_entries(map);
5185 if (map->pin_path) {
5186 err = bpf_object__reuse_map(map);
5188 pr_warn("map '%s': error reusing pinned map\n",
5192 if (retried && map->fd < 0) {
5193 pr_warn("map '%s': cannot find pinned map\n",
5201 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5202 map->name, map->fd);
5204 err = bpf_object__create_map(obj, map, false);
5208 pr_debug("map '%s': created successfully, fd=%d\n",
5209 map->name, map->fd);
5211 if (bpf_map__is_internal(map)) {
5212 err = bpf_object__populate_internal_map(obj, map);
5219 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5220 err = init_map_in_map_slots(obj, map);
5228 if (map->pin_path && !map->pinned) {
5229 err = bpf_map__pin(map, NULL);
5232 if (!retried && err == -EEXIST) {
5236 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5237 map->name, map->pin_path, err);
5246 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5247 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5249 for (j = 0; j < i; j++)
5250 zclose(obj->maps[j].fd);
5254 static bool bpf_core_is_flavor_sep(const char *s)
5256 /* check X___Y name pattern, where X and Y are not underscores */
5257 return s[0] != '_' && /* X */
5258 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5259 s[4] != '_'; /* Y */
5262 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5263 * before last triple underscore. Struct name part after last triple
5264 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5266 size_t bpf_core_essential_name_len(const char *name)
5268 size_t n = strlen(name);
5271 for (i = n - 5; i >= 0; i--) {
5272 if (bpf_core_is_flavor_sep(name + i))
5278 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5287 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5288 size_t local_essent_len,
5289 const struct btf *targ_btf,
5290 const char *targ_btf_name,
5292 struct bpf_core_cand_list *cands)
5294 struct bpf_core_cand *new_cands, *cand;
5295 const struct btf_type *t, *local_t;
5296 const char *targ_name, *local_name;
5297 size_t targ_essent_len;
5300 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5301 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5303 n = btf__type_cnt(targ_btf);
5304 for (i = targ_start_id; i < n; i++) {
5305 t = btf__type_by_id(targ_btf, i);
5306 if (!btf_kind_core_compat(t, local_t))
5309 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5310 if (str_is_empty(targ_name))
5313 targ_essent_len = bpf_core_essential_name_len(targ_name);
5314 if (targ_essent_len != local_essent_len)
5317 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5320 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5321 local_cand->id, btf_kind_str(local_t),
5322 local_name, i, btf_kind_str(t), targ_name,
5324 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5325 sizeof(*cands->cands));
5329 cand = &new_cands[cands->len];
5330 cand->btf = targ_btf;
5333 cands->cands = new_cands;
5339 static int load_module_btfs(struct bpf_object *obj)
5341 struct bpf_btf_info info;
5342 struct module_btf *mod_btf;
5348 if (obj->btf_modules_loaded)
5351 if (obj->gen_loader)
5354 /* don't do this again, even if we find no module BTFs */
5355 obj->btf_modules_loaded = true;
5357 /* kernel too old to support module BTFs */
5358 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5362 err = bpf_btf_get_next_id(id, &id);
5363 if (err && errno == ENOENT)
5367 pr_warn("failed to iterate BTF objects: %d\n", err);
5371 fd = bpf_btf_get_fd_by_id(id);
5373 if (errno == ENOENT)
5374 continue; /* expected race: BTF was unloaded */
5376 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5381 memset(&info, 0, sizeof(info));
5382 info.name = ptr_to_u64(name);
5383 info.name_len = sizeof(name);
5385 err = bpf_obj_get_info_by_fd(fd, &info, &len);
5388 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5392 /* ignore non-module BTFs */
5393 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5398 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5399 err = libbpf_get_error(btf);
5401 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5406 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5407 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5411 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5416 mod_btf->name = strdup(name);
5417 if (!mod_btf->name) {
5431 static struct bpf_core_cand_list *
5432 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5434 struct bpf_core_cand local_cand = {};
5435 struct bpf_core_cand_list *cands;
5436 const struct btf *main_btf;
5437 const struct btf_type *local_t;
5438 const char *local_name;
5439 size_t local_essent_len;
5442 local_cand.btf = local_btf;
5443 local_cand.id = local_type_id;
5444 local_t = btf__type_by_id(local_btf, local_type_id);
5446 return ERR_PTR(-EINVAL);
5448 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5449 if (str_is_empty(local_name))
5450 return ERR_PTR(-EINVAL);
5451 local_essent_len = bpf_core_essential_name_len(local_name);
5453 cands = calloc(1, sizeof(*cands));
5455 return ERR_PTR(-ENOMEM);
5457 /* Attempt to find target candidates in vmlinux BTF first */
5458 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5459 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5463 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5467 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5468 if (obj->btf_vmlinux_override)
5471 /* now look through module BTFs, trying to still find candidates */
5472 err = load_module_btfs(obj);
5476 for (i = 0; i < obj->btf_module_cnt; i++) {
5477 err = bpf_core_add_cands(&local_cand, local_essent_len,
5478 obj->btf_modules[i].btf,
5479 obj->btf_modules[i].name,
5480 btf__type_cnt(obj->btf_vmlinux),
5488 bpf_core_free_cands(cands);
5489 return ERR_PTR(err);
5492 /* Check local and target types for compatibility. This check is used for
5493 * type-based CO-RE relocations and follow slightly different rules than
5494 * field-based relocations. This function assumes that root types were already
5495 * checked for name match. Beyond that initial root-level name check, names
5496 * are completely ignored. Compatibility rules are as follows:
5497 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5498 * kind should match for local and target types (i.e., STRUCT is not
5499 * compatible with UNION);
5500 * - for ENUMs, the size is ignored;
5501 * - for INT, size and signedness are ignored;
5502 * - for ARRAY, dimensionality is ignored, element types are checked for
5503 * compatibility recursively;
5504 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5505 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5506 * - FUNC_PROTOs are compatible if they have compatible signature: same
5507 * number of input args and compatible return and argument types.
5508 * These rules are not set in stone and probably will be adjusted as we get
5509 * more experience with using BPF CO-RE relocations.
5511 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5512 const struct btf *targ_btf, __u32 targ_id)
5514 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5517 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5518 const struct btf *targ_btf, __u32 targ_id)
5520 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5523 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5528 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5533 static void *u32_as_hash_key(__u32 x)
5535 return (void *)(uintptr_t)x;
5538 static int record_relo_core(struct bpf_program *prog,
5539 const struct bpf_core_relo *core_relo, int insn_idx)
5541 struct reloc_desc *relos, *relo;
5543 relos = libbpf_reallocarray(prog->reloc_desc,
5544 prog->nr_reloc + 1, sizeof(*relos));
5547 relo = &relos[prog->nr_reloc];
5548 relo->type = RELO_CORE;
5549 relo->insn_idx = insn_idx;
5550 relo->core_relo = core_relo;
5551 prog->reloc_desc = relos;
5556 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5558 struct reloc_desc *relo;
5561 for (i = 0; i < prog->nr_reloc; i++) {
5562 relo = &prog->reloc_desc[i];
5563 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5566 return relo->core_relo;
5572 static int bpf_core_resolve_relo(struct bpf_program *prog,
5573 const struct bpf_core_relo *relo,
5575 const struct btf *local_btf,
5576 struct hashmap *cand_cache,
5577 struct bpf_core_relo_res *targ_res)
5579 struct bpf_core_spec specs_scratch[3] = {};
5580 const void *type_key = u32_as_hash_key(relo->type_id);
5581 struct bpf_core_cand_list *cands = NULL;
5582 const char *prog_name = prog->name;
5583 const struct btf_type *local_type;
5584 const char *local_name;
5585 __u32 local_id = relo->type_id;
5588 local_type = btf__type_by_id(local_btf, local_id);
5592 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5596 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5597 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5598 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5599 if (IS_ERR(cands)) {
5600 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5601 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5602 local_name, PTR_ERR(cands));
5603 return PTR_ERR(cands);
5605 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5607 bpf_core_free_cands(cands);
5612 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5617 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5619 const struct btf_ext_info_sec *sec;
5620 struct bpf_core_relo_res targ_res;
5621 const struct bpf_core_relo *rec;
5622 const struct btf_ext_info *seg;
5623 struct hashmap_entry *entry;
5624 struct hashmap *cand_cache = NULL;
5625 struct bpf_program *prog;
5626 struct bpf_insn *insn;
5627 const char *sec_name;
5628 int i, err = 0, insn_idx, sec_idx, sec_num;
5630 if (obj->btf_ext->core_relo_info.len == 0)
5633 if (targ_btf_path) {
5634 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5635 err = libbpf_get_error(obj->btf_vmlinux_override);
5637 pr_warn("failed to parse target BTF: %d\n", err);
5642 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5643 if (IS_ERR(cand_cache)) {
5644 err = PTR_ERR(cand_cache);
5648 seg = &obj->btf_ext->core_relo_info;
5650 for_each_btf_ext_sec(seg, sec) {
5651 sec_idx = seg->sec_idxs[sec_num];
5654 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5655 if (str_is_empty(sec_name)) {
5660 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5662 for_each_btf_ext_rec(seg, sec, i, rec) {
5663 if (rec->insn_off % BPF_INSN_SZ)
5665 insn_idx = rec->insn_off / BPF_INSN_SZ;
5666 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5668 /* When __weak subprog is "overridden" by another instance
5669 * of the subprog from a different object file, linker still
5670 * appends all the .BTF.ext info that used to belong to that
5671 * eliminated subprogram.
5672 * This is similar to what x86-64 linker does for relocations.
5673 * So just ignore such relocations just like we ignore
5674 * subprog instructions when discovering subprograms.
5676 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5677 sec_name, i, insn_idx);
5680 /* no need to apply CO-RE relocation if the program is
5681 * not going to be loaded
5683 if (!prog->autoload)
5686 /* adjust insn_idx from section frame of reference to the local
5687 * program's frame of reference; (sub-)program code is not yet
5688 * relocated, so it's enough to just subtract in-section offset
5690 insn_idx = insn_idx - prog->sec_insn_off;
5691 if (insn_idx >= prog->insns_cnt)
5693 insn = &prog->insns[insn_idx];
5695 err = record_relo_core(prog, rec, insn_idx);
5697 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5698 prog->name, i, err);
5702 if (prog->obj->gen_loader)
5705 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5707 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5708 prog->name, i, err);
5712 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5714 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5715 prog->name, i, insn_idx, err);
5722 /* obj->btf_vmlinux and module BTFs are freed after object load */
5723 btf__free(obj->btf_vmlinux_override);
5724 obj->btf_vmlinux_override = NULL;
5726 if (!IS_ERR_OR_NULL(cand_cache)) {
5727 hashmap__for_each_entry(cand_cache, entry, i) {
5728 bpf_core_free_cands(entry->value);
5730 hashmap__free(cand_cache);
5735 /* base map load ldimm64 special constant, used also for log fixup logic */
5736 #define MAP_LDIMM64_POISON_BASE 2001000000
5737 #define MAP_LDIMM64_POISON_PFX "200100"
5739 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5740 int insn_idx, struct bpf_insn *insn,
5741 int map_idx, const struct bpf_map *map)
5745 pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5746 prog->name, relo_idx, insn_idx, map_idx, map->name);
5748 /* we turn single ldimm64 into two identical invalid calls */
5749 for (i = 0; i < 2; i++) {
5750 insn->code = BPF_JMP | BPF_CALL;
5754 /* if this instruction is reachable (not a dead code),
5755 * verifier will complain with something like:
5756 * invalid func unknown#2001000123
5757 * where lower 123 is map index into obj->maps[] array
5759 insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5765 /* Relocate data references within program code:
5767 * - global variable references;
5768 * - extern references.
5771 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5775 for (i = 0; i < prog->nr_reloc; i++) {
5776 struct reloc_desc *relo = &prog->reloc_desc[i];
5777 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5778 const struct bpf_map *map;
5779 struct extern_desc *ext;
5781 switch (relo->type) {
5783 map = &obj->maps[relo->map_idx];
5784 if (obj->gen_loader) {
5785 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5786 insn[0].imm = relo->map_idx;
5787 } else if (map->autocreate) {
5788 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5789 insn[0].imm = map->fd;
5791 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5792 relo->map_idx, map);
5796 map = &obj->maps[relo->map_idx];
5797 insn[1].imm = insn[0].imm + relo->sym_off;
5798 if (obj->gen_loader) {
5799 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5800 insn[0].imm = relo->map_idx;
5801 } else if (map->autocreate) {
5802 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5803 insn[0].imm = map->fd;
5805 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5806 relo->map_idx, map);
5809 case RELO_EXTERN_VAR:
5810 ext = &obj->externs[relo->sym_off];
5811 if (ext->type == EXT_KCFG) {
5812 if (obj->gen_loader) {
5813 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5814 insn[0].imm = obj->kconfig_map_idx;
5816 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5817 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5819 insn[1].imm = ext->kcfg.data_off;
5820 } else /* EXT_KSYM */ {
5821 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5822 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5823 insn[0].imm = ext->ksym.kernel_btf_id;
5824 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5825 } else { /* typeless ksyms or unresolved typed ksyms */
5826 insn[0].imm = (__u32)ext->ksym.addr;
5827 insn[1].imm = ext->ksym.addr >> 32;
5831 case RELO_EXTERN_FUNC:
5832 ext = &obj->externs[relo->sym_off];
5833 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5835 insn[0].imm = ext->ksym.kernel_btf_id;
5836 insn[0].off = ext->ksym.btf_fd_idx;
5837 } else { /* unresolved weak kfunc */
5842 case RELO_SUBPROG_ADDR:
5843 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5844 pr_warn("prog '%s': relo #%d: bad insn\n",
5848 /* handled already */
5851 /* handled already */
5854 /* will be handled by bpf_program_record_relos() */
5857 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5858 prog->name, i, relo->type);
5866 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5867 const struct bpf_program *prog,
5868 const struct btf_ext_info *ext_info,
5869 void **prog_info, __u32 *prog_rec_cnt,
5872 void *copy_start = NULL, *copy_end = NULL;
5873 void *rec, *rec_end, *new_prog_info;
5874 const struct btf_ext_info_sec *sec;
5875 size_t old_sz, new_sz;
5876 int i, sec_num, sec_idx, off_adj;
5879 for_each_btf_ext_sec(ext_info, sec) {
5880 sec_idx = ext_info->sec_idxs[sec_num];
5882 if (prog->sec_idx != sec_idx)
5885 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5886 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5888 if (insn_off < prog->sec_insn_off)
5890 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5895 copy_end = rec + ext_info->rec_size;
5901 /* append func/line info of a given (sub-)program to the main
5902 * program func/line info
5904 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5905 new_sz = old_sz + (copy_end - copy_start);
5906 new_prog_info = realloc(*prog_info, new_sz);
5909 *prog_info = new_prog_info;
5910 *prog_rec_cnt = new_sz / ext_info->rec_size;
5911 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5913 /* Kernel instruction offsets are in units of 8-byte
5914 * instructions, while .BTF.ext instruction offsets generated
5915 * by Clang are in units of bytes. So convert Clang offsets
5916 * into kernel offsets and adjust offset according to program
5917 * relocated position.
5919 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5920 rec = new_prog_info + old_sz;
5921 rec_end = new_prog_info + new_sz;
5922 for (; rec < rec_end; rec += ext_info->rec_size) {
5923 __u32 *insn_off = rec;
5925 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5927 *prog_rec_sz = ext_info->rec_size;
5935 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5936 struct bpf_program *main_prog,
5937 const struct bpf_program *prog)
5941 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5942 * supprot func/line info
5944 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5947 /* only attempt func info relocation if main program's func_info
5948 * relocation was successful
5950 if (main_prog != prog && !main_prog->func_info)
5953 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5954 &main_prog->func_info,
5955 &main_prog->func_info_cnt,
5956 &main_prog->func_info_rec_size);
5958 if (err != -ENOENT) {
5959 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5963 if (main_prog->func_info) {
5965 * Some info has already been found but has problem
5966 * in the last btf_ext reloc. Must have to error out.
5968 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5971 /* Have problem loading the very first info. Ignore the rest. */
5972 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5977 /* don't relocate line info if main program's relocation failed */
5978 if (main_prog != prog && !main_prog->line_info)
5981 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5982 &main_prog->line_info,
5983 &main_prog->line_info_cnt,
5984 &main_prog->line_info_rec_size);
5986 if (err != -ENOENT) {
5987 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5991 if (main_prog->line_info) {
5993 * Some info has already been found but has problem
5994 * in the last btf_ext reloc. Must have to error out.
5996 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5999 /* Have problem loading the very first info. Ignore the rest. */
6000 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6006 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6008 size_t insn_idx = *(const size_t *)key;
6009 const struct reloc_desc *relo = elem;
6011 if (insn_idx == relo->insn_idx)
6013 return insn_idx < relo->insn_idx ? -1 : 1;
6016 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6018 if (!prog->nr_reloc)
6020 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6021 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6024 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6026 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6027 struct reloc_desc *relos;
6030 if (main_prog == subprog)
6032 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6035 if (subprog->nr_reloc)
6036 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6037 sizeof(*relos) * subprog->nr_reloc);
6039 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6040 relos[i].insn_idx += subprog->sub_insn_off;
6041 /* After insn_idx adjustment the 'relos' array is still sorted
6042 * by insn_idx and doesn't break bsearch.
6044 main_prog->reloc_desc = relos;
6045 main_prog->nr_reloc = new_cnt;
6050 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6051 struct bpf_program *prog)
6053 size_t sub_insn_idx, insn_idx, new_cnt;
6054 struct bpf_program *subprog;
6055 struct bpf_insn *insns, *insn;
6056 struct reloc_desc *relo;
6059 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6063 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6064 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6065 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6068 relo = find_prog_insn_relo(prog, insn_idx);
6069 if (relo && relo->type == RELO_EXTERN_FUNC)
6070 /* kfunc relocations will be handled later
6071 * in bpf_object__relocate_data()
6074 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6075 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6076 prog->name, insn_idx, relo->type);
6077 return -LIBBPF_ERRNO__RELOC;
6080 /* sub-program instruction index is a combination of
6081 * an offset of a symbol pointed to by relocation and
6082 * call instruction's imm field; for global functions,
6083 * call always has imm = -1, but for static functions
6084 * relocation is against STT_SECTION and insn->imm
6085 * points to a start of a static function
6087 * for subprog addr relocation, the relo->sym_off + insn->imm is
6088 * the byte offset in the corresponding section.
6090 if (relo->type == RELO_CALL)
6091 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6093 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6094 } else if (insn_is_pseudo_func(insn)) {
6096 * RELO_SUBPROG_ADDR relo is always emitted even if both
6097 * functions are in the same section, so it shouldn't reach here.
6099 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6100 prog->name, insn_idx);
6101 return -LIBBPF_ERRNO__RELOC;
6103 /* if subprogram call is to a static function within
6104 * the same ELF section, there won't be any relocation
6105 * emitted, but it also means there is no additional
6106 * offset necessary, insns->imm is relative to
6107 * instruction's original position within the section
6109 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6112 /* we enforce that sub-programs should be in .text section */
6113 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6115 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6117 return -LIBBPF_ERRNO__RELOC;
6120 /* if it's the first call instruction calling into this
6121 * subprogram (meaning this subprog hasn't been processed
6122 * yet) within the context of current main program:
6123 * - append it at the end of main program's instructions blog;
6124 * - process is recursively, while current program is put on hold;
6125 * - if that subprogram calls some other not yet processes
6126 * subprogram, same thing will happen recursively until
6127 * there are no more unprocesses subprograms left to append
6130 if (subprog->sub_insn_off == 0) {
6131 subprog->sub_insn_off = main_prog->insns_cnt;
6133 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6134 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6136 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6139 main_prog->insns = insns;
6140 main_prog->insns_cnt = new_cnt;
6142 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6143 subprog->insns_cnt * sizeof(*insns));
6145 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6146 main_prog->name, subprog->insns_cnt, subprog->name);
6148 /* The subprog insns are now appended. Append its relos too. */
6149 err = append_subprog_relos(main_prog, subprog);
6152 err = bpf_object__reloc_code(obj, main_prog, subprog);
6157 /* main_prog->insns memory could have been re-allocated, so
6158 * calculate pointer again
6160 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6161 /* calculate correct instruction position within current main
6162 * prog; each main prog can have a different set of
6163 * subprograms appended (potentially in different order as
6164 * well), so position of any subprog can be different for
6165 * different main programs */
6166 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6168 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6169 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6176 * Relocate sub-program calls.
6178 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6179 * main prog) is processed separately. For each subprog (non-entry functions,
6180 * that can be called from either entry progs or other subprogs) gets their
6181 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6182 * hasn't been yet appended and relocated within current main prog. Once its
6183 * relocated, sub_insn_off will point at the position within current main prog
6184 * where given subprog was appended. This will further be used to relocate all
6185 * the call instructions jumping into this subprog.
6187 * We start with main program and process all call instructions. If the call
6188 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6189 * is zero), subprog instructions are appended at the end of main program's
6190 * instruction array. Then main program is "put on hold" while we recursively
6191 * process newly appended subprogram. If that subprogram calls into another
6192 * subprogram that hasn't been appended, new subprogram is appended again to
6193 * the *main* prog's instructions (subprog's instructions are always left
6194 * untouched, as they need to be in unmodified state for subsequent main progs
6195 * and subprog instructions are always sent only as part of a main prog) and
6196 * the process continues recursively. Once all the subprogs called from a main
6197 * prog or any of its subprogs are appended (and relocated), all their
6198 * positions within finalized instructions array are known, so it's easy to
6199 * rewrite call instructions with correct relative offsets, corresponding to
6200 * desired target subprog.
6202 * Its important to realize that some subprogs might not be called from some
6203 * main prog and any of its called/used subprogs. Those will keep their
6204 * subprog->sub_insn_off as zero at all times and won't be appended to current
6205 * main prog and won't be relocated within the context of current main prog.
6206 * They might still be used from other main progs later.
6208 * Visually this process can be shown as below. Suppose we have two main
6209 * programs mainA and mainB and BPF object contains three subprogs: subA,
6210 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6211 * subC both call subB:
6213 * +--------+ +-------+
6215 * +--+---+ +--+-+-+ +---+--+
6216 * | subA | | subB | | subC |
6217 * +--+---+ +------+ +---+--+
6220 * +---+-------+ +------+----+
6221 * | mainA | | mainB |
6222 * +-----------+ +-----------+
6224 * We'll start relocating mainA, will find subA, append it and start
6225 * processing sub A recursively:
6227 * +-----------+------+
6229 * +-----------+------+
6231 * At this point we notice that subB is used from subA, so we append it and
6232 * relocate (there are no further subcalls from subB):
6234 * +-----------+------+------+
6235 * | mainA | subA | subB |
6236 * +-----------+------+------+
6238 * At this point, we relocate subA calls, then go one level up and finish with
6239 * relocatin mainA calls. mainA is done.
6241 * For mainB process is similar but results in different order. We start with
6242 * mainB and skip subA and subB, as mainB never calls them (at least
6243 * directly), but we see subC is needed, so we append and start processing it:
6245 * +-----------+------+
6247 * +-----------+------+
6248 * Now we see subC needs subB, so we go back to it, append and relocate it:
6250 * +-----------+------+------+
6251 * | mainB | subC | subB |
6252 * +-----------+------+------+
6254 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6257 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6259 struct bpf_program *subprog;
6262 /* mark all subprogs as not relocated (yet) within the context of
6263 * current main program
6265 for (i = 0; i < obj->nr_programs; i++) {
6266 subprog = &obj->programs[i];
6267 if (!prog_is_subprog(obj, subprog))
6270 subprog->sub_insn_off = 0;
6273 err = bpf_object__reloc_code(obj, prog, prog);
6281 bpf_object__free_relocs(struct bpf_object *obj)
6283 struct bpf_program *prog;
6286 /* free up relocation descriptors */
6287 for (i = 0; i < obj->nr_programs; i++) {
6288 prog = &obj->programs[i];
6289 zfree(&prog->reloc_desc);
6294 static int cmp_relocs(const void *_a, const void *_b)
6296 const struct reloc_desc *a = _a;
6297 const struct reloc_desc *b = _b;
6299 if (a->insn_idx != b->insn_idx)
6300 return a->insn_idx < b->insn_idx ? -1 : 1;
6302 /* no two relocations should have the same insn_idx, but ... */
6303 if (a->type != b->type)
6304 return a->type < b->type ? -1 : 1;
6309 static void bpf_object__sort_relos(struct bpf_object *obj)
6313 for (i = 0; i < obj->nr_programs; i++) {
6314 struct bpf_program *p = &obj->programs[i];
6319 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6324 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6326 struct bpf_program *prog;
6331 err = bpf_object__relocate_core(obj, targ_btf_path);
6333 pr_warn("failed to perform CO-RE relocations: %d\n",
6337 bpf_object__sort_relos(obj);
6340 /* Before relocating calls pre-process relocations and mark
6341 * few ld_imm64 instructions that points to subprogs.
6342 * Otherwise bpf_object__reloc_code() later would have to consider
6343 * all ld_imm64 insns as relocation candidates. That would
6344 * reduce relocation speed, since amount of find_prog_insn_relo()
6345 * would increase and most of them will fail to find a relo.
6347 for (i = 0; i < obj->nr_programs; i++) {
6348 prog = &obj->programs[i];
6349 for (j = 0; j < prog->nr_reloc; j++) {
6350 struct reloc_desc *relo = &prog->reloc_desc[j];
6351 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6353 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6354 if (relo->type == RELO_SUBPROG_ADDR)
6355 insn[0].src_reg = BPF_PSEUDO_FUNC;
6359 /* relocate subprogram calls and append used subprograms to main
6360 * programs; each copy of subprogram code needs to be relocated
6361 * differently for each main program, because its code location might
6363 * Append subprog relos to main programs to allow data relos to be
6364 * processed after text is completely relocated.
6366 for (i = 0; i < obj->nr_programs; i++) {
6367 prog = &obj->programs[i];
6368 /* sub-program's sub-calls are relocated within the context of
6369 * its main program only
6371 if (prog_is_subprog(obj, prog))
6373 if (!prog->autoload)
6376 err = bpf_object__relocate_calls(obj, prog);
6378 pr_warn("prog '%s': failed to relocate calls: %d\n",
6383 /* Process data relos for main programs */
6384 for (i = 0; i < obj->nr_programs; i++) {
6385 prog = &obj->programs[i];
6386 if (prog_is_subprog(obj, prog))
6388 if (!prog->autoload)
6390 err = bpf_object__relocate_data(obj, prog);
6392 pr_warn("prog '%s': failed to relocate data references: %d\n",
6401 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6402 Elf64_Shdr *shdr, Elf_Data *data);
6404 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6405 Elf64_Shdr *shdr, Elf_Data *data)
6407 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6408 int i, j, nrels, new_sz;
6409 const struct btf_var_secinfo *vi = NULL;
6410 const struct btf_type *sec, *var, *def;
6411 struct bpf_map *map = NULL, *targ_map = NULL;
6412 struct bpf_program *targ_prog = NULL;
6413 bool is_prog_array, is_map_in_map;
6414 const struct btf_member *member;
6415 const char *name, *mname, *type;
6421 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6423 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6427 nrels = shdr->sh_size / shdr->sh_entsize;
6428 for (i = 0; i < nrels; i++) {
6429 rel = elf_rel_by_idx(data, i);
6431 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6432 return -LIBBPF_ERRNO__FORMAT;
6435 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6437 pr_warn(".maps relo #%d: symbol %zx not found\n",
6438 i, (size_t)ELF64_R_SYM(rel->r_info));
6439 return -LIBBPF_ERRNO__FORMAT;
6441 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6443 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6444 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6445 (size_t)rel->r_offset, sym->st_name, name);
6447 for (j = 0; j < obj->nr_maps; j++) {
6448 map = &obj->maps[j];
6449 if (map->sec_idx != obj->efile.btf_maps_shndx)
6452 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6453 if (vi->offset <= rel->r_offset &&
6454 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6457 if (j == obj->nr_maps) {
6458 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6459 i, name, (size_t)rel->r_offset);
6463 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6464 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6465 type = is_map_in_map ? "map" : "prog";
6466 if (is_map_in_map) {
6467 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6468 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6470 return -LIBBPF_ERRNO__RELOC;
6472 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6473 map->def.key_size != sizeof(int)) {
6474 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6475 i, map->name, sizeof(int));
6478 targ_map = bpf_object__find_map_by_name(obj, name);
6480 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6484 } else if (is_prog_array) {
6485 targ_prog = bpf_object__find_program_by_name(obj, name);
6487 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6491 if (targ_prog->sec_idx != sym->st_shndx ||
6492 targ_prog->sec_insn_off * 8 != sym->st_value ||
6493 prog_is_subprog(obj, targ_prog)) {
6494 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6496 return -LIBBPF_ERRNO__RELOC;
6502 var = btf__type_by_id(obj->btf, vi->type);
6503 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6504 if (btf_vlen(def) == 0)
6506 member = btf_members(def) + btf_vlen(def) - 1;
6507 mname = btf__name_by_offset(obj->btf, member->name_off);
6508 if (strcmp(mname, "values"))
6511 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6512 if (rel->r_offset - vi->offset < moff)
6515 moff = rel->r_offset - vi->offset - moff;
6516 /* here we use BPF pointer size, which is always 64 bit, as we
6517 * are parsing ELF that was built for BPF target
6519 if (moff % bpf_ptr_sz)
6522 if (moff >= map->init_slots_sz) {
6524 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6527 map->init_slots = tmp;
6528 memset(map->init_slots + map->init_slots_sz, 0,
6529 (new_sz - map->init_slots_sz) * host_ptr_sz);
6530 map->init_slots_sz = new_sz;
6532 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6534 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6535 i, map->name, moff, type, name);
6541 static int bpf_object__collect_relos(struct bpf_object *obj)
6545 for (i = 0; i < obj->efile.sec_cnt; i++) {
6546 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6551 if (sec_desc->sec_type != SEC_RELO)
6554 shdr = sec_desc->shdr;
6555 data = sec_desc->data;
6556 idx = shdr->sh_info;
6558 if (shdr->sh_type != SHT_REL) {
6559 pr_warn("internal error at %d\n", __LINE__);
6560 return -LIBBPF_ERRNO__INTERNAL;
6563 if (idx == obj->efile.st_ops_shndx)
6564 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6565 else if (idx == obj->efile.btf_maps_shndx)
6566 err = bpf_object__collect_map_relos(obj, shdr, data);
6568 err = bpf_object__collect_prog_relos(obj, shdr, data);
6573 bpf_object__sort_relos(obj);
6577 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6579 if (BPF_CLASS(insn->code) == BPF_JMP &&
6580 BPF_OP(insn->code) == BPF_CALL &&
6581 BPF_SRC(insn->code) == BPF_K &&
6582 insn->src_reg == 0 &&
6583 insn->dst_reg == 0) {
6584 *func_id = insn->imm;
6590 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6592 struct bpf_insn *insn = prog->insns;
6593 enum bpf_func_id func_id;
6596 if (obj->gen_loader)
6599 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6600 if (!insn_is_helper_call(insn, &func_id))
6603 /* on kernels that don't yet support
6604 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6605 * to bpf_probe_read() which works well for old kernels
6608 case BPF_FUNC_probe_read_kernel:
6609 case BPF_FUNC_probe_read_user:
6610 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6611 insn->imm = BPF_FUNC_probe_read;
6613 case BPF_FUNC_probe_read_kernel_str:
6614 case BPF_FUNC_probe_read_user_str:
6615 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6616 insn->imm = BPF_FUNC_probe_read_str;
6625 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6626 int *btf_obj_fd, int *btf_type_id);
6628 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6629 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6630 struct bpf_prog_load_opts *opts, long cookie)
6632 enum sec_def_flags def = cookie;
6634 /* old kernels might not support specifying expected_attach_type */
6635 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6636 opts->expected_attach_type = 0;
6638 if (def & SEC_SLEEPABLE)
6639 opts->prog_flags |= BPF_F_SLEEPABLE;
6641 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6642 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6644 if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6645 int btf_obj_fd = 0, btf_type_id = 0, err;
6646 const char *attach_name;
6648 attach_name = strchr(prog->sec_name, '/');
6650 /* if BPF program is annotated with just SEC("fentry")
6651 * (or similar) without declaratively specifying
6652 * target, then it is expected that target will be
6653 * specified with bpf_program__set_attach_target() at
6654 * runtime before BPF object load step. If not, then
6655 * there is nothing to load into the kernel as BPF
6656 * verifier won't be able to validate BPF program
6657 * correctness anyways.
6659 pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6663 attach_name++; /* skip over / */
6665 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6669 /* cache resolved BTF FD and BTF type ID in the prog */
6670 prog->attach_btf_obj_fd = btf_obj_fd;
6671 prog->attach_btf_id = btf_type_id;
6673 /* but by now libbpf common logic is not utilizing
6674 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6675 * this callback is called after opts were populated by
6676 * libbpf, so this callback has to update opts explicitly here
6678 opts->attach_btf_obj_fd = btf_obj_fd;
6679 opts->attach_btf_id = btf_type_id;
6684 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6686 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6687 struct bpf_insn *insns, int insns_cnt,
6688 const char *license, __u32 kern_version, int *prog_fd)
6690 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6691 const char *prog_name = NULL;
6692 char *cp, errmsg[STRERR_BUFSIZE];
6693 size_t log_buf_size = 0;
6694 char *log_buf = NULL, *tmp;
6695 int btf_fd, ret, err;
6696 bool own_log_buf = true;
6697 __u32 log_level = prog->log_level;
6699 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6701 * The program type must be set. Most likely we couldn't find a proper
6702 * section definition at load time, and thus we didn't infer the type.
6704 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6705 prog->name, prog->sec_name);
6709 if (!insns || !insns_cnt)
6712 load_attr.expected_attach_type = prog->expected_attach_type;
6713 if (kernel_supports(obj, FEAT_PROG_NAME))
6714 prog_name = prog->name;
6715 load_attr.attach_prog_fd = prog->attach_prog_fd;
6716 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6717 load_attr.attach_btf_id = prog->attach_btf_id;
6718 load_attr.kern_version = kern_version;
6719 load_attr.prog_ifindex = prog->prog_ifindex;
6721 /* specify func_info/line_info only if kernel supports them */
6722 btf_fd = bpf_object__btf_fd(obj);
6723 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6724 load_attr.prog_btf_fd = btf_fd;
6725 load_attr.func_info = prog->func_info;
6726 load_attr.func_info_rec_size = prog->func_info_rec_size;
6727 load_attr.func_info_cnt = prog->func_info_cnt;
6728 load_attr.line_info = prog->line_info;
6729 load_attr.line_info_rec_size = prog->line_info_rec_size;
6730 load_attr.line_info_cnt = prog->line_info_cnt;
6732 load_attr.log_level = log_level;
6733 load_attr.prog_flags = prog->prog_flags;
6734 load_attr.fd_array = obj->fd_array;
6736 /* adjust load_attr if sec_def provides custom preload callback */
6737 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6738 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6740 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6744 insns = prog->insns;
6745 insns_cnt = prog->insns_cnt;
6748 if (obj->gen_loader) {
6749 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6750 license, insns, insns_cnt, &load_attr,
6751 prog - obj->programs);
6757 /* if log_level is zero, we don't request logs initially even if
6758 * custom log_buf is specified; if the program load fails, then we'll
6759 * bump log_level to 1 and use either custom log_buf or we'll allocate
6760 * our own and retry the load to get details on what failed
6763 if (prog->log_buf) {
6764 log_buf = prog->log_buf;
6765 log_buf_size = prog->log_size;
6766 own_log_buf = false;
6767 } else if (obj->log_buf) {
6768 log_buf = obj->log_buf;
6769 log_buf_size = obj->log_size;
6770 own_log_buf = false;
6772 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6773 tmp = realloc(log_buf, log_buf_size);
6784 load_attr.log_buf = log_buf;
6785 load_attr.log_size = log_buf_size;
6786 load_attr.log_level = log_level;
6788 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6790 if (log_level && own_log_buf) {
6791 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6792 prog->name, log_buf);
6795 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6796 struct bpf_map *map;
6799 for (i = 0; i < obj->nr_maps; i++) {
6800 map = &prog->obj->maps[i];
6801 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6804 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6805 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6806 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6807 prog->name, map->real_name, cp);
6808 /* Don't fail hard if can't bind rodata. */
6818 if (log_level == 0) {
6822 /* On ENOSPC, increase log buffer size and retry, unless custom
6823 * log_buf is specified.
6824 * Be careful to not overflow u32, though. Kernel's log buf size limit
6825 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6826 * multiply by 2 unless we are sure we'll fit within 32 bits.
6827 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6829 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6834 /* post-process verifier log to improve error descriptions */
6835 fixup_verifier_log(prog, log_buf, log_buf_size);
6837 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6838 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6841 if (own_log_buf && log_buf && log_buf[0] != '\0') {
6842 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6843 prog->name, log_buf);
6852 static char *find_prev_line(char *buf, char *cur)
6856 if (cur == buf) /* end of a log buf */
6860 while (p - 1 >= buf && *(p - 1) != '\n')
6866 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6867 char *orig, size_t orig_sz, const char *patch)
6869 /* size of the remaining log content to the right from the to-be-replaced part */
6870 size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6871 size_t patch_sz = strlen(patch);
6873 if (patch_sz != orig_sz) {
6874 /* If patch line(s) are longer than original piece of verifier log,
6875 * shift log contents by (patch_sz - orig_sz) bytes to the right
6876 * starting from after to-be-replaced part of the log.
6878 * If patch line(s) are shorter than original piece of verifier log,
6879 * shift log contents by (orig_sz - patch_sz) bytes to the left
6880 * starting from after to-be-replaced part of the log
6882 * We need to be careful about not overflowing available
6883 * buf_sz capacity. If that's the case, we'll truncate the end
6884 * of the original log, as necessary.
6886 if (patch_sz > orig_sz) {
6887 if (orig + patch_sz >= buf + buf_sz) {
6888 /* patch is big enough to cover remaining space completely */
6889 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6891 } else if (patch_sz - orig_sz > buf_sz - log_sz) {
6892 /* patch causes part of remaining log to be truncated */
6893 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6896 /* shift remaining log to the right by calculated amount */
6897 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6900 memcpy(orig, patch, patch_sz);
6903 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6904 char *buf, size_t buf_sz, size_t log_sz,
6905 char *line1, char *line2, char *line3)
6907 /* Expected log for failed and not properly guarded CO-RE relocation:
6908 * line1 -> 123: (85) call unknown#195896080
6909 * line2 -> invalid func unknown#195896080
6910 * line3 -> <anything else or end of buffer>
6912 * "123" is the index of the instruction that was poisoned. We extract
6913 * instruction index to find corresponding CO-RE relocation and
6914 * replace this part of the log with more relevant information about
6915 * failed CO-RE relocation.
6917 const struct bpf_core_relo *relo;
6918 struct bpf_core_spec spec;
6919 char patch[512], spec_buf[256];
6920 int insn_idx, err, spec_len;
6922 if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
6925 relo = find_relo_core(prog, insn_idx);
6929 err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
6933 spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
6934 snprintf(patch, sizeof(patch),
6935 "%d: <invalid CO-RE relocation>\n"
6936 "failed to resolve CO-RE relocation %s%s\n",
6937 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
6939 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
6942 static void fixup_log_missing_map_load(struct bpf_program *prog,
6943 char *buf, size_t buf_sz, size_t log_sz,
6944 char *line1, char *line2, char *line3)
6946 /* Expected log for failed and not properly guarded CO-RE relocation:
6947 * line1 -> 123: (85) call unknown#2001000345
6948 * line2 -> invalid func unknown#2001000345
6949 * line3 -> <anything else or end of buffer>
6951 * "123" is the index of the instruction that was poisoned.
6952 * "345" in "2001000345" are map index in obj->maps to fetch map name.
6954 struct bpf_object *obj = prog->obj;
6955 const struct bpf_map *map;
6956 int insn_idx, map_idx;
6959 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
6962 map_idx -= MAP_LDIMM64_POISON_BASE;
6963 if (map_idx < 0 || map_idx >= obj->nr_maps)
6965 map = &obj->maps[map_idx];
6967 snprintf(patch, sizeof(patch),
6968 "%d: <invalid BPF map reference>\n"
6969 "BPF map '%s' is referenced but wasn't created\n",
6970 insn_idx, map->name);
6972 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
6975 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
6977 /* look for familiar error patterns in last N lines of the log */
6978 const size_t max_last_line_cnt = 10;
6979 char *prev_line, *cur_line, *next_line;
6986 log_sz = strlen(buf) + 1;
6987 next_line = buf + log_sz - 1;
6989 for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
6990 cur_line = find_prev_line(buf, next_line);
6994 /* failed CO-RE relocation case */
6995 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
6996 prev_line = find_prev_line(buf, cur_line);
7000 fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7001 prev_line, cur_line, next_line);
7003 } else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7004 prev_line = find_prev_line(buf, cur_line);
7008 fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7009 prev_line, cur_line, next_line);
7015 static int bpf_program_record_relos(struct bpf_program *prog)
7017 struct bpf_object *obj = prog->obj;
7020 for (i = 0; i < prog->nr_reloc; i++) {
7021 struct reloc_desc *relo = &prog->reloc_desc[i];
7022 struct extern_desc *ext = &obj->externs[relo->sym_off];
7024 switch (relo->type) {
7025 case RELO_EXTERN_VAR:
7026 if (ext->type != EXT_KSYM)
7028 bpf_gen__record_extern(obj->gen_loader, ext->name,
7029 ext->is_weak, !ext->ksym.type_id,
7030 BTF_KIND_VAR, relo->insn_idx);
7032 case RELO_EXTERN_FUNC:
7033 bpf_gen__record_extern(obj->gen_loader, ext->name,
7034 ext->is_weak, false, BTF_KIND_FUNC,
7038 struct bpf_core_relo cr = {
7039 .insn_off = relo->insn_idx * 8,
7040 .type_id = relo->core_relo->type_id,
7041 .access_str_off = relo->core_relo->access_str_off,
7042 .kind = relo->core_relo->kind,
7045 bpf_gen__record_relo_core(obj->gen_loader, &cr);
7056 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7058 struct bpf_program *prog;
7062 for (i = 0; i < obj->nr_programs; i++) {
7063 prog = &obj->programs[i];
7064 err = bpf_object__sanitize_prog(obj, prog);
7069 for (i = 0; i < obj->nr_programs; i++) {
7070 prog = &obj->programs[i];
7071 if (prog_is_subprog(obj, prog))
7073 if (!prog->autoload) {
7074 pr_debug("prog '%s': skipped loading\n", prog->name);
7077 prog->log_level |= log_level;
7079 if (obj->gen_loader)
7080 bpf_program_record_relos(prog);
7082 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7083 obj->license, obj->kern_version, &prog->fd);
7085 pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7090 bpf_object__free_relocs(obj);
7094 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7096 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7098 struct bpf_program *prog;
7101 bpf_object__for_each_program(prog, obj) {
7102 prog->sec_def = find_sec_def(prog->sec_name);
7103 if (!prog->sec_def) {
7104 /* couldn't guess, but user might manually specify */
7105 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7106 prog->name, prog->sec_name);
7110 prog->type = prog->sec_def->prog_type;
7111 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7113 /* sec_def can have custom callback which should be called
7114 * after bpf_program is initialized to adjust its properties
7116 if (prog->sec_def->prog_setup_fn) {
7117 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7119 pr_warn("prog '%s': failed to initialize: %d\n",
7129 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7130 const struct bpf_object_open_opts *opts)
7132 const char *obj_name, *kconfig, *btf_tmp_path;
7133 struct bpf_object *obj;
7140 if (elf_version(EV_CURRENT) == EV_NONE) {
7141 pr_warn("failed to init libelf for %s\n",
7142 path ? : "(mem buf)");
7143 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7146 if (!OPTS_VALID(opts, bpf_object_open_opts))
7147 return ERR_PTR(-EINVAL);
7149 obj_name = OPTS_GET(opts, object_name, NULL);
7152 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7153 (unsigned long)obj_buf,
7154 (unsigned long)obj_buf_sz);
7155 obj_name = tmp_name;
7158 pr_debug("loading object '%s' from buffer\n", obj_name);
7161 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7162 log_size = OPTS_GET(opts, kernel_log_size, 0);
7163 log_level = OPTS_GET(opts, kernel_log_level, 0);
7164 if (log_size > UINT_MAX)
7165 return ERR_PTR(-EINVAL);
7166 if (log_size && !log_buf)
7167 return ERR_PTR(-EINVAL);
7169 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7173 obj->log_buf = log_buf;
7174 obj->log_size = log_size;
7175 obj->log_level = log_level;
7177 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7179 if (strlen(btf_tmp_path) >= PATH_MAX) {
7180 err = -ENAMETOOLONG;
7183 obj->btf_custom_path = strdup(btf_tmp_path);
7184 if (!obj->btf_custom_path) {
7190 kconfig = OPTS_GET(opts, kconfig, NULL);
7192 obj->kconfig = strdup(kconfig);
7193 if (!obj->kconfig) {
7199 err = bpf_object__elf_init(obj);
7200 err = err ? : bpf_object__check_endianness(obj);
7201 err = err ? : bpf_object__elf_collect(obj);
7202 err = err ? : bpf_object__collect_externs(obj);
7203 err = err ? : bpf_object__finalize_btf(obj);
7204 err = err ? : bpf_object__init_maps(obj, opts);
7205 err = err ? : bpf_object_init_progs(obj, opts);
7206 err = err ? : bpf_object__collect_relos(obj);
7210 bpf_object__elf_finish(obj);
7214 bpf_object__close(obj);
7215 return ERR_PTR(err);
7219 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7222 return libbpf_err_ptr(-EINVAL);
7224 pr_debug("loading %s\n", path);
7226 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7229 struct bpf_object *bpf_object__open(const char *path)
7231 return bpf_object__open_file(path, NULL);
7235 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7236 const struct bpf_object_open_opts *opts)
7238 if (!obj_buf || obj_buf_sz == 0)
7239 return libbpf_err_ptr(-EINVAL);
7241 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7244 static int bpf_object_unload(struct bpf_object *obj)
7249 return libbpf_err(-EINVAL);
7251 for (i = 0; i < obj->nr_maps; i++) {
7252 zclose(obj->maps[i].fd);
7253 if (obj->maps[i].st_ops)
7254 zfree(&obj->maps[i].st_ops->kern_vdata);
7257 for (i = 0; i < obj->nr_programs; i++)
7258 bpf_program__unload(&obj->programs[i]);
7263 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7265 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7269 bpf_object__for_each_map(m, obj) {
7270 if (!bpf_map__is_internal(m))
7272 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7273 m->def.map_flags ^= BPF_F_MMAPABLE;
7279 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7281 char sym_type, sym_name[500];
7282 unsigned long long sym_addr;
7286 f = fopen("/proc/kallsyms", "r");
7289 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7294 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7295 &sym_addr, &sym_type, sym_name);
7296 if (ret == EOF && feof(f))
7299 pr_warn("failed to read kallsyms entry: %d\n", ret);
7304 err = cb(sym_addr, sym_type, sym_name, ctx);
7313 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7314 const char *sym_name, void *ctx)
7316 struct bpf_object *obj = ctx;
7317 const struct btf_type *t;
7318 struct extern_desc *ext;
7320 ext = find_extern_by_name(obj, sym_name);
7321 if (!ext || ext->type != EXT_KSYM)
7324 t = btf__type_by_id(obj->btf, ext->btf_id);
7328 if (ext->is_set && ext->ksym.addr != sym_addr) {
7329 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7330 sym_name, ext->ksym.addr, sym_addr);
7335 ext->ksym.addr = sym_addr;
7336 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7341 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7343 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7346 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7347 __u16 kind, struct btf **res_btf,
7348 struct module_btf **res_mod_btf)
7350 struct module_btf *mod_btf;
7354 btf = obj->btf_vmlinux;
7356 id = btf__find_by_name_kind(btf, ksym_name, kind);
7358 if (id == -ENOENT) {
7359 err = load_module_btfs(obj);
7363 for (i = 0; i < obj->btf_module_cnt; i++) {
7364 /* we assume module_btf's BTF FD is always >0 */
7365 mod_btf = &obj->btf_modules[i];
7367 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7376 *res_mod_btf = mod_btf;
7380 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7381 struct extern_desc *ext)
7383 const struct btf_type *targ_var, *targ_type;
7384 __u32 targ_type_id, local_type_id;
7385 struct module_btf *mod_btf = NULL;
7386 const char *targ_var_name;
7387 struct btf *btf = NULL;
7390 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7392 if (id == -ESRCH && ext->is_weak)
7394 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7399 /* find local type_id */
7400 local_type_id = ext->ksym.type_id;
7402 /* find target type_id */
7403 targ_var = btf__type_by_id(btf, id);
7404 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7405 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7407 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7410 const struct btf_type *local_type;
7411 const char *targ_name, *local_name;
7413 local_type = btf__type_by_id(obj->btf, local_type_id);
7414 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7415 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7417 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7418 ext->name, local_type_id,
7419 btf_kind_str(local_type), local_name, targ_type_id,
7420 btf_kind_str(targ_type), targ_name);
7425 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7426 ext->ksym.kernel_btf_id = id;
7427 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7428 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7433 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7434 struct extern_desc *ext)
7436 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7437 struct module_btf *mod_btf = NULL;
7438 const struct btf_type *kern_func;
7439 struct btf *kern_btf = NULL;
7442 local_func_proto_id = ext->ksym.type_id;
7444 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7446 if (kfunc_id == -ESRCH && ext->is_weak)
7448 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7453 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7454 kfunc_proto_id = kern_func->type;
7456 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7457 kern_btf, kfunc_proto_id);
7459 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7460 ext->name, local_func_proto_id, kfunc_proto_id);
7464 /* set index for module BTF fd in fd_array, if unset */
7465 if (mod_btf && !mod_btf->fd_array_idx) {
7466 /* insn->off is s16 */
7467 if (obj->fd_array_cnt == INT16_MAX) {
7468 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7469 ext->name, mod_btf->fd_array_idx);
7472 /* Cannot use index 0 for module BTF fd */
7473 if (!obj->fd_array_cnt)
7474 obj->fd_array_cnt = 1;
7476 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7477 obj->fd_array_cnt + 1);
7480 mod_btf->fd_array_idx = obj->fd_array_cnt;
7481 /* we assume module BTF FD is always >0 */
7482 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7486 ext->ksym.kernel_btf_id = kfunc_id;
7487 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7488 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7489 ext->name, kfunc_id);
7494 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7496 const struct btf_type *t;
7497 struct extern_desc *ext;
7500 for (i = 0; i < obj->nr_extern; i++) {
7501 ext = &obj->externs[i];
7502 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7505 if (obj->gen_loader) {
7507 ext->ksym.kernel_btf_obj_fd = 0;
7508 ext->ksym.kernel_btf_id = 0;
7511 t = btf__type_by_id(obj->btf, ext->btf_id);
7513 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7515 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7522 static int bpf_object__resolve_externs(struct bpf_object *obj,
7523 const char *extra_kconfig)
7525 bool need_config = false, need_kallsyms = false;
7526 bool need_vmlinux_btf = false;
7527 struct extern_desc *ext;
7528 void *kcfg_data = NULL;
7531 if (obj->nr_extern == 0)
7534 if (obj->kconfig_map_idx >= 0)
7535 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7537 for (i = 0; i < obj->nr_extern; i++) {
7538 ext = &obj->externs[i];
7540 if (ext->type == EXT_KSYM) {
7541 if (ext->ksym.type_id)
7542 need_vmlinux_btf = true;
7544 need_kallsyms = true;
7546 } else if (ext->type == EXT_KCFG) {
7547 void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7550 /* Kconfig externs need actual /proc/config.gz */
7551 if (str_has_pfx(ext->name, "CONFIG_")) {
7556 /* Virtual kcfg externs are customly handled by libbpf */
7557 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7558 value = get_kernel_version();
7560 pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7563 } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7564 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7565 } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7566 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7567 } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7568 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7569 * __kconfig externs, where LINUX_ ones are virtual and filled out
7570 * customly by libbpf (their values don't come from Kconfig).
7571 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7572 * __weak, it defaults to zero value, just like for CONFIG_xxx
7575 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7579 err = set_kcfg_value_num(ext, ext_ptr, value);
7582 pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7583 ext->name, (long long)value);
7585 pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7589 if (need_config && extra_kconfig) {
7590 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7593 need_config = false;
7594 for (i = 0; i < obj->nr_extern; i++) {
7595 ext = &obj->externs[i];
7596 if (ext->type == EXT_KCFG && !ext->is_set) {
7603 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7607 if (need_kallsyms) {
7608 err = bpf_object__read_kallsyms_file(obj);
7612 if (need_vmlinux_btf) {
7613 err = bpf_object__resolve_ksyms_btf_id(obj);
7617 for (i = 0; i < obj->nr_extern; i++) {
7618 ext = &obj->externs[i];
7620 if (!ext->is_set && !ext->is_weak) {
7621 pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7623 } else if (!ext->is_set) {
7624 pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7632 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7637 return libbpf_err(-EINVAL);
7640 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7641 return libbpf_err(-EINVAL);
7644 if (obj->gen_loader)
7645 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7647 err = bpf_object__probe_loading(obj);
7648 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7649 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7650 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7651 err = err ? : bpf_object__sanitize_maps(obj);
7652 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7653 err = err ? : bpf_object__create_maps(obj);
7654 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7655 err = err ? : bpf_object__load_progs(obj, extra_log_level);
7656 err = err ? : bpf_object_init_prog_arrays(obj);
7658 if (obj->gen_loader) {
7661 btf__set_fd(obj->btf, -1);
7662 for (i = 0; i < obj->nr_maps; i++)
7663 obj->maps[i].fd = -1;
7665 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7668 /* clean up fd_array */
7669 zfree(&obj->fd_array);
7671 /* clean up module BTFs */
7672 for (i = 0; i < obj->btf_module_cnt; i++) {
7673 close(obj->btf_modules[i].fd);
7674 btf__free(obj->btf_modules[i].btf);
7675 free(obj->btf_modules[i].name);
7677 free(obj->btf_modules);
7679 /* clean up vmlinux BTF */
7680 btf__free(obj->btf_vmlinux);
7681 obj->btf_vmlinux = NULL;
7683 obj->loaded = true; /* doesn't matter if successfully or not */
7690 /* unpin any maps that were auto-pinned during load */
7691 for (i = 0; i < obj->nr_maps; i++)
7692 if (obj->maps[i].pinned && !obj->maps[i].reused)
7693 bpf_map__unpin(&obj->maps[i], NULL);
7695 bpf_object_unload(obj);
7696 pr_warn("failed to load object '%s'\n", obj->path);
7697 return libbpf_err(err);
7700 int bpf_object__load(struct bpf_object *obj)
7702 return bpf_object_load(obj, 0, NULL);
7705 static int make_parent_dir(const char *path)
7707 char *cp, errmsg[STRERR_BUFSIZE];
7711 dname = strdup(path);
7715 dir = dirname(dname);
7716 if (mkdir(dir, 0700) && errno != EEXIST)
7721 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7722 pr_warn("failed to mkdir %s: %s\n", path, cp);
7727 static int check_path(const char *path)
7729 char *cp, errmsg[STRERR_BUFSIZE];
7730 struct statfs st_fs;
7737 dname = strdup(path);
7741 dir = dirname(dname);
7742 if (statfs(dir, &st_fs)) {
7743 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7744 pr_warn("failed to statfs %s: %s\n", dir, cp);
7749 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7750 pr_warn("specified path %s is not on BPF FS\n", path);
7757 int bpf_program__pin(struct bpf_program *prog, const char *path)
7759 char *cp, errmsg[STRERR_BUFSIZE];
7763 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7764 return libbpf_err(-EINVAL);
7767 err = make_parent_dir(path);
7769 return libbpf_err(err);
7771 err = check_path(path);
7773 return libbpf_err(err);
7775 if (bpf_obj_pin(prog->fd, path)) {
7777 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7778 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7779 return libbpf_err(err);
7782 pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7786 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7791 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7792 return libbpf_err(-EINVAL);
7795 err = check_path(path);
7797 return libbpf_err(err);
7801 return libbpf_err(-errno);
7803 pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7807 int bpf_map__pin(struct bpf_map *map, const char *path)
7809 char *cp, errmsg[STRERR_BUFSIZE];
7813 pr_warn("invalid map pointer\n");
7814 return libbpf_err(-EINVAL);
7817 if (map->pin_path) {
7818 if (path && strcmp(path, map->pin_path)) {
7819 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7820 bpf_map__name(map), map->pin_path, path);
7821 return libbpf_err(-EINVAL);
7822 } else if (map->pinned) {
7823 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7824 bpf_map__name(map), map->pin_path);
7829 pr_warn("missing a path to pin map '%s' at\n",
7830 bpf_map__name(map));
7831 return libbpf_err(-EINVAL);
7832 } else if (map->pinned) {
7833 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7834 return libbpf_err(-EEXIST);
7837 map->pin_path = strdup(path);
7838 if (!map->pin_path) {
7844 err = make_parent_dir(map->pin_path);
7846 return libbpf_err(err);
7848 err = check_path(map->pin_path);
7850 return libbpf_err(err);
7852 if (bpf_obj_pin(map->fd, map->pin_path)) {
7858 pr_debug("pinned map '%s'\n", map->pin_path);
7863 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7864 pr_warn("failed to pin map: %s\n", cp);
7865 return libbpf_err(err);
7868 int bpf_map__unpin(struct bpf_map *map, const char *path)
7873 pr_warn("invalid map pointer\n");
7874 return libbpf_err(-EINVAL);
7877 if (map->pin_path) {
7878 if (path && strcmp(path, map->pin_path)) {
7879 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7880 bpf_map__name(map), map->pin_path, path);
7881 return libbpf_err(-EINVAL);
7883 path = map->pin_path;
7885 pr_warn("no path to unpin map '%s' from\n",
7886 bpf_map__name(map));
7887 return libbpf_err(-EINVAL);
7890 err = check_path(path);
7892 return libbpf_err(err);
7896 return libbpf_err(-errno);
7898 map->pinned = false;
7899 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7904 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7911 return libbpf_err(-errno);
7914 free(map->pin_path);
7915 map->pin_path = new;
7919 __alias(bpf_map__pin_path)
7920 const char *bpf_map__get_pin_path(const struct bpf_map *map);
7922 const char *bpf_map__pin_path(const struct bpf_map *map)
7924 return map->pin_path;
7927 bool bpf_map__is_pinned(const struct bpf_map *map)
7932 static void sanitize_pin_path(char *s)
7934 /* bpffs disallows periods in path names */
7942 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7944 struct bpf_map *map;
7948 return libbpf_err(-ENOENT);
7951 pr_warn("object not yet loaded; load it first\n");
7952 return libbpf_err(-ENOENT);
7955 bpf_object__for_each_map(map, obj) {
7956 char *pin_path = NULL;
7959 if (!map->autocreate)
7965 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7966 bpf_map__name(map));
7969 goto err_unpin_maps;
7970 } else if (len >= PATH_MAX) {
7971 err = -ENAMETOOLONG;
7972 goto err_unpin_maps;
7974 sanitize_pin_path(buf);
7976 } else if (!map->pin_path) {
7980 err = bpf_map__pin(map, pin_path);
7982 goto err_unpin_maps;
7988 while ((map = bpf_object__prev_map(obj, map))) {
7992 bpf_map__unpin(map, NULL);
7995 return libbpf_err(err);
7998 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8000 struct bpf_map *map;
8004 return libbpf_err(-ENOENT);
8006 bpf_object__for_each_map(map, obj) {
8007 char *pin_path = NULL;
8013 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8014 bpf_map__name(map));
8016 return libbpf_err(-EINVAL);
8017 else if (len >= PATH_MAX)
8018 return libbpf_err(-ENAMETOOLONG);
8019 sanitize_pin_path(buf);
8021 } else if (!map->pin_path) {
8025 err = bpf_map__unpin(map, pin_path);
8027 return libbpf_err(err);
8033 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8035 struct bpf_program *prog;
8039 return libbpf_err(-ENOENT);
8042 pr_warn("object not yet loaded; load it first\n");
8043 return libbpf_err(-ENOENT);
8046 bpf_object__for_each_program(prog, obj) {
8050 len = snprintf(buf, PATH_MAX, "%s/%s", path, prog->name);
8053 goto err_unpin_programs;
8054 } else if (len >= PATH_MAX) {
8055 err = -ENAMETOOLONG;
8056 goto err_unpin_programs;
8059 err = bpf_program__pin(prog, buf);
8061 goto err_unpin_programs;
8067 while ((prog = bpf_object__prev_program(obj, prog))) {
8071 len = snprintf(buf, PATH_MAX, "%s/%s", path, prog->name);
8074 else if (len >= PATH_MAX)
8077 bpf_program__unpin(prog, buf);
8080 return libbpf_err(err);
8083 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8085 struct bpf_program *prog;
8089 return libbpf_err(-ENOENT);
8091 bpf_object__for_each_program(prog, obj) {
8095 len = snprintf(buf, PATH_MAX, "%s/%s", path, prog->name);
8097 return libbpf_err(-EINVAL);
8098 else if (len >= PATH_MAX)
8099 return libbpf_err(-ENAMETOOLONG);
8101 err = bpf_program__unpin(prog, buf);
8103 return libbpf_err(err);
8109 int bpf_object__pin(struct bpf_object *obj, const char *path)
8113 err = bpf_object__pin_maps(obj, path);
8115 return libbpf_err(err);
8117 err = bpf_object__pin_programs(obj, path);
8119 bpf_object__unpin_maps(obj, path);
8120 return libbpf_err(err);
8126 static void bpf_map__destroy(struct bpf_map *map)
8128 if (map->inner_map) {
8129 bpf_map__destroy(map->inner_map);
8130 zfree(&map->inner_map);
8133 zfree(&map->init_slots);
8134 map->init_slots_sz = 0;
8137 munmap(map->mmaped, bpf_map_mmap_sz(map));
8142 zfree(&map->st_ops->data);
8143 zfree(&map->st_ops->progs);
8144 zfree(&map->st_ops->kern_func_off);
8145 zfree(&map->st_ops);
8149 zfree(&map->real_name);
8150 zfree(&map->pin_path);
8156 void bpf_object__close(struct bpf_object *obj)
8160 if (IS_ERR_OR_NULL(obj))
8163 usdt_manager_free(obj->usdt_man);
8164 obj->usdt_man = NULL;
8166 bpf_gen__free(obj->gen_loader);
8167 bpf_object__elf_finish(obj);
8168 bpf_object_unload(obj);
8169 btf__free(obj->btf);
8170 btf_ext__free(obj->btf_ext);
8172 for (i = 0; i < obj->nr_maps; i++)
8173 bpf_map__destroy(&obj->maps[i]);
8175 zfree(&obj->btf_custom_path);
8176 zfree(&obj->kconfig);
8177 zfree(&obj->externs);
8183 if (obj->programs && obj->nr_programs) {
8184 for (i = 0; i < obj->nr_programs; i++)
8185 bpf_program__exit(&obj->programs[i]);
8187 zfree(&obj->programs);
8192 const char *bpf_object__name(const struct bpf_object *obj)
8194 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8197 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8199 return obj ? obj->kern_version : 0;
8202 struct btf *bpf_object__btf(const struct bpf_object *obj)
8204 return obj ? obj->btf : NULL;
8207 int bpf_object__btf_fd(const struct bpf_object *obj)
8209 return obj->btf ? btf__fd(obj->btf) : -1;
8212 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8215 return libbpf_err(-EINVAL);
8217 obj->kern_version = kern_version;
8222 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8224 struct bpf_gen *gen;
8228 if (!OPTS_VALID(opts, gen_loader_opts))
8230 gen = calloc(sizeof(*gen), 1);
8234 obj->gen_loader = gen;
8238 static struct bpf_program *
8239 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8242 size_t nr_programs = obj->nr_programs;
8249 /* Iter from the beginning */
8250 return forward ? &obj->programs[0] :
8251 &obj->programs[nr_programs - 1];
8253 if (p->obj != obj) {
8254 pr_warn("error: program handler doesn't match object\n");
8255 return errno = EINVAL, NULL;
8258 idx = (p - obj->programs) + (forward ? 1 : -1);
8259 if (idx >= obj->nr_programs || idx < 0)
8261 return &obj->programs[idx];
8264 struct bpf_program *
8265 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8267 struct bpf_program *prog = prev;
8270 prog = __bpf_program__iter(prog, obj, true);
8271 } while (prog && prog_is_subprog(obj, prog));
8276 struct bpf_program *
8277 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8279 struct bpf_program *prog = next;
8282 prog = __bpf_program__iter(prog, obj, false);
8283 } while (prog && prog_is_subprog(obj, prog));
8288 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8290 prog->prog_ifindex = ifindex;
8293 const char *bpf_program__name(const struct bpf_program *prog)
8298 const char *bpf_program__section_name(const struct bpf_program *prog)
8300 return prog->sec_name;
8303 bool bpf_program__autoload(const struct bpf_program *prog)
8305 return prog->autoload;
8308 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8310 if (prog->obj->loaded)
8311 return libbpf_err(-EINVAL);
8313 prog->autoload = autoload;
8317 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8322 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8324 return prog->insns_cnt;
8327 int bpf_program__set_insns(struct bpf_program *prog,
8328 struct bpf_insn *new_insns, size_t new_insn_cnt)
8330 struct bpf_insn *insns;
8332 if (prog->obj->loaded)
8335 insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8337 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8340 memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8342 prog->insns = insns;
8343 prog->insns_cnt = new_insn_cnt;
8347 int bpf_program__fd(const struct bpf_program *prog)
8350 return libbpf_err(-EINVAL);
8353 return libbpf_err(-ENOENT);
8358 __alias(bpf_program__type)
8359 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8361 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8366 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8368 if (prog->obj->loaded)
8369 return libbpf_err(-EBUSY);
8375 __alias(bpf_program__expected_attach_type)
8376 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8378 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8380 return prog->expected_attach_type;
8383 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8384 enum bpf_attach_type type)
8386 if (prog->obj->loaded)
8387 return libbpf_err(-EBUSY);
8389 prog->expected_attach_type = type;
8393 __u32 bpf_program__flags(const struct bpf_program *prog)
8395 return prog->prog_flags;
8398 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8400 if (prog->obj->loaded)
8401 return libbpf_err(-EBUSY);
8403 prog->prog_flags = flags;
8407 __u32 bpf_program__log_level(const struct bpf_program *prog)
8409 return prog->log_level;
8412 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8414 if (prog->obj->loaded)
8415 return libbpf_err(-EBUSY);
8417 prog->log_level = log_level;
8421 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8423 *log_size = prog->log_size;
8424 return prog->log_buf;
8427 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8429 if (log_size && !log_buf)
8431 if (prog->log_size > UINT_MAX)
8433 if (prog->obj->loaded)
8436 prog->log_buf = log_buf;
8437 prog->log_size = log_size;
8441 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8442 .sec = (char *)sec_pfx, \
8443 .prog_type = BPF_PROG_TYPE_##ptype, \
8444 .expected_attach_type = atype, \
8445 .cookie = (long)(flags), \
8446 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
8450 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8451 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8452 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8453 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8454 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8455 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8456 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8457 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8458 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8459 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8461 static const struct bpf_sec_def section_defs[] = {
8462 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8463 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8464 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8465 SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8466 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8467 SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8468 SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8469 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8470 SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8471 SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8472 SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8473 SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8474 SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8475 SEC_DEF("usdt+", KPROBE, 0, SEC_NONE, attach_usdt),
8476 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
8477 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE),
8478 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE),
8479 SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8480 SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8481 SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8482 SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8483 SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8484 SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8485 SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8486 SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8487 SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8488 SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8489 SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8490 SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8491 SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8492 SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8493 SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8494 SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8495 SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8496 SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8497 SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8498 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8499 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8500 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8501 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8502 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8503 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
8504 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8505 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8506 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8507 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8508 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8509 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8510 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8511 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8512 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8513 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8514 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8515 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8516 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8517 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8518 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8519 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8520 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8521 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8522 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8523 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8524 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8525 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8526 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8527 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8528 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8529 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8530 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8531 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8532 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8533 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8534 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8535 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8536 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8537 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8538 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8539 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8540 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8541 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8542 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8545 static size_t custom_sec_def_cnt;
8546 static struct bpf_sec_def *custom_sec_defs;
8547 static struct bpf_sec_def custom_fallback_def;
8548 static bool has_custom_fallback_def;
8550 static int last_custom_sec_def_handler_id;
8552 int libbpf_register_prog_handler(const char *sec,
8553 enum bpf_prog_type prog_type,
8554 enum bpf_attach_type exp_attach_type,
8555 const struct libbpf_prog_handler_opts *opts)
8557 struct bpf_sec_def *sec_def;
8559 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8560 return libbpf_err(-EINVAL);
8562 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8563 return libbpf_err(-E2BIG);
8566 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8569 return libbpf_err(-ENOMEM);
8571 custom_sec_defs = sec_def;
8572 sec_def = &custom_sec_defs[custom_sec_def_cnt];
8574 if (has_custom_fallback_def)
8575 return libbpf_err(-EBUSY);
8577 sec_def = &custom_fallback_def;
8580 sec_def->sec = sec ? strdup(sec) : NULL;
8581 if (sec && !sec_def->sec)
8582 return libbpf_err(-ENOMEM);
8584 sec_def->prog_type = prog_type;
8585 sec_def->expected_attach_type = exp_attach_type;
8586 sec_def->cookie = OPTS_GET(opts, cookie, 0);
8588 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8589 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8590 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8592 sec_def->handler_id = ++last_custom_sec_def_handler_id;
8595 custom_sec_def_cnt++;
8597 has_custom_fallback_def = true;
8599 return sec_def->handler_id;
8602 int libbpf_unregister_prog_handler(int handler_id)
8604 struct bpf_sec_def *sec_defs;
8607 if (handler_id <= 0)
8608 return libbpf_err(-EINVAL);
8610 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8611 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8612 has_custom_fallback_def = false;
8616 for (i = 0; i < custom_sec_def_cnt; i++) {
8617 if (custom_sec_defs[i].handler_id == handler_id)
8621 if (i == custom_sec_def_cnt)
8622 return libbpf_err(-ENOENT);
8624 free(custom_sec_defs[i].sec);
8625 for (i = i + 1; i < custom_sec_def_cnt; i++)
8626 custom_sec_defs[i - 1] = custom_sec_defs[i];
8627 custom_sec_def_cnt--;
8629 /* try to shrink the array, but it's ok if we couldn't */
8630 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8632 custom_sec_defs = sec_defs;
8637 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8639 size_t len = strlen(sec_def->sec);
8641 /* "type/" always has to have proper SEC("type/extras") form */
8642 if (sec_def->sec[len - 1] == '/') {
8643 if (str_has_pfx(sec_name, sec_def->sec))
8648 /* "type+" means it can be either exact SEC("type") or
8649 * well-formed SEC("type/extras") with proper '/' separator
8651 if (sec_def->sec[len - 1] == '+') {
8653 /* not even a prefix */
8654 if (strncmp(sec_name, sec_def->sec, len) != 0)
8656 /* exact match or has '/' separator */
8657 if (sec_name[len] == '\0' || sec_name[len] == '/')
8662 return strcmp(sec_name, sec_def->sec) == 0;
8665 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8667 const struct bpf_sec_def *sec_def;
8670 n = custom_sec_def_cnt;
8671 for (i = 0; i < n; i++) {
8672 sec_def = &custom_sec_defs[i];
8673 if (sec_def_matches(sec_def, sec_name))
8677 n = ARRAY_SIZE(section_defs);
8678 for (i = 0; i < n; i++) {
8679 sec_def = §ion_defs[i];
8680 if (sec_def_matches(sec_def, sec_name))
8684 if (has_custom_fallback_def)
8685 return &custom_fallback_def;
8690 #define MAX_TYPE_NAME_SIZE 32
8692 static char *libbpf_get_type_names(bool attach_type)
8694 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8702 /* Forge string buf with all available names */
8703 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8704 const struct bpf_sec_def *sec_def = §ion_defs[i];
8707 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8710 if (!(sec_def->cookie & SEC_ATTACHABLE))
8714 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8719 strcat(buf, section_defs[i].sec);
8725 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8726 enum bpf_attach_type *expected_attach_type)
8728 const struct bpf_sec_def *sec_def;
8732 return libbpf_err(-EINVAL);
8734 sec_def = find_sec_def(name);
8736 *prog_type = sec_def->prog_type;
8737 *expected_attach_type = sec_def->expected_attach_type;
8741 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8742 type_names = libbpf_get_type_names(false);
8743 if (type_names != NULL) {
8744 pr_debug("supported section(type) names are:%s\n", type_names);
8748 return libbpf_err(-ESRCH);
8751 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8753 if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8756 return attach_type_name[t];
8759 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8761 if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8764 return link_type_name[t];
8767 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8769 if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8772 return map_type_name[t];
8775 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8777 if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8780 return prog_type_name[t];
8783 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8786 struct bpf_map *map;
8789 for (i = 0; i < obj->nr_maps; i++) {
8790 map = &obj->maps[i];
8791 if (!bpf_map__is_struct_ops(map))
8793 if (map->sec_offset <= offset &&
8794 offset - map->sec_offset < map->def.value_size)
8801 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8802 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8803 Elf64_Shdr *shdr, Elf_Data *data)
8805 const struct btf_member *member;
8806 struct bpf_struct_ops *st_ops;
8807 struct bpf_program *prog;
8808 unsigned int shdr_idx;
8809 const struct btf *btf;
8810 struct bpf_map *map;
8811 unsigned int moff, insn_idx;
8819 nrels = shdr->sh_size / shdr->sh_entsize;
8820 for (i = 0; i < nrels; i++) {
8821 rel = elf_rel_by_idx(data, i);
8823 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8824 return -LIBBPF_ERRNO__FORMAT;
8827 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8829 pr_warn("struct_ops reloc: symbol %zx not found\n",
8830 (size_t)ELF64_R_SYM(rel->r_info));
8831 return -LIBBPF_ERRNO__FORMAT;
8834 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8835 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8837 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8838 (size_t)rel->r_offset);
8842 moff = rel->r_offset - map->sec_offset;
8843 shdr_idx = sym->st_shndx;
8844 st_ops = map->st_ops;
8845 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",
8847 (long long)(rel->r_info >> 32),
8848 (long long)sym->st_value,
8849 shdr_idx, (size_t)rel->r_offset,
8850 map->sec_offset, sym->st_name, name);
8852 if (shdr_idx >= SHN_LORESERVE) {
8853 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8854 map->name, (size_t)rel->r_offset, shdr_idx);
8855 return -LIBBPF_ERRNO__RELOC;
8857 if (sym->st_value % BPF_INSN_SZ) {
8858 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8859 map->name, (unsigned long long)sym->st_value);
8860 return -LIBBPF_ERRNO__FORMAT;
8862 insn_idx = sym->st_value / BPF_INSN_SZ;
8864 member = find_member_by_offset(st_ops->type, moff * 8);
8866 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8870 member_idx = member - btf_members(st_ops->type);
8871 name = btf__name_by_offset(btf, member->name_off);
8873 if (!resolve_func_ptr(btf, member->type, NULL)) {
8874 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8879 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8881 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8882 map->name, shdr_idx, name);
8886 /* prevent the use of BPF prog with invalid type */
8887 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8888 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8889 map->name, prog->name);
8893 /* if we haven't yet processed this BPF program, record proper
8894 * attach_btf_id and member_idx
8896 if (!prog->attach_btf_id) {
8897 prog->attach_btf_id = st_ops->type_id;
8898 prog->expected_attach_type = member_idx;
8901 /* struct_ops BPF prog can be re-used between multiple
8902 * .struct_ops as long as it's the same struct_ops struct
8903 * definition and the same function pointer field
8905 if (prog->attach_btf_id != st_ops->type_id ||
8906 prog->expected_attach_type != member_idx) {
8907 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",
8908 map->name, prog->name, prog->sec_name, prog->type,
8909 prog->attach_btf_id, prog->expected_attach_type, name);
8913 st_ops->progs[member_idx] = prog;
8919 #define BTF_TRACE_PREFIX "btf_trace_"
8920 #define BTF_LSM_PREFIX "bpf_lsm_"
8921 #define BTF_ITER_PREFIX "bpf_iter_"
8922 #define BTF_MAX_NAME_SIZE 128
8924 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8925 const char **prefix, int *kind)
8927 switch (attach_type) {
8928 case BPF_TRACE_RAW_TP:
8929 *prefix = BTF_TRACE_PREFIX;
8930 *kind = BTF_KIND_TYPEDEF;
8933 case BPF_LSM_CGROUP:
8934 *prefix = BTF_LSM_PREFIX;
8935 *kind = BTF_KIND_FUNC;
8937 case BPF_TRACE_ITER:
8938 *prefix = BTF_ITER_PREFIX;
8939 *kind = BTF_KIND_FUNC;
8943 *kind = BTF_KIND_FUNC;
8947 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8948 const char *name, __u32 kind)
8950 char btf_type_name[BTF_MAX_NAME_SIZE];
8953 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8954 "%s%s", prefix, name);
8955 /* snprintf returns the number of characters written excluding the
8956 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8957 * indicates truncation.
8959 if (ret < 0 || ret >= sizeof(btf_type_name))
8960 return -ENAMETOOLONG;
8961 return btf__find_by_name_kind(btf, btf_type_name, kind);
8964 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8965 enum bpf_attach_type attach_type)
8970 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8971 return find_btf_by_prefix_kind(btf, prefix, name, kind);
8974 int libbpf_find_vmlinux_btf_id(const char *name,
8975 enum bpf_attach_type attach_type)
8980 btf = btf__load_vmlinux_btf();
8981 err = libbpf_get_error(btf);
8983 pr_warn("vmlinux BTF is not found\n");
8984 return libbpf_err(err);
8987 err = find_attach_btf_id(btf, name, attach_type);
8989 pr_warn("%s is not found in vmlinux BTF\n", name);
8992 return libbpf_err(err);
8995 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8997 struct bpf_prog_info info = {};
8998 __u32 info_len = sizeof(info);
9002 err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9004 pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9005 attach_prog_fd, err);
9011 pr_warn("The target program doesn't have BTF\n");
9014 btf = btf__load_from_kernel_by_id(info.btf_id);
9015 err = libbpf_get_error(btf);
9017 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9020 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9023 pr_warn("%s is not found in prog's BTF\n", name);
9030 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9031 enum bpf_attach_type attach_type,
9032 int *btf_obj_fd, int *btf_type_id)
9036 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9038 *btf_obj_fd = 0; /* vmlinux BTF */
9045 ret = load_module_btfs(obj);
9049 for (i = 0; i < obj->btf_module_cnt; i++) {
9050 const struct module_btf *mod = &obj->btf_modules[i];
9052 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9054 *btf_obj_fd = mod->fd;
9067 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9068 int *btf_obj_fd, int *btf_type_id)
9070 enum bpf_attach_type attach_type = prog->expected_attach_type;
9071 __u32 attach_prog_fd = prog->attach_prog_fd;
9074 /* BPF program's BTF ID */
9075 if (attach_prog_fd) {
9076 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9078 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9079 attach_prog_fd, attach_name, err);
9087 /* kernel/module BTF ID */
9088 if (prog->obj->gen_loader) {
9089 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9093 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9096 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9102 int libbpf_attach_type_by_name(const char *name,
9103 enum bpf_attach_type *attach_type)
9106 const struct bpf_sec_def *sec_def;
9109 return libbpf_err(-EINVAL);
9111 sec_def = find_sec_def(name);
9113 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9114 type_names = libbpf_get_type_names(true);
9115 if (type_names != NULL) {
9116 pr_debug("attachable section(type) names are:%s\n", type_names);
9120 return libbpf_err(-EINVAL);
9123 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9124 return libbpf_err(-EINVAL);
9125 if (!(sec_def->cookie & SEC_ATTACHABLE))
9126 return libbpf_err(-EINVAL);
9128 *attach_type = sec_def->expected_attach_type;
9132 int bpf_map__fd(const struct bpf_map *map)
9134 return map ? map->fd : libbpf_err(-EINVAL);
9137 static bool map_uses_real_name(const struct bpf_map *map)
9139 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9140 * their user-visible name differs from kernel-visible name. Users see
9141 * such map's corresponding ELF section name as a map name.
9142 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9143 * maps to know which name has to be returned to the user.
9145 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9147 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9152 const char *bpf_map__name(const struct bpf_map *map)
9157 if (map_uses_real_name(map))
9158 return map->real_name;
9163 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9165 return map->def.type;
9168 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9171 return libbpf_err(-EBUSY);
9172 map->def.type = type;
9176 __u32 bpf_map__map_flags(const struct bpf_map *map)
9178 return map->def.map_flags;
9181 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9184 return libbpf_err(-EBUSY);
9185 map->def.map_flags = flags;
9189 __u64 bpf_map__map_extra(const struct bpf_map *map)
9191 return map->map_extra;
9194 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9197 return libbpf_err(-EBUSY);
9198 map->map_extra = map_extra;
9202 __u32 bpf_map__numa_node(const struct bpf_map *map)
9204 return map->numa_node;
9207 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9210 return libbpf_err(-EBUSY);
9211 map->numa_node = numa_node;
9215 __u32 bpf_map__key_size(const struct bpf_map *map)
9217 return map->def.key_size;
9220 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9223 return libbpf_err(-EBUSY);
9224 map->def.key_size = size;
9228 __u32 bpf_map__value_size(const struct bpf_map *map)
9230 return map->def.value_size;
9233 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9236 return libbpf_err(-EBUSY);
9237 map->def.value_size = size;
9241 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9243 return map ? map->btf_key_type_id : 0;
9246 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9248 return map ? map->btf_value_type_id : 0;
9251 int bpf_map__set_initial_value(struct bpf_map *map,
9252 const void *data, size_t size)
9254 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9255 size != map->def.value_size || map->fd >= 0)
9256 return libbpf_err(-EINVAL);
9258 memcpy(map->mmaped, data, size);
9262 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9266 *psize = map->def.value_size;
9270 bool bpf_map__is_internal(const struct bpf_map *map)
9272 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9275 __u32 bpf_map__ifindex(const struct bpf_map *map)
9277 return map->map_ifindex;
9280 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9283 return libbpf_err(-EBUSY);
9284 map->map_ifindex = ifindex;
9288 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9290 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9291 pr_warn("error: unsupported map type\n");
9292 return libbpf_err(-EINVAL);
9294 if (map->inner_map_fd != -1) {
9295 pr_warn("error: inner_map_fd already specified\n");
9296 return libbpf_err(-EINVAL);
9298 if (map->inner_map) {
9299 bpf_map__destroy(map->inner_map);
9300 zfree(&map->inner_map);
9302 map->inner_map_fd = fd;
9306 static struct bpf_map *
9307 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9310 struct bpf_map *s, *e;
9312 if (!obj || !obj->maps)
9313 return errno = EINVAL, NULL;
9316 e = obj->maps + obj->nr_maps;
9318 if ((m < s) || (m >= e)) {
9319 pr_warn("error in %s: map handler doesn't belong to object\n",
9321 return errno = EINVAL, NULL;
9324 idx = (m - obj->maps) + i;
9325 if (idx >= obj->nr_maps || idx < 0)
9327 return &obj->maps[idx];
9331 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9336 return __bpf_map__iter(prev, obj, 1);
9340 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9345 return obj->maps + obj->nr_maps - 1;
9348 return __bpf_map__iter(next, obj, -1);
9352 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9354 struct bpf_map *pos;
9356 bpf_object__for_each_map(pos, obj) {
9357 /* if it's a special internal map name (which always starts
9358 * with dot) then check if that special name matches the
9359 * real map name (ELF section name)
9361 if (name[0] == '.') {
9362 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9366 /* otherwise map name has to be an exact match */
9367 if (map_uses_real_name(pos)) {
9368 if (strcmp(pos->real_name, name) == 0)
9372 if (strcmp(pos->name, name) == 0)
9375 return errno = ENOENT, NULL;
9379 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9381 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9384 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9385 size_t value_sz, bool check_value_sz)
9390 if (map->def.key_size != key_sz) {
9391 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9392 map->name, key_sz, map->def.key_size);
9396 if (!check_value_sz)
9399 switch (map->def.type) {
9400 case BPF_MAP_TYPE_PERCPU_ARRAY:
9401 case BPF_MAP_TYPE_PERCPU_HASH:
9402 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9403 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9404 int num_cpu = libbpf_num_possible_cpus();
9405 size_t elem_sz = roundup(map->def.value_size, 8);
9407 if (value_sz != num_cpu * elem_sz) {
9408 pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9409 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9415 if (map->def.value_size != value_sz) {
9416 pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9417 map->name, value_sz, map->def.value_size);
9425 int bpf_map__lookup_elem(const struct bpf_map *map,
9426 const void *key, size_t key_sz,
9427 void *value, size_t value_sz, __u64 flags)
9431 err = validate_map_op(map, key_sz, value_sz, true);
9433 return libbpf_err(err);
9435 return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9438 int bpf_map__update_elem(const struct bpf_map *map,
9439 const void *key, size_t key_sz,
9440 const void *value, size_t value_sz, __u64 flags)
9444 err = validate_map_op(map, key_sz, value_sz, true);
9446 return libbpf_err(err);
9448 return bpf_map_update_elem(map->fd, key, value, flags);
9451 int bpf_map__delete_elem(const struct bpf_map *map,
9452 const void *key, size_t key_sz, __u64 flags)
9456 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9458 return libbpf_err(err);
9460 return bpf_map_delete_elem_flags(map->fd, key, flags);
9463 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9464 const void *key, size_t key_sz,
9465 void *value, size_t value_sz, __u64 flags)
9469 err = validate_map_op(map, key_sz, value_sz, true);
9471 return libbpf_err(err);
9473 return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9476 int bpf_map__get_next_key(const struct bpf_map *map,
9477 const void *cur_key, void *next_key, size_t key_sz)
9481 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9483 return libbpf_err(err);
9485 return bpf_map_get_next_key(map->fd, cur_key, next_key);
9488 long libbpf_get_error(const void *ptr)
9490 if (!IS_ERR_OR_NULL(ptr))
9494 errno = -PTR_ERR(ptr);
9496 /* If ptr == NULL, then errno should be already set by the failing
9497 * API, because libbpf never returns NULL on success and it now always
9498 * sets errno on error. So no extra errno handling for ptr == NULL
9504 /* Replace link's underlying BPF program with the new one */
9505 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9509 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9510 return libbpf_err_errno(ret);
9513 /* Release "ownership" of underlying BPF resource (typically, BPF program
9514 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9515 * link, when destructed through bpf_link__destroy() call won't attempt to
9516 * detach/unregisted that BPF resource. This is useful in situations where,
9517 * say, attached BPF program has to outlive userspace program that attached it
9518 * in the system. Depending on type of BPF program, though, there might be
9519 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9520 * exit of userspace program doesn't trigger automatic detachment and clean up
9521 * inside the kernel.
9523 void bpf_link__disconnect(struct bpf_link *link)
9525 link->disconnected = true;
9528 int bpf_link__destroy(struct bpf_link *link)
9532 if (IS_ERR_OR_NULL(link))
9535 if (!link->disconnected && link->detach)
9536 err = link->detach(link);
9538 free(link->pin_path);
9540 link->dealloc(link);
9544 return libbpf_err(err);
9547 int bpf_link__fd(const struct bpf_link *link)
9552 const char *bpf_link__pin_path(const struct bpf_link *link)
9554 return link->pin_path;
9557 static int bpf_link__detach_fd(struct bpf_link *link)
9559 return libbpf_err_errno(close(link->fd));
9562 struct bpf_link *bpf_link__open(const char *path)
9564 struct bpf_link *link;
9567 fd = bpf_obj_get(path);
9570 pr_warn("failed to open link at %s: %d\n", path, fd);
9571 return libbpf_err_ptr(fd);
9574 link = calloc(1, sizeof(*link));
9577 return libbpf_err_ptr(-ENOMEM);
9579 link->detach = &bpf_link__detach_fd;
9582 link->pin_path = strdup(path);
9583 if (!link->pin_path) {
9584 bpf_link__destroy(link);
9585 return libbpf_err_ptr(-ENOMEM);
9591 int bpf_link__detach(struct bpf_link *link)
9593 return bpf_link_detach(link->fd) ? -errno : 0;
9596 int bpf_link__pin(struct bpf_link *link, const char *path)
9601 return libbpf_err(-EBUSY);
9602 err = make_parent_dir(path);
9604 return libbpf_err(err);
9605 err = check_path(path);
9607 return libbpf_err(err);
9609 link->pin_path = strdup(path);
9610 if (!link->pin_path)
9611 return libbpf_err(-ENOMEM);
9613 if (bpf_obj_pin(link->fd, link->pin_path)) {
9615 zfree(&link->pin_path);
9616 return libbpf_err(err);
9619 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9623 int bpf_link__unpin(struct bpf_link *link)
9627 if (!link->pin_path)
9628 return libbpf_err(-EINVAL);
9630 err = unlink(link->pin_path);
9634 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9635 zfree(&link->pin_path);
9639 struct bpf_link_perf {
9640 struct bpf_link link;
9642 /* legacy kprobe support: keep track of probe identifier and type */
9643 char *legacy_probe_name;
9644 bool legacy_is_kprobe;
9645 bool legacy_is_retprobe;
9648 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9649 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9651 static int bpf_link_perf_detach(struct bpf_link *link)
9653 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9656 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9659 if (perf_link->perf_event_fd != link->fd)
9660 close(perf_link->perf_event_fd);
9663 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9664 if (perf_link->legacy_probe_name) {
9665 if (perf_link->legacy_is_kprobe) {
9666 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9667 perf_link->legacy_is_retprobe);
9669 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9670 perf_link->legacy_is_retprobe);
9677 static void bpf_link_perf_dealloc(struct bpf_link *link)
9679 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9681 free(perf_link->legacy_probe_name);
9685 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9686 const struct bpf_perf_event_opts *opts)
9688 char errmsg[STRERR_BUFSIZE];
9689 struct bpf_link_perf *link;
9690 int prog_fd, link_fd = -1, err;
9692 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9693 return libbpf_err_ptr(-EINVAL);
9696 pr_warn("prog '%s': invalid perf event FD %d\n",
9698 return libbpf_err_ptr(-EINVAL);
9700 prog_fd = bpf_program__fd(prog);
9702 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9704 return libbpf_err_ptr(-EINVAL);
9707 link = calloc(1, sizeof(*link));
9709 return libbpf_err_ptr(-ENOMEM);
9710 link->link.detach = &bpf_link_perf_detach;
9711 link->link.dealloc = &bpf_link_perf_dealloc;
9712 link->perf_event_fd = pfd;
9714 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9715 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9716 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9718 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9721 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9723 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9726 link->link.fd = link_fd;
9728 if (OPTS_GET(opts, bpf_cookie, 0)) {
9729 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9734 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9736 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9737 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9739 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9743 link->link.fd = pfd;
9745 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9747 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9748 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9757 return libbpf_err_ptr(err);
9760 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9762 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9766 * this function is expected to parse integer in the range of [0, 2^31-1] from
9767 * given file using scanf format string fmt. If actual parsed value is
9768 * negative, the result might be indistinguishable from error
9770 static int parse_uint_from_file(const char *file, const char *fmt)
9772 char buf[STRERR_BUFSIZE];
9776 f = fopen(file, "r");
9779 pr_debug("failed to open '%s': %s\n", file,
9780 libbpf_strerror_r(err, buf, sizeof(buf)));
9783 err = fscanf(f, fmt, &ret);
9785 err = err == EOF ? -EIO : -errno;
9786 pr_debug("failed to parse '%s': %s\n", file,
9787 libbpf_strerror_r(err, buf, sizeof(buf)));
9795 static int determine_kprobe_perf_type(void)
9797 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9799 return parse_uint_from_file(file, "%d\n");
9802 static int determine_uprobe_perf_type(void)
9804 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9806 return parse_uint_from_file(file, "%d\n");
9809 static int determine_kprobe_retprobe_bit(void)
9811 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9813 return parse_uint_from_file(file, "config:%d\n");
9816 static int determine_uprobe_retprobe_bit(void)
9818 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9820 return parse_uint_from_file(file, "config:%d\n");
9823 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9824 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9826 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9827 uint64_t offset, int pid, size_t ref_ctr_off)
9829 struct perf_event_attr attr = {};
9830 char errmsg[STRERR_BUFSIZE];
9833 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9836 type = uprobe ? determine_uprobe_perf_type()
9837 : determine_kprobe_perf_type();
9839 pr_warn("failed to determine %s perf type: %s\n",
9840 uprobe ? "uprobe" : "kprobe",
9841 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9845 int bit = uprobe ? determine_uprobe_retprobe_bit()
9846 : determine_kprobe_retprobe_bit();
9849 pr_warn("failed to determine %s retprobe bit: %s\n",
9850 uprobe ? "uprobe" : "kprobe",
9851 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9854 attr.config |= 1 << bit;
9856 attr.size = sizeof(attr);
9858 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9859 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9860 attr.config2 = offset; /* kprobe_addr or probe_offset */
9862 /* pid filter is meaningful only for uprobes */
9863 pfd = syscall(__NR_perf_event_open, &attr,
9864 pid < 0 ? -1 : pid /* pid */,
9865 pid == -1 ? 0 : -1 /* cpu */,
9866 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9867 return pfd >= 0 ? pfd : -errno;
9870 static int append_to_file(const char *file, const char *fmt, ...)
9875 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9880 n = vdprintf(fd, fmt, ap);
9890 #define DEBUGFS "/sys/kernel/debug/tracing"
9891 #define TRACEFS "/sys/kernel/tracing"
9893 static bool use_debugfs(void)
9895 static int has_debugfs = -1;
9897 if (has_debugfs < 0)
9898 has_debugfs = access(DEBUGFS, F_OK) == 0;
9900 return has_debugfs == 1;
9903 static const char *tracefs_path(void)
9905 return use_debugfs() ? DEBUGFS : TRACEFS;
9908 static const char *tracefs_kprobe_events(void)
9910 return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
9913 static const char *tracefs_uprobe_events(void)
9915 return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
9918 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9919 const char *kfunc_name, size_t offset)
9921 static int index = 0;
9923 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
9924 __sync_fetch_and_add(&index, 1));
9927 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9928 const char *kfunc_name, size_t offset)
9930 return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
9931 retprobe ? 'r' : 'p',
9932 retprobe ? "kretprobes" : "kprobes",
9933 probe_name, kfunc_name, offset);
9936 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9938 return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
9939 retprobe ? "kretprobes" : "kprobes", probe_name);
9942 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9946 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
9947 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
9949 return parse_uint_from_file(file, "%d\n");
9952 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9953 const char *kfunc_name, size_t offset, int pid)
9955 struct perf_event_attr attr = {};
9956 char errmsg[STRERR_BUFSIZE];
9959 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9961 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9963 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9966 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
9969 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9971 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9972 goto err_clean_legacy;
9974 attr.size = sizeof(attr);
9976 attr.type = PERF_TYPE_TRACEPOINT;
9978 pfd = syscall(__NR_perf_event_open, &attr,
9979 pid < 0 ? -1 : pid, /* pid */
9980 pid == -1 ? 0 : -1, /* cpu */
9981 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9984 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
9985 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9986 goto err_clean_legacy;
9991 /* Clear the newly added legacy kprobe_event */
9992 remove_kprobe_event_legacy(probe_name, retprobe);
9996 static const char *arch_specific_syscall_pfx(void)
9998 #if defined(__x86_64__)
10000 #elif defined(__i386__)
10002 #elif defined(__s390x__)
10004 #elif defined(__s390__)
10006 #elif defined(__arm__)
10008 #elif defined(__aarch64__)
10010 #elif defined(__mips__)
10012 #elif defined(__riscv)
10014 #elif defined(__powerpc__)
10016 #elif defined(__powerpc64__)
10017 return "powerpc64";
10023 static int probe_kern_syscall_wrapper(void)
10025 char syscall_name[64];
10026 const char *ksys_pfx;
10028 ksys_pfx = arch_specific_syscall_pfx();
10032 snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10034 if (determine_kprobe_perf_type() >= 0) {
10037 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10041 return pfd >= 0 ? 1 : 0;
10042 } else { /* legacy mode */
10043 char probe_name[128];
10045 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10046 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10049 (void)remove_kprobe_event_legacy(probe_name, false);
10055 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10056 const char *func_name,
10057 const struct bpf_kprobe_opts *opts)
10059 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10060 char errmsg[STRERR_BUFSIZE];
10061 char *legacy_probe = NULL;
10062 struct bpf_link *link;
10064 bool retprobe, legacy;
10067 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10068 return libbpf_err_ptr(-EINVAL);
10070 retprobe = OPTS_GET(opts, retprobe, false);
10071 offset = OPTS_GET(opts, offset, 0);
10072 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10074 legacy = determine_kprobe_perf_type() < 0;
10076 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10078 -1 /* pid */, 0 /* ref_ctr_off */);
10080 char probe_name[256];
10082 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10083 func_name, offset);
10085 legacy_probe = strdup(probe_name);
10087 return libbpf_err_ptr(-ENOMEM);
10089 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10090 offset, -1 /* pid */);
10094 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10095 prog->name, retprobe ? "kretprobe" : "kprobe",
10097 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10100 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10101 err = libbpf_get_error(link);
10104 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10105 prog->name, retprobe ? "kretprobe" : "kprobe",
10107 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10108 goto err_clean_legacy;
10111 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10113 perf_link->legacy_probe_name = legacy_probe;
10114 perf_link->legacy_is_kprobe = true;
10115 perf_link->legacy_is_retprobe = retprobe;
10122 remove_kprobe_event_legacy(legacy_probe, retprobe);
10124 free(legacy_probe);
10125 return libbpf_err_ptr(err);
10128 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10130 const char *func_name)
10132 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10133 .retprobe = retprobe,
10136 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10139 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10140 const char *syscall_name,
10141 const struct bpf_ksyscall_opts *opts)
10143 LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10144 char func_name[128];
10146 if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10147 return libbpf_err_ptr(-EINVAL);
10149 if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10150 /* arch_specific_syscall_pfx() should never return NULL here
10151 * because it is guarded by kernel_supports(). However, since
10152 * compiler does not know that we have an explicit conditional
10155 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10156 arch_specific_syscall_pfx() ? : "", syscall_name);
10158 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10161 kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10162 kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10164 return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10167 /* Adapted from perf/util/string.c */
10168 static bool glob_match(const char *str, const char *pat)
10170 while (*str && *pat && *pat != '*') {
10171 if (*pat == '?') { /* Matches any single character */
10181 /* Check wild card */
10183 while (*pat == '*')
10185 if (!*pat) /* Tail wild card matches all */
10188 if (glob_match(str++, pat))
10191 return !*str && !*pat;
10194 struct kprobe_multi_resolve {
10195 const char *pattern;
10196 unsigned long *addrs;
10202 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10203 const char *sym_name, void *ctx)
10205 struct kprobe_multi_resolve *res = ctx;
10208 if (!glob_match(sym_name, res->pattern))
10211 err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10216 res->addrs[res->cnt++] = (unsigned long) sym_addr;
10221 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10222 const char *pattern,
10223 const struct bpf_kprobe_multi_opts *opts)
10225 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10226 struct kprobe_multi_resolve res = {
10227 .pattern = pattern,
10229 struct bpf_link *link = NULL;
10230 char errmsg[STRERR_BUFSIZE];
10231 const unsigned long *addrs;
10232 int err, link_fd, prog_fd;
10233 const __u64 *cookies;
10238 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10239 return libbpf_err_ptr(-EINVAL);
10241 syms = OPTS_GET(opts, syms, false);
10242 addrs = OPTS_GET(opts, addrs, false);
10243 cnt = OPTS_GET(opts, cnt, false);
10244 cookies = OPTS_GET(opts, cookies, false);
10246 if (!pattern && !addrs && !syms)
10247 return libbpf_err_ptr(-EINVAL);
10248 if (pattern && (addrs || syms || cookies || cnt))
10249 return libbpf_err_ptr(-EINVAL);
10250 if (!pattern && !cnt)
10251 return libbpf_err_ptr(-EINVAL);
10253 return libbpf_err_ptr(-EINVAL);
10256 err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10267 retprobe = OPTS_GET(opts, retprobe, false);
10269 lopts.kprobe_multi.syms = syms;
10270 lopts.kprobe_multi.addrs = addrs;
10271 lopts.kprobe_multi.cookies = cookies;
10272 lopts.kprobe_multi.cnt = cnt;
10273 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10275 link = calloc(1, sizeof(*link));
10280 link->detach = &bpf_link__detach_fd;
10282 prog_fd = bpf_program__fd(prog);
10283 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10286 pr_warn("prog '%s': failed to attach: %s\n",
10287 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10290 link->fd = link_fd;
10297 return libbpf_err_ptr(err);
10300 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10302 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10303 unsigned long offset = 0;
10304 const char *func_name;
10310 /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10311 if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10314 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10316 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10318 func_name = prog->sec_name + sizeof("kprobe/") - 1;
10320 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10322 pr_warn("kprobe name is invalid: %s\n", func_name);
10325 if (opts.retprobe && offset != 0) {
10327 pr_warn("kretprobes do not support offset specification\n");
10331 opts.offset = offset;
10332 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10334 return libbpf_get_error(*link);
10337 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10339 LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10340 const char *syscall_name;
10344 /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10345 if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10348 opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10350 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10352 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10354 *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10355 return *link ? 0 : -errno;
10358 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10360 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10367 /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10368 if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10369 strcmp(prog->sec_name, "kretprobe.multi") == 0)
10372 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10374 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10376 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10378 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10380 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10384 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10386 return libbpf_get_error(*link);
10389 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10390 const char *binary_path, uint64_t offset)
10394 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10396 /* sanitize binary_path in the probe name */
10397 for (i = 0; buf[i]; i++) {
10398 if (!isalnum(buf[i]))
10403 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10404 const char *binary_path, size_t offset)
10406 return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10407 retprobe ? 'r' : 'p',
10408 retprobe ? "uretprobes" : "uprobes",
10409 probe_name, binary_path, offset);
10412 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10414 return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10415 retprobe ? "uretprobes" : "uprobes", probe_name);
10418 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10422 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10423 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10425 return parse_uint_from_file(file, "%d\n");
10428 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10429 const char *binary_path, size_t offset, int pid)
10431 struct perf_event_attr attr;
10432 int type, pfd, err;
10434 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10436 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10437 binary_path, (size_t)offset, err);
10440 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10443 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10444 binary_path, offset, err);
10445 goto err_clean_legacy;
10448 memset(&attr, 0, sizeof(attr));
10449 attr.size = sizeof(attr);
10450 attr.config = type;
10451 attr.type = PERF_TYPE_TRACEPOINT;
10453 pfd = syscall(__NR_perf_event_open, &attr,
10454 pid < 0 ? -1 : pid, /* pid */
10455 pid == -1 ? 0 : -1, /* cpu */
10456 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10459 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10460 goto err_clean_legacy;
10465 /* Clear the newly added legacy uprobe_event */
10466 remove_uprobe_event_legacy(probe_name, retprobe);
10470 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10471 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10473 while ((scn = elf_nextscn(elf, scn)) != NULL) {
10476 if (!gelf_getshdr(scn, &sh))
10478 if (sh.sh_type == sh_type)
10484 /* Find offset of function name in object specified by path. "name" matches
10485 * symbol name or name@@LIB for library functions.
10487 static long elf_find_func_offset(const char *binary_path, const char *name)
10489 int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10490 bool is_shared_lib, is_name_qualified;
10491 char errmsg[STRERR_BUFSIZE];
10492 long ret = -ENOENT;
10497 fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10500 pr_warn("failed to open %s: %s\n", binary_path,
10501 libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10504 elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10506 pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10508 return -LIBBPF_ERRNO__FORMAT;
10510 if (!gelf_getehdr(elf, &ehdr)) {
10511 pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10512 ret = -LIBBPF_ERRNO__FORMAT;
10515 /* for shared lib case, we do not need to calculate relative offset */
10516 is_shared_lib = ehdr.e_type == ET_DYN;
10518 name_len = strlen(name);
10519 /* Does name specify "@@LIB"? */
10520 is_name_qualified = strstr(name, "@@") != NULL;
10522 /* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10523 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10524 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10525 * reported as a warning/error.
10527 for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10528 size_t nr_syms, strtabidx, idx;
10529 Elf_Data *symbols = NULL;
10530 Elf_Scn *scn = NULL;
10531 int last_bind = -1;
10535 scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10537 pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10541 if (!gelf_getshdr(scn, &sh))
10543 strtabidx = sh.sh_link;
10544 symbols = elf_getdata(scn, 0);
10546 pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10547 binary_path, elf_errmsg(-1));
10548 ret = -LIBBPF_ERRNO__FORMAT;
10551 nr_syms = symbols->d_size / sh.sh_entsize;
10553 for (idx = 0; idx < nr_syms; idx++) {
10559 if (!gelf_getsym(symbols, idx, &sym))
10562 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10565 sname = elf_strptr(elf, strtabidx, sym.st_name);
10569 curr_bind = GELF_ST_BIND(sym.st_info);
10571 /* User can specify func, func@@LIB or func@@LIB_VERSION. */
10572 if (strncmp(sname, name, name_len) != 0)
10574 /* ...but we don't want a search for "foo" to match 'foo2" also, so any
10575 * additional characters in sname should be of the form "@@LIB".
10577 if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10581 /* handle multiple matches */
10582 if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10583 /* Only accept one non-weak bind. */
10584 pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10585 sname, name, binary_path);
10586 ret = -LIBBPF_ERRNO__FORMAT;
10588 } else if (curr_bind == STB_WEAK) {
10589 /* already have a non-weak bind, and
10590 * this is a weak bind, so ignore.
10596 /* Transform symbol's virtual address (absolute for
10597 * binaries and relative for shared libs) into file
10598 * offset, which is what kernel is expecting for
10599 * uprobe/uretprobe attachment.
10600 * See Documentation/trace/uprobetracer.rst for more
10602 * This is done by looking up symbol's containing
10603 * section's header and using it's virtual address
10604 * (sh_addr) and corresponding file offset (sh_offset)
10605 * to transform sym.st_value (virtual address) into
10606 * desired final file offset.
10608 sym_scn = elf_getscn(elf, sym.st_shndx);
10611 if (!gelf_getshdr(sym_scn, &sym_sh))
10614 ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10615 last_bind = curr_bind;
10622 pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10626 pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10627 is_shared_lib ? "should not be 0 in a shared library" :
10628 "try using shared library path instead");
10631 pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10640 static const char *arch_specific_lib_paths(void)
10643 * Based on https://packages.debian.org/sid/libc6.
10645 * Assume that the traced program is built for the same architecture
10646 * as libbpf, which should cover the vast majority of cases.
10648 #if defined(__x86_64__)
10649 return "/lib/x86_64-linux-gnu";
10650 #elif defined(__i386__)
10651 return "/lib/i386-linux-gnu";
10652 #elif defined(__s390x__)
10653 return "/lib/s390x-linux-gnu";
10654 #elif defined(__s390__)
10655 return "/lib/s390-linux-gnu";
10656 #elif defined(__arm__) && defined(__SOFTFP__)
10657 return "/lib/arm-linux-gnueabi";
10658 #elif defined(__arm__) && !defined(__SOFTFP__)
10659 return "/lib/arm-linux-gnueabihf";
10660 #elif defined(__aarch64__)
10661 return "/lib/aarch64-linux-gnu";
10662 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10663 return "/lib/mips64el-linux-gnuabi64";
10664 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10665 return "/lib/mipsel-linux-gnu";
10666 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10667 return "/lib/powerpc64le-linux-gnu";
10668 #elif defined(__sparc__) && defined(__arch64__)
10669 return "/lib/sparc64-linux-gnu";
10670 #elif defined(__riscv) && __riscv_xlen == 64
10671 return "/lib/riscv64-linux-gnu";
10677 /* Get full path to program/shared library. */
10678 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10680 const char *search_paths[3] = {};
10683 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10684 search_paths[0] = getenv("LD_LIBRARY_PATH");
10685 search_paths[1] = "/usr/lib64:/usr/lib";
10686 search_paths[2] = arch_specific_lib_paths();
10689 search_paths[0] = getenv("PATH");
10690 search_paths[1] = "/usr/bin:/usr/sbin";
10691 perm = R_OK | X_OK;
10694 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10697 if (!search_paths[i])
10699 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10705 next_path = strchr(s, ':');
10706 seg_len = next_path ? next_path - s : strlen(s);
10709 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10710 /* ensure it has required permissions */
10711 if (access(result, perm) < 0)
10713 pr_debug("resolved '%s' to '%s'\n", file, result);
10720 LIBBPF_API struct bpf_link *
10721 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10722 const char *binary_path, size_t func_offset,
10723 const struct bpf_uprobe_opts *opts)
10725 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10726 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10727 char full_binary_path[PATH_MAX];
10728 struct bpf_link *link;
10729 size_t ref_ctr_off;
10731 bool retprobe, legacy;
10732 const char *func_name;
10734 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10735 return libbpf_err_ptr(-EINVAL);
10737 retprobe = OPTS_GET(opts, retprobe, false);
10738 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10739 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10742 return libbpf_err_ptr(-EINVAL);
10744 if (!strchr(binary_path, '/')) {
10745 err = resolve_full_path(binary_path, full_binary_path,
10746 sizeof(full_binary_path));
10748 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10749 prog->name, binary_path, err);
10750 return libbpf_err_ptr(err);
10752 binary_path = full_binary_path;
10754 func_name = OPTS_GET(opts, func_name, NULL);
10758 sym_off = elf_find_func_offset(binary_path, func_name);
10760 return libbpf_err_ptr(sym_off);
10761 func_offset += sym_off;
10764 legacy = determine_uprobe_perf_type() < 0;
10766 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10767 func_offset, pid, ref_ctr_off);
10769 char probe_name[PATH_MAX + 64];
10772 return libbpf_err_ptr(-EINVAL);
10774 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10775 binary_path, func_offset);
10777 legacy_probe = strdup(probe_name);
10779 return libbpf_err_ptr(-ENOMEM);
10781 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10782 binary_path, func_offset, pid);
10786 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10787 prog->name, retprobe ? "uretprobe" : "uprobe",
10788 binary_path, func_offset,
10789 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10793 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10794 err = libbpf_get_error(link);
10797 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10798 prog->name, retprobe ? "uretprobe" : "uprobe",
10799 binary_path, func_offset,
10800 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10801 goto err_clean_legacy;
10804 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10806 perf_link->legacy_probe_name = legacy_probe;
10807 perf_link->legacy_is_kprobe = false;
10808 perf_link->legacy_is_retprobe = retprobe;
10814 remove_uprobe_event_legacy(legacy_probe, retprobe);
10816 free(legacy_probe);
10817 return libbpf_err_ptr(err);
10820 /* Format of u[ret]probe section definition supporting auto-attach:
10821 * u[ret]probe/binary:function[+offset]
10823 * binary can be an absolute/relative path or a filename; the latter is resolved to a
10824 * full binary path via bpf_program__attach_uprobe_opts.
10826 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
10827 * specified (and auto-attach is not possible) or the above format is specified for
10830 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10832 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
10833 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
10834 int n, ret = -EINVAL;
10839 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
10840 &probe_type, &binary_path, &func_name, &offset);
10843 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
10847 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
10848 prog->name, prog->sec_name);
10852 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
10853 strcmp(probe_type, "uretprobe.s") == 0;
10854 if (opts.retprobe && offset != 0) {
10855 pr_warn("prog '%s': uretprobes do not support offset specification\n",
10859 opts.func_name = func_name;
10860 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
10861 ret = libbpf_get_error(*link);
10864 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
10875 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
10876 bool retprobe, pid_t pid,
10877 const char *binary_path,
10878 size_t func_offset)
10880 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10882 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10885 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
10886 pid_t pid, const char *binary_path,
10887 const char *usdt_provider, const char *usdt_name,
10888 const struct bpf_usdt_opts *opts)
10890 char resolved_path[512];
10891 struct bpf_object *obj = prog->obj;
10892 struct bpf_link *link;
10896 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10897 return libbpf_err_ptr(-EINVAL);
10899 if (bpf_program__fd(prog) < 0) {
10900 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10902 return libbpf_err_ptr(-EINVAL);
10906 return libbpf_err_ptr(-EINVAL);
10908 if (!strchr(binary_path, '/')) {
10909 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
10911 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10912 prog->name, binary_path, err);
10913 return libbpf_err_ptr(err);
10915 binary_path = resolved_path;
10918 /* USDT manager is instantiated lazily on first USDT attach. It will
10919 * be destroyed together with BPF object in bpf_object__close().
10921 if (IS_ERR(obj->usdt_man))
10922 return libbpf_ptr(obj->usdt_man);
10923 if (!obj->usdt_man) {
10924 obj->usdt_man = usdt_manager_new(obj);
10925 if (IS_ERR(obj->usdt_man))
10926 return libbpf_ptr(obj->usdt_man);
10929 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
10930 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
10931 usdt_provider, usdt_name, usdt_cookie);
10932 err = libbpf_get_error(link);
10934 return libbpf_err_ptr(err);
10938 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10940 char *path = NULL, *provider = NULL, *name = NULL;
10941 const char *sec_name;
10944 sec_name = bpf_program__section_name(prog);
10945 if (strcmp(sec_name, "usdt") == 0) {
10946 /* no auto-attach for just SEC("usdt") */
10951 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
10953 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
10957 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
10958 provider, name, NULL);
10959 err = libbpf_get_error(*link);
10967 static int determine_tracepoint_id(const char *tp_category,
10968 const char *tp_name)
10970 char file[PATH_MAX];
10973 ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10974 tracefs_path(), tp_category, tp_name);
10977 if (ret >= sizeof(file)) {
10978 pr_debug("tracepoint %s/%s path is too long\n",
10979 tp_category, tp_name);
10982 return parse_uint_from_file(file, "%d\n");
10985 static int perf_event_open_tracepoint(const char *tp_category,
10986 const char *tp_name)
10988 struct perf_event_attr attr = {};
10989 char errmsg[STRERR_BUFSIZE];
10990 int tp_id, pfd, err;
10992 tp_id = determine_tracepoint_id(tp_category, tp_name);
10994 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
10995 tp_category, tp_name,
10996 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11000 attr.type = PERF_TYPE_TRACEPOINT;
11001 attr.size = sizeof(attr);
11002 attr.config = tp_id;
11004 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11005 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11008 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11009 tp_category, tp_name,
11010 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11016 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11017 const char *tp_category,
11018 const char *tp_name,
11019 const struct bpf_tracepoint_opts *opts)
11021 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11022 char errmsg[STRERR_BUFSIZE];
11023 struct bpf_link *link;
11026 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11027 return libbpf_err_ptr(-EINVAL);
11029 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11031 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11033 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11034 prog->name, tp_category, tp_name,
11035 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11036 return libbpf_err_ptr(pfd);
11038 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11039 err = libbpf_get_error(link);
11042 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11043 prog->name, tp_category, tp_name,
11044 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11045 return libbpf_err_ptr(err);
11050 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11051 const char *tp_category,
11052 const char *tp_name)
11054 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11057 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11059 char *sec_name, *tp_cat, *tp_name;
11063 /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11064 if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11067 sec_name = strdup(prog->sec_name);
11071 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11072 if (str_has_pfx(prog->sec_name, "tp/"))
11073 tp_cat = sec_name + sizeof("tp/") - 1;
11075 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11076 tp_name = strchr(tp_cat, '/');
11084 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11086 return libbpf_get_error(*link);
11089 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11090 const char *tp_name)
11092 char errmsg[STRERR_BUFSIZE];
11093 struct bpf_link *link;
11096 prog_fd = bpf_program__fd(prog);
11098 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11099 return libbpf_err_ptr(-EINVAL);
11102 link = calloc(1, sizeof(*link));
11104 return libbpf_err_ptr(-ENOMEM);
11105 link->detach = &bpf_link__detach_fd;
11107 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11111 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11112 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11113 return libbpf_err_ptr(pfd);
11119 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11121 static const char *const prefixes[] = {
11125 "raw_tracepoint.w",
11128 const char *tp_name = NULL;
11132 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11135 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11138 pfx_len = strlen(prefixes[i]);
11139 /* no auto-attach case of, e.g., SEC("raw_tp") */
11140 if (prog->sec_name[pfx_len] == '\0')
11143 if (prog->sec_name[pfx_len] != '/')
11146 tp_name = prog->sec_name + pfx_len + 1;
11151 pr_warn("prog '%s': invalid section name '%s'\n",
11152 prog->name, prog->sec_name);
11156 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11157 return libbpf_get_error(link);
11160 /* Common logic for all BPF program types that attach to a btf_id */
11161 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11162 const struct bpf_trace_opts *opts)
11164 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11165 char errmsg[STRERR_BUFSIZE];
11166 struct bpf_link *link;
11169 if (!OPTS_VALID(opts, bpf_trace_opts))
11170 return libbpf_err_ptr(-EINVAL);
11172 prog_fd = bpf_program__fd(prog);
11174 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11175 return libbpf_err_ptr(-EINVAL);
11178 link = calloc(1, sizeof(*link));
11180 return libbpf_err_ptr(-ENOMEM);
11181 link->detach = &bpf_link__detach_fd;
11183 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11184 link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11185 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11189 pr_warn("prog '%s': failed to attach: %s\n",
11190 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11191 return libbpf_err_ptr(pfd);
11197 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11199 return bpf_program__attach_btf_id(prog, NULL);
11202 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11203 const struct bpf_trace_opts *opts)
11205 return bpf_program__attach_btf_id(prog, opts);
11208 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11210 return bpf_program__attach_btf_id(prog, NULL);
11213 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11215 *link = bpf_program__attach_trace(prog);
11216 return libbpf_get_error(*link);
11219 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11221 *link = bpf_program__attach_lsm(prog);
11222 return libbpf_get_error(*link);
11225 static struct bpf_link *
11226 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11227 const char *target_name)
11229 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11230 .target_btf_id = btf_id);
11231 enum bpf_attach_type attach_type;
11232 char errmsg[STRERR_BUFSIZE];
11233 struct bpf_link *link;
11234 int prog_fd, link_fd;
11236 prog_fd = bpf_program__fd(prog);
11238 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11239 return libbpf_err_ptr(-EINVAL);
11242 link = calloc(1, sizeof(*link));
11244 return libbpf_err_ptr(-ENOMEM);
11245 link->detach = &bpf_link__detach_fd;
11247 attach_type = bpf_program__expected_attach_type(prog);
11248 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11252 pr_warn("prog '%s': failed to attach to %s: %s\n",
11253 prog->name, target_name,
11254 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11255 return libbpf_err_ptr(link_fd);
11257 link->fd = link_fd;
11262 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11264 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11268 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11270 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11273 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11275 /* target_fd/target_ifindex use the same field in LINK_CREATE */
11276 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11279 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11281 const char *attach_func_name)
11285 if (!!target_fd != !!attach_func_name) {
11286 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11288 return libbpf_err_ptr(-EINVAL);
11291 if (prog->type != BPF_PROG_TYPE_EXT) {
11292 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11294 return libbpf_err_ptr(-EINVAL);
11298 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11300 return libbpf_err_ptr(btf_id);
11302 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11304 /* no target, so use raw_tracepoint_open for compatibility
11307 return bpf_program__attach_trace(prog);
11312 bpf_program__attach_iter(const struct bpf_program *prog,
11313 const struct bpf_iter_attach_opts *opts)
11315 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11316 char errmsg[STRERR_BUFSIZE];
11317 struct bpf_link *link;
11318 int prog_fd, link_fd;
11319 __u32 target_fd = 0;
11321 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11322 return libbpf_err_ptr(-EINVAL);
11324 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11325 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11327 prog_fd = bpf_program__fd(prog);
11329 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11330 return libbpf_err_ptr(-EINVAL);
11333 link = calloc(1, sizeof(*link));
11335 return libbpf_err_ptr(-ENOMEM);
11336 link->detach = &bpf_link__detach_fd;
11338 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11339 &link_create_opts);
11343 pr_warn("prog '%s': failed to attach to iterator: %s\n",
11344 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11345 return libbpf_err_ptr(link_fd);
11347 link->fd = link_fd;
11351 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11353 *link = bpf_program__attach_iter(prog, NULL);
11354 return libbpf_get_error(*link);
11357 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11359 struct bpf_link *link = NULL;
11362 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11363 return libbpf_err_ptr(-EOPNOTSUPP);
11365 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11367 return libbpf_err_ptr(err);
11369 /* When calling bpf_program__attach() explicitly, auto-attach support
11370 * is expected to work, so NULL returned link is considered an error.
11371 * This is different for skeleton's attach, see comment in
11372 * bpf_object__attach_skeleton().
11375 return libbpf_err_ptr(-EOPNOTSUPP);
11380 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11384 if (bpf_map_delete_elem(link->fd, &zero))
11390 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11392 struct bpf_struct_ops *st_ops;
11393 struct bpf_link *link;
11397 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11398 return libbpf_err_ptr(-EINVAL);
11400 link = calloc(1, sizeof(*link));
11402 return libbpf_err_ptr(-EINVAL);
11404 st_ops = map->st_ops;
11405 for (i = 0; i < btf_vlen(st_ops->type); i++) {
11406 struct bpf_program *prog = st_ops->progs[i];
11413 prog_fd = bpf_program__fd(prog);
11414 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11415 *(unsigned long *)kern_data = prog_fd;
11418 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11422 return libbpf_err_ptr(err);
11425 link->detach = bpf_link__detach_struct_ops;
11426 link->fd = map->fd;
11431 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11432 void *private_data);
11434 static enum bpf_perf_event_ret
11435 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11436 void **copy_mem, size_t *copy_size,
11437 bpf_perf_event_print_t fn, void *private_data)
11439 struct perf_event_mmap_page *header = mmap_mem;
11440 __u64 data_head = ring_buffer_read_head(header);
11441 __u64 data_tail = header->data_tail;
11442 void *base = ((__u8 *)header) + page_size;
11443 int ret = LIBBPF_PERF_EVENT_CONT;
11444 struct perf_event_header *ehdr;
11447 while (data_head != data_tail) {
11448 ehdr = base + (data_tail & (mmap_size - 1));
11449 ehdr_size = ehdr->size;
11451 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11452 void *copy_start = ehdr;
11453 size_t len_first = base + mmap_size - copy_start;
11454 size_t len_secnd = ehdr_size - len_first;
11456 if (*copy_size < ehdr_size) {
11458 *copy_mem = malloc(ehdr_size);
11461 ret = LIBBPF_PERF_EVENT_ERROR;
11464 *copy_size = ehdr_size;
11467 memcpy(*copy_mem, copy_start, len_first);
11468 memcpy(*copy_mem + len_first, base, len_secnd);
11472 ret = fn(ehdr, private_data);
11473 data_tail += ehdr_size;
11474 if (ret != LIBBPF_PERF_EVENT_CONT)
11478 ring_buffer_write_tail(header, data_tail);
11479 return libbpf_err(ret);
11482 struct perf_buffer;
11484 struct perf_buffer_params {
11485 struct perf_event_attr *attr;
11486 /* if event_cb is specified, it takes precendence */
11487 perf_buffer_event_fn event_cb;
11488 /* sample_cb and lost_cb are higher-level common-case callbacks */
11489 perf_buffer_sample_fn sample_cb;
11490 perf_buffer_lost_fn lost_cb;
11497 struct perf_cpu_buf {
11498 struct perf_buffer *pb;
11499 void *base; /* mmap()'ed memory */
11500 void *buf; /* for reconstructing segmented data */
11507 struct perf_buffer {
11508 perf_buffer_event_fn event_cb;
11509 perf_buffer_sample_fn sample_cb;
11510 perf_buffer_lost_fn lost_cb;
11511 void *ctx; /* passed into callbacks */
11515 struct perf_cpu_buf **cpu_bufs;
11516 struct epoll_event *events;
11517 int cpu_cnt; /* number of allocated CPU buffers */
11518 int epoll_fd; /* perf event FD */
11519 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11522 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11523 struct perf_cpu_buf *cpu_buf)
11527 if (cpu_buf->base &&
11528 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11529 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11530 if (cpu_buf->fd >= 0) {
11531 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11532 close(cpu_buf->fd);
11534 free(cpu_buf->buf);
11538 void perf_buffer__free(struct perf_buffer *pb)
11542 if (IS_ERR_OR_NULL(pb))
11544 if (pb->cpu_bufs) {
11545 for (i = 0; i < pb->cpu_cnt; i++) {
11546 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11551 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11552 perf_buffer__free_cpu_buf(pb, cpu_buf);
11554 free(pb->cpu_bufs);
11556 if (pb->epoll_fd >= 0)
11557 close(pb->epoll_fd);
11562 static struct perf_cpu_buf *
11563 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11564 int cpu, int map_key)
11566 struct perf_cpu_buf *cpu_buf;
11567 char msg[STRERR_BUFSIZE];
11570 cpu_buf = calloc(1, sizeof(*cpu_buf));
11572 return ERR_PTR(-ENOMEM);
11575 cpu_buf->cpu = cpu;
11576 cpu_buf->map_key = map_key;
11578 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11579 -1, PERF_FLAG_FD_CLOEXEC);
11580 if (cpu_buf->fd < 0) {
11582 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11583 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11587 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11588 PROT_READ | PROT_WRITE, MAP_SHARED,
11590 if (cpu_buf->base == MAP_FAILED) {
11591 cpu_buf->base = NULL;
11593 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11594 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11598 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11600 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11601 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11608 perf_buffer__free_cpu_buf(pb, cpu_buf);
11609 return (struct perf_cpu_buf *)ERR_PTR(err);
11612 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11613 struct perf_buffer_params *p);
11615 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11616 perf_buffer_sample_fn sample_cb,
11617 perf_buffer_lost_fn lost_cb,
11619 const struct perf_buffer_opts *opts)
11621 struct perf_buffer_params p = {};
11622 struct perf_event_attr attr = {};
11624 if (!OPTS_VALID(opts, perf_buffer_opts))
11625 return libbpf_err_ptr(-EINVAL);
11627 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11628 attr.type = PERF_TYPE_SOFTWARE;
11629 attr.sample_type = PERF_SAMPLE_RAW;
11630 attr.sample_period = 1;
11631 attr.wakeup_events = 1;
11634 p.sample_cb = sample_cb;
11635 p.lost_cb = lost_cb;
11638 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11641 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11642 struct perf_event_attr *attr,
11643 perf_buffer_event_fn event_cb, void *ctx,
11644 const struct perf_buffer_raw_opts *opts)
11646 struct perf_buffer_params p = {};
11649 return libbpf_err_ptr(-EINVAL);
11651 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11652 return libbpf_err_ptr(-EINVAL);
11655 p.event_cb = event_cb;
11657 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11658 p.cpus = OPTS_GET(opts, cpus, NULL);
11659 p.map_keys = OPTS_GET(opts, map_keys, NULL);
11661 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11664 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11665 struct perf_buffer_params *p)
11667 const char *online_cpus_file = "/sys/devices/system/cpu/online";
11668 struct bpf_map_info map;
11669 char msg[STRERR_BUFSIZE];
11670 struct perf_buffer *pb;
11671 bool *online = NULL;
11672 __u32 map_info_len;
11675 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
11676 pr_warn("page count should be power of two, but is %zu\n",
11678 return ERR_PTR(-EINVAL);
11681 /* best-effort sanity checks */
11682 memset(&map, 0, sizeof(map));
11683 map_info_len = sizeof(map);
11684 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11687 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11688 * -EBADFD, -EFAULT, or -E2BIG on real error
11690 if (err != -EINVAL) {
11691 pr_warn("failed to get map info for map FD %d: %s\n",
11692 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11693 return ERR_PTR(err);
11695 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11698 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11699 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11701 return ERR_PTR(-EINVAL);
11705 pb = calloc(1, sizeof(*pb));
11707 return ERR_PTR(-ENOMEM);
11709 pb->event_cb = p->event_cb;
11710 pb->sample_cb = p->sample_cb;
11711 pb->lost_cb = p->lost_cb;
11714 pb->page_size = getpagesize();
11715 pb->mmap_size = pb->page_size * page_cnt;
11716 pb->map_fd = map_fd;
11718 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11719 if (pb->epoll_fd < 0) {
11721 pr_warn("failed to create epoll instance: %s\n",
11722 libbpf_strerror_r(err, msg, sizeof(msg)));
11726 if (p->cpu_cnt > 0) {
11727 pb->cpu_cnt = p->cpu_cnt;
11729 pb->cpu_cnt = libbpf_num_possible_cpus();
11730 if (pb->cpu_cnt < 0) {
11734 if (map.max_entries && map.max_entries < pb->cpu_cnt)
11735 pb->cpu_cnt = map.max_entries;
11738 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11741 pr_warn("failed to allocate events: out of memory\n");
11744 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11745 if (!pb->cpu_bufs) {
11747 pr_warn("failed to allocate buffers: out of memory\n");
11751 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11753 pr_warn("failed to get online CPU mask: %d\n", err);
11757 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11758 struct perf_cpu_buf *cpu_buf;
11761 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11762 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11764 /* in case user didn't explicitly requested particular CPUs to
11765 * be attached to, skip offline/not present CPUs
11767 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11770 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11771 if (IS_ERR(cpu_buf)) {
11772 err = PTR_ERR(cpu_buf);
11776 pb->cpu_bufs[j] = cpu_buf;
11778 err = bpf_map_update_elem(pb->map_fd, &map_key,
11782 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11783 cpu, map_key, cpu_buf->fd,
11784 libbpf_strerror_r(err, msg, sizeof(msg)));
11788 pb->events[j].events = EPOLLIN;
11789 pb->events[j].data.ptr = cpu_buf;
11790 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11791 &pb->events[j]) < 0) {
11793 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11795 libbpf_strerror_r(err, msg, sizeof(msg)));
11808 perf_buffer__free(pb);
11809 return ERR_PTR(err);
11812 struct perf_sample_raw {
11813 struct perf_event_header header;
11818 struct perf_sample_lost {
11819 struct perf_event_header header;
11822 uint64_t sample_id;
11825 static enum bpf_perf_event_ret
11826 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11828 struct perf_cpu_buf *cpu_buf = ctx;
11829 struct perf_buffer *pb = cpu_buf->pb;
11832 /* user wants full control over parsing perf event */
11834 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11837 case PERF_RECORD_SAMPLE: {
11838 struct perf_sample_raw *s = data;
11841 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11844 case PERF_RECORD_LOST: {
11845 struct perf_sample_lost *s = data;
11848 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11852 pr_warn("unknown perf sample type %d\n", e->type);
11853 return LIBBPF_PERF_EVENT_ERROR;
11855 return LIBBPF_PERF_EVENT_CONT;
11858 static int perf_buffer__process_records(struct perf_buffer *pb,
11859 struct perf_cpu_buf *cpu_buf)
11861 enum bpf_perf_event_ret ret;
11863 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11864 pb->page_size, &cpu_buf->buf,
11865 &cpu_buf->buf_size,
11866 perf_buffer__process_record, cpu_buf);
11867 if (ret != LIBBPF_PERF_EVENT_CONT)
11872 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11874 return pb->epoll_fd;
11877 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11881 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11885 for (i = 0; i < cnt; i++) {
11886 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11888 err = perf_buffer__process_records(pb, cpu_buf);
11890 pr_warn("error while processing records: %d\n", err);
11891 return libbpf_err(err);
11897 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11900 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11902 return pb->cpu_cnt;
11906 * Return perf_event FD of a ring buffer in *buf_idx* slot of
11907 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11908 * select()/poll()/epoll() Linux syscalls.
11910 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11912 struct perf_cpu_buf *cpu_buf;
11914 if (buf_idx >= pb->cpu_cnt)
11915 return libbpf_err(-EINVAL);
11917 cpu_buf = pb->cpu_bufs[buf_idx];
11919 return libbpf_err(-ENOENT);
11921 return cpu_buf->fd;
11924 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
11926 struct perf_cpu_buf *cpu_buf;
11928 if (buf_idx >= pb->cpu_cnt)
11929 return libbpf_err(-EINVAL);
11931 cpu_buf = pb->cpu_bufs[buf_idx];
11933 return libbpf_err(-ENOENT);
11935 *buf = cpu_buf->base;
11936 *buf_size = pb->mmap_size;
11941 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11942 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11943 * consume, do nothing and return success.
11948 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11950 struct perf_cpu_buf *cpu_buf;
11952 if (buf_idx >= pb->cpu_cnt)
11953 return libbpf_err(-EINVAL);
11955 cpu_buf = pb->cpu_bufs[buf_idx];
11957 return libbpf_err(-ENOENT);
11959 return perf_buffer__process_records(pb, cpu_buf);
11962 int perf_buffer__consume(struct perf_buffer *pb)
11966 for (i = 0; i < pb->cpu_cnt; i++) {
11967 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11972 err = perf_buffer__process_records(pb, cpu_buf);
11974 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
11975 return libbpf_err(err);
11981 int bpf_program__set_attach_target(struct bpf_program *prog,
11982 int attach_prog_fd,
11983 const char *attach_func_name)
11985 int btf_obj_fd = 0, btf_id = 0, err;
11987 if (!prog || attach_prog_fd < 0)
11988 return libbpf_err(-EINVAL);
11990 if (prog->obj->loaded)
11991 return libbpf_err(-EINVAL);
11993 if (attach_prog_fd && !attach_func_name) {
11994 /* remember attach_prog_fd and let bpf_program__load() find
11995 * BTF ID during the program load
11997 prog->attach_prog_fd = attach_prog_fd;
12001 if (attach_prog_fd) {
12002 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12005 return libbpf_err(btf_id);
12007 if (!attach_func_name)
12008 return libbpf_err(-EINVAL);
12010 /* load btf_vmlinux, if not yet */
12011 err = bpf_object__load_vmlinux_btf(prog->obj, true);
12013 return libbpf_err(err);
12014 err = find_kernel_btf_id(prog->obj, attach_func_name,
12015 prog->expected_attach_type,
12016 &btf_obj_fd, &btf_id);
12018 return libbpf_err(err);
12021 prog->attach_btf_id = btf_id;
12022 prog->attach_btf_obj_fd = btf_obj_fd;
12023 prog->attach_prog_fd = attach_prog_fd;
12027 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12029 int err = 0, n, len, start, end = -1;
12035 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12037 if (*s == ',' || *s == '\n') {
12041 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12042 if (n <= 0 || n > 2) {
12043 pr_warn("Failed to get CPU range %s: %d\n", s, n);
12046 } else if (n == 1) {
12049 if (start < 0 || start > end) {
12050 pr_warn("Invalid CPU range [%d,%d] in %s\n",
12055 tmp = realloc(*mask, end + 1);
12061 memset(tmp + *mask_sz, 0, start - *mask_sz);
12062 memset(tmp + start, 1, end - start + 1);
12063 *mask_sz = end + 1;
12067 pr_warn("Empty CPU range\n");
12077 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12079 int fd, err = 0, len;
12082 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12085 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12088 len = read(fd, buf, sizeof(buf));
12091 err = len ? -errno : -EINVAL;
12092 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12095 if (len >= sizeof(buf)) {
12096 pr_warn("CPU mask is too big in file %s\n", fcpu);
12101 return parse_cpu_mask_str(buf, mask, mask_sz);
12104 int libbpf_num_possible_cpus(void)
12106 static const char *fcpu = "/sys/devices/system/cpu/possible";
12108 int err, n, i, tmp_cpus;
12111 tmp_cpus = READ_ONCE(cpus);
12115 err = parse_cpu_mask_file(fcpu, &mask, &n);
12117 return libbpf_err(err);
12120 for (i = 0; i < n; i++) {
12126 WRITE_ONCE(cpus, tmp_cpus);
12130 static int populate_skeleton_maps(const struct bpf_object *obj,
12131 struct bpf_map_skeleton *maps,
12136 for (i = 0; i < map_cnt; i++) {
12137 struct bpf_map **map = maps[i].map;
12138 const char *name = maps[i].name;
12139 void **mmaped = maps[i].mmaped;
12141 *map = bpf_object__find_map_by_name(obj, name);
12143 pr_warn("failed to find skeleton map '%s'\n", name);
12147 /* externs shouldn't be pre-setup from user code */
12148 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12149 *mmaped = (*map)->mmaped;
12154 static int populate_skeleton_progs(const struct bpf_object *obj,
12155 struct bpf_prog_skeleton *progs,
12160 for (i = 0; i < prog_cnt; i++) {
12161 struct bpf_program **prog = progs[i].prog;
12162 const char *name = progs[i].name;
12164 *prog = bpf_object__find_program_by_name(obj, name);
12166 pr_warn("failed to find skeleton program '%s'\n", name);
12173 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12174 const struct bpf_object_open_opts *opts)
12176 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12177 .object_name = s->name,
12179 struct bpf_object *obj;
12182 /* Attempt to preserve opts->object_name, unless overriden by user
12183 * explicitly. Overwriting object name for skeletons is discouraged,
12184 * as it breaks global data maps, because they contain object name
12185 * prefix as their own map name prefix. When skeleton is generated,
12186 * bpftool is making an assumption that this name will stay the same.
12189 memcpy(&skel_opts, opts, sizeof(*opts));
12190 if (!opts->object_name)
12191 skel_opts.object_name = s->name;
12194 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12195 err = libbpf_get_error(obj);
12197 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12199 return libbpf_err(err);
12203 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12205 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12206 return libbpf_err(err);
12209 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12211 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12212 return libbpf_err(err);
12218 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12220 int err, len, var_idx, i;
12221 const char *var_name;
12222 const struct bpf_map *map;
12225 const struct btf_type *map_type, *var_type;
12226 const struct bpf_var_skeleton *var_skel;
12227 struct btf_var_secinfo *var;
12230 return libbpf_err(-EINVAL);
12232 btf = bpf_object__btf(s->obj);
12234 pr_warn("subskeletons require BTF at runtime (object %s)\n",
12235 bpf_object__name(s->obj));
12236 return libbpf_err(-errno);
12239 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12241 pr_warn("failed to populate subskeleton maps: %d\n", err);
12242 return libbpf_err(err);
12245 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12247 pr_warn("failed to populate subskeleton maps: %d\n", err);
12248 return libbpf_err(err);
12251 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12252 var_skel = &s->vars[var_idx];
12253 map = *var_skel->map;
12254 map_type_id = bpf_map__btf_value_type_id(map);
12255 map_type = btf__type_by_id(btf, map_type_id);
12257 if (!btf_is_datasec(map_type)) {
12258 pr_warn("type for map '%1$s' is not a datasec: %2$s",
12259 bpf_map__name(map),
12260 __btf_kind_str(btf_kind(map_type)));
12261 return libbpf_err(-EINVAL);
12264 len = btf_vlen(map_type);
12265 var = btf_var_secinfos(map_type);
12266 for (i = 0; i < len; i++, var++) {
12267 var_type = btf__type_by_id(btf, var->type);
12268 var_name = btf__name_by_offset(btf, var_type->name_off);
12269 if (strcmp(var_name, var_skel->name) == 0) {
12270 *var_skel->addr = map->mmaped + var->offset;
12278 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12288 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12292 err = bpf_object__load(*s->obj);
12294 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12295 return libbpf_err(err);
12298 for (i = 0; i < s->map_cnt; i++) {
12299 struct bpf_map *map = *s->maps[i].map;
12300 size_t mmap_sz = bpf_map_mmap_sz(map);
12301 int prot, map_fd = bpf_map__fd(map);
12302 void **mmaped = s->maps[i].mmaped;
12307 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12312 if (map->def.map_flags & BPF_F_RDONLY_PROG)
12315 prot = PROT_READ | PROT_WRITE;
12317 /* Remap anonymous mmap()-ed "map initialization image" as
12318 * a BPF map-backed mmap()-ed memory, but preserving the same
12319 * memory address. This will cause kernel to change process'
12320 * page table to point to a different piece of kernel memory,
12321 * but from userspace point of view memory address (and its
12322 * contents, being identical at this point) will stay the
12323 * same. This mapping will be released by bpf_object__close()
12324 * as per normal clean up procedure, so we don't need to worry
12325 * about it from skeleton's clean up perspective.
12327 *mmaped = mmap(map->mmaped, mmap_sz, prot,
12328 MAP_SHARED | MAP_FIXED, map_fd, 0);
12329 if (*mmaped == MAP_FAILED) {
12332 pr_warn("failed to re-mmap() map '%s': %d\n",
12333 bpf_map__name(map), err);
12334 return libbpf_err(err);
12341 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12345 for (i = 0; i < s->prog_cnt; i++) {
12346 struct bpf_program *prog = *s->progs[i].prog;
12347 struct bpf_link **link = s->progs[i].link;
12349 if (!prog->autoload)
12352 /* auto-attaching not supported for this program */
12353 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12356 /* if user already set the link manually, don't attempt auto-attach */
12360 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12362 pr_warn("prog '%s': failed to auto-attach: %d\n",
12363 bpf_program__name(prog), err);
12364 return libbpf_err(err);
12367 /* It's possible that for some SEC() definitions auto-attach
12368 * is supported in some cases (e.g., if definition completely
12369 * specifies target information), but is not in other cases.
12370 * SEC("uprobe") is one such case. If user specified target
12371 * binary and function name, such BPF program can be
12372 * auto-attached. But if not, it shouldn't trigger skeleton's
12373 * attach to fail. It should just be skipped.
12374 * attach_fn signals such case with returning 0 (no error) and
12375 * setting link to NULL.
12382 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12386 for (i = 0; i < s->prog_cnt; i++) {
12387 struct bpf_link **link = s->progs[i].link;
12389 bpf_link__destroy(*link);
12394 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12400 bpf_object__detach_skeleton(s);
12402 bpf_object__close(*s->obj);