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 <sys/epoll.h>
38 #include <sys/ioctl.h>
41 #include <sys/types.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
52 #include "str_error.h"
53 #include "libbpf_internal.h"
55 #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",
119 [BPF_STRUCT_OPS] = "struct_ops",
122 static const char * const link_type_name[] = {
123 [BPF_LINK_TYPE_UNSPEC] = "unspec",
124 [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
125 [BPF_LINK_TYPE_TRACING] = "tracing",
126 [BPF_LINK_TYPE_CGROUP] = "cgroup",
127 [BPF_LINK_TYPE_ITER] = "iter",
128 [BPF_LINK_TYPE_NETNS] = "netns",
129 [BPF_LINK_TYPE_XDP] = "xdp",
130 [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
131 [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
132 [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
135 static const char * const map_type_name[] = {
136 [BPF_MAP_TYPE_UNSPEC] = "unspec",
137 [BPF_MAP_TYPE_HASH] = "hash",
138 [BPF_MAP_TYPE_ARRAY] = "array",
139 [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
140 [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
141 [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
142 [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
143 [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
144 [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
145 [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
146 [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
147 [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
148 [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
149 [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
150 [BPF_MAP_TYPE_DEVMAP] = "devmap",
151 [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
152 [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
153 [BPF_MAP_TYPE_CPUMAP] = "cpumap",
154 [BPF_MAP_TYPE_XSKMAP] = "xskmap",
155 [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
156 [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
157 [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
158 [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
159 [BPF_MAP_TYPE_QUEUE] = "queue",
160 [BPF_MAP_TYPE_STACK] = "stack",
161 [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
162 [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
163 [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
164 [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
165 [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
166 [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
167 [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
168 [BPF_MAP_TYPE_CGRP_STORAGE] = "cgrp_storage",
171 static const char * const prog_type_name[] = {
172 [BPF_PROG_TYPE_UNSPEC] = "unspec",
173 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
174 [BPF_PROG_TYPE_KPROBE] = "kprobe",
175 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
176 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
177 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
178 [BPF_PROG_TYPE_XDP] = "xdp",
179 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
180 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
181 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
182 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
183 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
184 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
185 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
186 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
187 [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
188 [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
189 [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
190 [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
191 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
192 [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
193 [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
194 [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
195 [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
196 [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
197 [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
198 [BPF_PROG_TYPE_TRACING] = "tracing",
199 [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
200 [BPF_PROG_TYPE_EXT] = "ext",
201 [BPF_PROG_TYPE_LSM] = "lsm",
202 [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
203 [BPF_PROG_TYPE_SYSCALL] = "syscall",
206 static int __base_pr(enum libbpf_print_level level, const char *format,
209 if (level == LIBBPF_DEBUG)
212 return vfprintf(stderr, format, args);
215 static libbpf_print_fn_t __libbpf_pr = __base_pr;
217 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
219 libbpf_print_fn_t old_print_fn = __libbpf_pr;
226 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
236 va_start(args, format);
237 __libbpf_pr(level, format, args);
243 static void pr_perm_msg(int err)
248 if (err != -EPERM || geteuid() != 0)
251 err = getrlimit(RLIMIT_MEMLOCK, &limit);
255 if (limit.rlim_cur == RLIM_INFINITY)
258 if (limit.rlim_cur < 1024)
259 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
260 else if (limit.rlim_cur < 1024*1024)
261 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
263 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
265 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
269 #define STRERR_BUFSIZE 128
271 /* Copied from tools/perf/util/util.h */
273 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
277 # define zclose(fd) ({ \
280 ___err = close((fd)); \
285 static inline __u64 ptr_to_u64(const void *ptr)
287 return (__u64) (unsigned long) ptr;
290 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
292 /* as of v1.0 libbpf_set_strict_mode() is a no-op */
296 __u32 libbpf_major_version(void)
298 return LIBBPF_MAJOR_VERSION;
301 __u32 libbpf_minor_version(void)
303 return LIBBPF_MINOR_VERSION;
306 const char *libbpf_version_string(void)
310 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
326 enum reloc_type type;
329 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
337 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
340 /* expected_attach_type is optional, if kernel doesn't support that */
341 SEC_EXP_ATTACH_OPT = 1,
342 /* legacy, only used by libbpf_get_type_names() and
343 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
344 * This used to be associated with cgroup (and few other) BPF programs
345 * that were attachable through BPF_PROG_ATTACH command. Pretty
346 * meaningless nowadays, though.
349 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
350 /* attachment target is specified through BTF ID in either kernel or
351 * other BPF program's BTF object
354 /* BPF program type allows sleeping/blocking in kernel */
356 /* BPF program support non-linear XDP buffer */
362 enum bpf_prog_type prog_type;
363 enum bpf_attach_type expected_attach_type;
367 libbpf_prog_setup_fn_t prog_setup_fn;
368 libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
369 libbpf_prog_attach_fn_t prog_attach_fn;
373 * bpf_prog should be a better name but it has been used in
380 const struct bpf_sec_def *sec_def;
381 /* this program's instruction offset (in number of instructions)
382 * within its containing ELF section
385 /* number of original instructions in ELF section belonging to this
386 * program, not taking into account subprogram instructions possible
387 * appended later during relocation
390 /* Offset (in number of instructions) of the start of instruction
391 * belonging to this BPF program within its containing main BPF
392 * program. For the entry-point (main) BPF program, this is always
393 * zero. For a sub-program, this gets reset before each of main BPF
394 * programs are processed and relocated and is used to determined
395 * whether sub-program was already appended to the main program, and
396 * if yes, at which instruction offset.
400 /* instructions that belong to BPF program; insns[0] is located at
401 * sec_insn_off instruction within its ELF section in ELF file, so
402 * when mapping ELF file instruction index to the local instruction,
403 * one needs to subtract sec_insn_off; and vice versa.
405 struct bpf_insn *insns;
406 /* actual number of instruction in this BPF program's image; for
407 * entry-point BPF programs this includes the size of main program
408 * itself plus all the used sub-programs, appended at the end
412 struct reloc_desc *reloc_desc;
415 /* BPF verifier log settings */
420 struct bpf_object *obj;
425 bool mark_btf_static;
426 enum bpf_prog_type type;
427 enum bpf_attach_type expected_attach_type;
430 __u32 attach_btf_obj_fd;
432 __u32 attach_prog_fd;
435 __u32 func_info_rec_size;
439 __u32 line_info_rec_size;
444 struct bpf_struct_ops {
446 const struct btf_type *type;
447 struct bpf_program **progs;
448 __u32 *kern_func_off;
449 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
451 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
452 * btf_vmlinux's format.
453 * struct bpf_struct_ops_tcp_congestion_ops {
454 * [... some other kernel fields ...]
455 * struct tcp_congestion_ops data;
457 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
458 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
465 #define DATA_SEC ".data"
466 #define BSS_SEC ".bss"
467 #define RODATA_SEC ".rodata"
468 #define KCONFIG_SEC ".kconfig"
469 #define KSYMS_SEC ".ksyms"
470 #define STRUCT_OPS_SEC ".struct_ops"
471 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
473 enum libbpf_map_type {
483 unsigned int key_size;
484 unsigned int value_size;
485 unsigned int max_entries;
486 unsigned int map_flags;
490 struct bpf_object *obj;
492 /* real_name is defined for special internal maps (.rodata*,
493 * .data*, .bss, .kconfig) and preserves their original ELF section
494 * name. This is important to be able to find corresponding BTF
495 * DATASEC information.
503 struct bpf_map_def def;
506 __u32 btf_key_type_id;
507 __u32 btf_value_type_id;
508 __u32 btf_vmlinux_value_type_id;
509 enum libbpf_map_type libbpf_type;
511 struct bpf_struct_ops *st_ops;
512 struct bpf_map *inner_map;
538 enum extern_type type;
554 unsigned long long addr;
556 /* target btf_id of the corresponding kernel var. */
557 int kernel_btf_obj_fd;
560 /* local btf_id of the ksym extern's type. */
562 /* BTF fd index to be patched in for insn->off, this is
563 * 0 for vmlinux BTF, index in obj->fd_array for module
587 struct elf_sec_desc {
588 enum sec_type sec_type;
600 Elf_Data *st_ops_data;
601 Elf_Data *st_ops_link_data;
602 size_t shstrndx; /* section index for section name strings */
604 struct elf_sec_desc *secs;
607 __u32 btf_maps_sec_btf_id;
611 int st_ops_link_shndx;
617 char name[BPF_OBJ_NAME_LEN];
621 struct bpf_program *programs;
623 struct bpf_map *maps;
628 struct extern_desc *externs;
636 struct bpf_gen *gen_loader;
638 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
639 struct elf_state efile;
642 struct btf_ext *btf_ext;
644 /* Parse and load BTF vmlinux if any of the programs in the object need
647 struct btf *btf_vmlinux;
648 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
649 * override for vmlinux BTF.
651 char *btf_custom_path;
652 /* vmlinux BTF override for CO-RE relocations */
653 struct btf *btf_vmlinux_override;
654 /* Lazily initialized kernel module BTFs */
655 struct module_btf *btf_modules;
656 bool btf_modules_loaded;
657 size_t btf_module_cnt;
658 size_t btf_module_cap;
660 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
669 struct usdt_manager *usdt_man;
674 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
675 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
676 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
677 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
678 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
679 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
680 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
681 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
682 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
684 void bpf_program__unload(struct bpf_program *prog)
691 zfree(&prog->func_info);
692 zfree(&prog->line_info);
695 static void bpf_program__exit(struct bpf_program *prog)
700 bpf_program__unload(prog);
702 zfree(&prog->sec_name);
704 zfree(&prog->reloc_desc);
711 static bool insn_is_subprog_call(const struct bpf_insn *insn)
713 return BPF_CLASS(insn->code) == BPF_JMP &&
714 BPF_OP(insn->code) == BPF_CALL &&
715 BPF_SRC(insn->code) == BPF_K &&
716 insn->src_reg == BPF_PSEUDO_CALL &&
717 insn->dst_reg == 0 &&
721 static bool is_call_insn(const struct bpf_insn *insn)
723 return insn->code == (BPF_JMP | BPF_CALL);
726 static bool insn_is_pseudo_func(struct bpf_insn *insn)
728 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
732 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
733 const char *name, size_t sec_idx, const char *sec_name,
734 size_t sec_off, void *insn_data, size_t insn_data_sz)
736 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
737 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
738 sec_name, name, sec_off, insn_data_sz);
742 memset(prog, 0, sizeof(*prog));
745 prog->sec_idx = sec_idx;
746 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
747 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
748 /* insns_cnt can later be increased by appending used subprograms */
749 prog->insns_cnt = prog->sec_insn_cnt;
751 prog->type = BPF_PROG_TYPE_UNSPEC;
754 /* libbpf's convention for SEC("?abc...") is that it's just like
755 * SEC("abc...") but the corresponding bpf_program starts out with
756 * autoload set to false.
758 if (sec_name[0] == '?') {
759 prog->autoload = false;
760 /* from now on forget there was ? in section name */
763 prog->autoload = true;
766 prog->autoattach = true;
768 /* inherit object's log_level */
769 prog->log_level = obj->log_level;
771 prog->sec_name = strdup(sec_name);
775 prog->name = strdup(name);
779 prog->insns = malloc(insn_data_sz);
782 memcpy(prog->insns, insn_data, insn_data_sz);
786 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
787 bpf_program__exit(prog);
792 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
793 const char *sec_name, int sec_idx)
795 Elf_Data *symbols = obj->efile.symbols;
796 struct bpf_program *prog, *progs;
797 void *data = sec_data->d_buf;
798 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
799 int nr_progs, err, i;
803 progs = obj->programs;
804 nr_progs = obj->nr_programs;
805 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
807 for (i = 0; i < nr_syms; i++) {
808 sym = elf_sym_by_idx(obj, i);
810 if (sym->st_shndx != sec_idx)
812 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
815 prog_sz = sym->st_size;
816 sec_off = sym->st_value;
818 name = elf_sym_str(obj, sym->st_name);
820 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
822 return -LIBBPF_ERRNO__FORMAT;
825 if (sec_off + prog_sz > sec_sz) {
826 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
828 return -LIBBPF_ERRNO__FORMAT;
831 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
832 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
836 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
837 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
839 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
842 * In this case the original obj->programs
843 * is still valid, so don't need special treat for
844 * bpf_close_object().
846 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
850 obj->programs = progs;
852 prog = &progs[nr_progs];
854 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
855 sec_off, data + sec_off, prog_sz);
859 /* if function is a global/weak symbol, but has restricted
860 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
861 * as static to enable more permissive BPF verification mode
862 * with more outside context available to BPF verifier
864 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
865 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
866 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
867 prog->mark_btf_static = true;
870 obj->nr_programs = nr_progs;
876 static const struct btf_member *
877 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
879 struct btf_member *m;
882 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
883 if (btf_member_bit_offset(t, i) == bit_offset)
890 static const struct btf_member *
891 find_member_by_name(const struct btf *btf, const struct btf_type *t,
894 struct btf_member *m;
897 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
898 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
905 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
906 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
907 const char *name, __u32 kind);
910 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
911 const struct btf_type **type, __u32 *type_id,
912 const struct btf_type **vtype, __u32 *vtype_id,
913 const struct btf_member **data_member)
915 const struct btf_type *kern_type, *kern_vtype;
916 const struct btf_member *kern_data_member;
917 __s32 kern_vtype_id, kern_type_id;
920 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
921 if (kern_type_id < 0) {
922 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
926 kern_type = btf__type_by_id(btf, kern_type_id);
928 /* Find the corresponding "map_value" type that will be used
929 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
930 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
933 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
934 tname, BTF_KIND_STRUCT);
935 if (kern_vtype_id < 0) {
936 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
937 STRUCT_OPS_VALUE_PREFIX, tname);
938 return kern_vtype_id;
940 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
942 /* Find "struct tcp_congestion_ops" from
943 * struct bpf_struct_ops_tcp_congestion_ops {
945 * struct tcp_congestion_ops data;
948 kern_data_member = btf_members(kern_vtype);
949 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
950 if (kern_data_member->type == kern_type_id)
953 if (i == btf_vlen(kern_vtype)) {
954 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
955 tname, STRUCT_OPS_VALUE_PREFIX, tname);
960 *type_id = kern_type_id;
962 *vtype_id = kern_vtype_id;
963 *data_member = kern_data_member;
968 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
970 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
973 /* Init the map's fields that depend on kern_btf */
974 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
975 const struct btf *btf,
976 const struct btf *kern_btf)
978 const struct btf_member *member, *kern_member, *kern_data_member;
979 const struct btf_type *type, *kern_type, *kern_vtype;
980 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
981 struct bpf_struct_ops *st_ops;
982 void *data, *kern_data;
986 st_ops = map->st_ops;
988 tname = st_ops->tname;
989 err = find_struct_ops_kern_types(kern_btf, tname,
990 &kern_type, &kern_type_id,
991 &kern_vtype, &kern_vtype_id,
996 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
997 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
999 map->def.value_size = kern_vtype->size;
1000 map->btf_vmlinux_value_type_id = kern_vtype_id;
1002 st_ops->kern_vdata = calloc(1, kern_vtype->size);
1003 if (!st_ops->kern_vdata)
1006 data = st_ops->data;
1007 kern_data_off = kern_data_member->offset / 8;
1008 kern_data = st_ops->kern_vdata + kern_data_off;
1010 member = btf_members(type);
1011 for (i = 0; i < btf_vlen(type); i++, member++) {
1012 const struct btf_type *mtype, *kern_mtype;
1013 __u32 mtype_id, kern_mtype_id;
1014 void *mdata, *kern_mdata;
1015 __s64 msize, kern_msize;
1016 __u32 moff, kern_moff;
1017 __u32 kern_member_idx;
1020 mname = btf__name_by_offset(btf, member->name_off);
1021 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1023 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1028 kern_member_idx = kern_member - btf_members(kern_type);
1029 if (btf_member_bitfield_size(type, i) ||
1030 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1031 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1036 moff = member->offset / 8;
1037 kern_moff = kern_member->offset / 8;
1039 mdata = data + moff;
1040 kern_mdata = kern_data + kern_moff;
1042 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1043 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1045 if (BTF_INFO_KIND(mtype->info) !=
1046 BTF_INFO_KIND(kern_mtype->info)) {
1047 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1048 map->name, mname, BTF_INFO_KIND(mtype->info),
1049 BTF_INFO_KIND(kern_mtype->info));
1053 if (btf_is_ptr(mtype)) {
1054 struct bpf_program *prog;
1056 prog = st_ops->progs[i];
1060 kern_mtype = skip_mods_and_typedefs(kern_btf,
1064 /* mtype->type must be a func_proto which was
1065 * guaranteed in bpf_object__collect_st_ops_relos(),
1066 * so only check kern_mtype for func_proto here.
1068 if (!btf_is_func_proto(kern_mtype)) {
1069 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1074 prog->attach_btf_id = kern_type_id;
1075 prog->expected_attach_type = kern_member_idx;
1077 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1079 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1080 map->name, mname, prog->name, moff,
1086 msize = btf__resolve_size(btf, mtype_id);
1087 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1088 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1089 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1090 map->name, mname, (ssize_t)msize,
1091 (ssize_t)kern_msize);
1095 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1096 map->name, mname, (unsigned int)msize,
1098 memcpy(kern_mdata, mdata, msize);
1104 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1106 struct bpf_map *map;
1110 for (i = 0; i < obj->nr_maps; i++) {
1111 map = &obj->maps[i];
1113 if (!bpf_map__is_struct_ops(map))
1116 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1125 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1126 int shndx, Elf_Data *data, __u32 map_flags)
1128 const struct btf_type *type, *datasec;
1129 const struct btf_var_secinfo *vsi;
1130 struct bpf_struct_ops *st_ops;
1131 const char *tname, *var_name;
1132 __s32 type_id, datasec_id;
1133 const struct btf *btf;
1134 struct bpf_map *map;
1141 datasec_id = btf__find_by_name_kind(btf, sec_name,
1143 if (datasec_id < 0) {
1144 pr_warn("struct_ops init: DATASEC %s not found\n",
1149 datasec = btf__type_by_id(btf, datasec_id);
1150 vsi = btf_var_secinfos(datasec);
1151 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1152 type = btf__type_by_id(obj->btf, vsi->type);
1153 var_name = btf__name_by_offset(obj->btf, type->name_off);
1155 type_id = btf__resolve_type(obj->btf, vsi->type);
1157 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1158 vsi->type, sec_name);
1162 type = btf__type_by_id(obj->btf, type_id);
1163 tname = btf__name_by_offset(obj->btf, type->name_off);
1165 pr_warn("struct_ops init: anonymous type is not supported\n");
1168 if (!btf_is_struct(type)) {
1169 pr_warn("struct_ops init: %s is not a struct\n", tname);
1173 map = bpf_object__add_map(obj);
1175 return PTR_ERR(map);
1177 map->sec_idx = shndx;
1178 map->sec_offset = vsi->offset;
1179 map->name = strdup(var_name);
1183 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1184 map->def.key_size = sizeof(int);
1185 map->def.value_size = type->size;
1186 map->def.max_entries = 1;
1187 map->def.map_flags = map_flags;
1189 map->st_ops = calloc(1, sizeof(*map->st_ops));
1192 st_ops = map->st_ops;
1193 st_ops->data = malloc(type->size);
1194 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1195 st_ops->kern_func_off = malloc(btf_vlen(type) *
1196 sizeof(*st_ops->kern_func_off));
1197 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1200 if (vsi->offset + type->size > data->d_size) {
1201 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1202 var_name, sec_name);
1206 memcpy(st_ops->data,
1207 data->d_buf + vsi->offset,
1209 st_ops->tname = tname;
1210 st_ops->type = type;
1211 st_ops->type_id = type_id;
1213 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1214 tname, type_id, var_name, vsi->offset);
1220 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1224 err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1225 obj->efile.st_ops_data, 0);
1226 err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1227 obj->efile.st_ops_link_shndx,
1228 obj->efile.st_ops_link_data,
1233 static struct bpf_object *bpf_object__new(const char *path,
1234 const void *obj_buf,
1236 const char *obj_name)
1238 struct bpf_object *obj;
1241 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1243 pr_warn("alloc memory failed for %s\n", path);
1244 return ERR_PTR(-ENOMEM);
1247 strcpy(obj->path, path);
1249 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1251 /* Using basename() GNU version which doesn't modify arg. */
1252 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1253 end = strchr(obj->name, '.');
1260 * Caller of this function should also call
1261 * bpf_object__elf_finish() after data collection to return
1262 * obj_buf to user. If not, we should duplicate the buffer to
1263 * avoid user freeing them before elf finish.
1265 obj->efile.obj_buf = obj_buf;
1266 obj->efile.obj_buf_sz = obj_buf_sz;
1267 obj->efile.btf_maps_shndx = -1;
1268 obj->efile.st_ops_shndx = -1;
1269 obj->efile.st_ops_link_shndx = -1;
1270 obj->kconfig_map_idx = -1;
1272 obj->kern_version = get_kernel_version();
1273 obj->loaded = false;
1278 static void bpf_object__elf_finish(struct bpf_object *obj)
1280 if (!obj->efile.elf)
1283 elf_end(obj->efile.elf);
1284 obj->efile.elf = NULL;
1285 obj->efile.symbols = NULL;
1286 obj->efile.st_ops_data = NULL;
1287 obj->efile.st_ops_link_data = NULL;
1289 zfree(&obj->efile.secs);
1290 obj->efile.sec_cnt = 0;
1291 zclose(obj->efile.fd);
1292 obj->efile.obj_buf = NULL;
1293 obj->efile.obj_buf_sz = 0;
1296 static int bpf_object__elf_init(struct bpf_object *obj)
1302 if (obj->efile.elf) {
1303 pr_warn("elf: init internal error\n");
1304 return -LIBBPF_ERRNO__LIBELF;
1307 if (obj->efile.obj_buf_sz > 0) {
1308 /* obj_buf should have been validated by bpf_object__open_mem(). */
1309 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1311 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1312 if (obj->efile.fd < 0) {
1313 char errmsg[STRERR_BUFSIZE], *cp;
1316 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1317 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1321 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1325 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1326 err = -LIBBPF_ERRNO__LIBELF;
1330 obj->efile.elf = elf;
1332 if (elf_kind(elf) != ELF_K_ELF) {
1333 err = -LIBBPF_ERRNO__FORMAT;
1334 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1338 if (gelf_getclass(elf) != ELFCLASS64) {
1339 err = -LIBBPF_ERRNO__FORMAT;
1340 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1344 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1345 if (!obj->efile.ehdr) {
1346 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1347 err = -LIBBPF_ERRNO__FORMAT;
1351 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1352 pr_warn("elf: failed to get section names section index for %s: %s\n",
1353 obj->path, elf_errmsg(-1));
1354 err = -LIBBPF_ERRNO__FORMAT;
1358 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1359 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1360 pr_warn("elf: failed to get section names strings from %s: %s\n",
1361 obj->path, elf_errmsg(-1));
1362 err = -LIBBPF_ERRNO__FORMAT;
1366 /* Old LLVM set e_machine to EM_NONE */
1367 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1368 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1369 err = -LIBBPF_ERRNO__FORMAT;
1375 bpf_object__elf_finish(obj);
1379 static int bpf_object__check_endianness(struct bpf_object *obj)
1381 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1382 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1384 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1385 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1388 # error "Unrecognized __BYTE_ORDER__"
1390 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1391 return -LIBBPF_ERRNO__ENDIAN;
1395 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1398 pr_warn("invalid license section in %s\n", obj->path);
1399 return -LIBBPF_ERRNO__FORMAT;
1401 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1402 * go over allowed ELF data section buffer
1404 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1405 pr_debug("license of %s is %s\n", obj->path, obj->license);
1410 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1414 if (!data || size != sizeof(kver)) {
1415 pr_warn("invalid kver section in %s\n", obj->path);
1416 return -LIBBPF_ERRNO__FORMAT;
1418 memcpy(&kver, data, sizeof(kver));
1419 obj->kern_version = kver;
1420 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1424 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1426 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1427 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1432 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1440 scn = elf_sec_by_name(obj, name);
1441 data = elf_sec_data(obj, scn);
1443 *size = data->d_size;
1444 return 0; /* found it */
1450 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1452 Elf_Data *symbols = obj->efile.symbols;
1456 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1457 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1459 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1462 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1463 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1466 sname = elf_sym_str(obj, sym->st_name);
1468 pr_warn("failed to get sym name string for var %s\n", name);
1469 return ERR_PTR(-EIO);
1471 if (strcmp(name, sname) == 0)
1475 return ERR_PTR(-ENOENT);
1478 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1480 struct bpf_map *map;
1483 err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1484 sizeof(*obj->maps), obj->nr_maps + 1);
1486 return ERR_PTR(err);
1488 map = &obj->maps[obj->nr_maps++];
1491 map->inner_map_fd = -1;
1492 map->autocreate = true;
1497 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1499 long page_sz = sysconf(_SC_PAGE_SIZE);
1502 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1503 map_sz = roundup(map_sz, page_sz);
1507 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1509 char map_name[BPF_OBJ_NAME_LEN], *p;
1510 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1512 /* This is one of the more confusing parts of libbpf for various
1513 * reasons, some of which are historical. The original idea for naming
1514 * internal names was to include as much of BPF object name prefix as
1515 * possible, so that it can be distinguished from similar internal
1516 * maps of a different BPF object.
1517 * As an example, let's say we have bpf_object named 'my_object_name'
1518 * and internal map corresponding to '.rodata' ELF section. The final
1519 * map name advertised to user and to the kernel will be
1520 * 'my_objec.rodata', taking first 8 characters of object name and
1521 * entire 7 characters of '.rodata'.
1522 * Somewhat confusingly, if internal map ELF section name is shorter
1523 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1524 * for the suffix, even though we only have 4 actual characters, and
1525 * resulting map will be called 'my_objec.bss', not even using all 15
1526 * characters allowed by the kernel. Oh well, at least the truncated
1527 * object name is somewhat consistent in this case. But if the map
1528 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1529 * (8 chars) and thus will be left with only first 7 characters of the
1530 * object name ('my_obje'). Happy guessing, user, that the final map
1531 * name will be "my_obje.kconfig".
1532 * Now, with libbpf starting to support arbitrarily named .rodata.*
1533 * and .data.* data sections, it's possible that ELF section name is
1534 * longer than allowed 15 chars, so we now need to be careful to take
1535 * only up to 15 first characters of ELF name, taking no BPF object
1536 * name characters at all. So '.rodata.abracadabra' will result in
1537 * '.rodata.abracad' kernel and user-visible name.
1538 * We need to keep this convoluted logic intact for .data, .bss and
1539 * .rodata maps, but for new custom .data.custom and .rodata.custom
1540 * maps we use their ELF names as is, not prepending bpf_object name
1541 * in front. We still need to truncate them to 15 characters for the
1542 * kernel. Full name can be recovered for such maps by using DATASEC
1543 * BTF type associated with such map's value type, though.
1545 if (sfx_len >= BPF_OBJ_NAME_LEN)
1546 sfx_len = BPF_OBJ_NAME_LEN - 1;
1548 /* if there are two or more dots in map name, it's a custom dot map */
1549 if (strchr(real_name + 1, '.') != NULL)
1552 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1554 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1555 sfx_len, real_name);
1557 /* sanitise map name to characters allowed by kernel */
1558 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1559 if (!isalnum(*p) && *p != '_' && *p != '.')
1562 return strdup(map_name);
1566 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1568 /* Internal BPF map is mmap()'able only if at least one of corresponding
1569 * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1570 * variable and it's not marked as __hidden (which turns it into, effectively,
1571 * a STATIC variable).
1573 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1575 const struct btf_type *t, *vt;
1576 struct btf_var_secinfo *vsi;
1579 if (!map->btf_value_type_id)
1582 t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1583 if (!btf_is_datasec(t))
1586 vsi = btf_var_secinfos(t);
1587 for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1588 vt = btf__type_by_id(obj->btf, vsi->type);
1589 if (!btf_is_var(vt))
1592 if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1600 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1601 const char *real_name, int sec_idx, void *data, size_t data_sz)
1603 struct bpf_map_def *def;
1604 struct bpf_map *map;
1607 map = bpf_object__add_map(obj);
1609 return PTR_ERR(map);
1611 map->libbpf_type = type;
1612 map->sec_idx = sec_idx;
1613 map->sec_offset = 0;
1614 map->real_name = strdup(real_name);
1615 map->name = internal_map_name(obj, real_name);
1616 if (!map->real_name || !map->name) {
1617 zfree(&map->real_name);
1623 def->type = BPF_MAP_TYPE_ARRAY;
1624 def->key_size = sizeof(int);
1625 def->value_size = data_sz;
1626 def->max_entries = 1;
1627 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1628 ? BPF_F_RDONLY_PROG : 0;
1630 /* failures are fine because of maps like .rodata.str1.1 */
1631 (void) map_fill_btf_type_info(obj, map);
1633 if (map_is_mmapable(obj, map))
1634 def->map_flags |= BPF_F_MMAPABLE;
1636 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1637 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1639 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1640 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1641 if (map->mmaped == MAP_FAILED) {
1644 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1646 zfree(&map->real_name);
1652 memcpy(map->mmaped, data, data_sz);
1654 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1658 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1660 struct elf_sec_desc *sec_desc;
1661 const char *sec_name;
1662 int err = 0, sec_idx;
1665 * Populate obj->maps with libbpf internal maps.
1667 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1668 sec_desc = &obj->efile.secs[sec_idx];
1670 /* Skip recognized sections with size 0. */
1671 if (!sec_desc->data || sec_desc->data->d_size == 0)
1674 switch (sec_desc->sec_type) {
1676 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1677 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1679 sec_desc->data->d_buf,
1680 sec_desc->data->d_size);
1683 obj->has_rodata = true;
1684 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1685 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1687 sec_desc->data->d_buf,
1688 sec_desc->data->d_size);
1691 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1692 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1695 sec_desc->data->d_size);
1708 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1713 for (i = 0; i < obj->nr_extern; i++) {
1714 if (strcmp(obj->externs[i].name, name) == 0)
1715 return &obj->externs[i];
1720 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1723 switch (ext->kcfg.type) {
1726 pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1730 *(bool *)ext_val = value == 'y' ? true : false;
1734 *(enum libbpf_tristate *)ext_val = TRI_YES;
1735 else if (value == 'm')
1736 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1737 else /* value == 'n' */
1738 *(enum libbpf_tristate *)ext_val = TRI_NO;
1741 *(char *)ext_val = value;
1747 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1755 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1760 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1761 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1766 len = strlen(value);
1767 if (value[len - 1] != '"') {
1768 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1775 if (len >= ext->kcfg.sz) {
1776 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1777 ext->name, value, len, ext->kcfg.sz - 1);
1778 len = ext->kcfg.sz - 1;
1780 memcpy(ext_val, value + 1, len);
1781 ext_val[len] = '\0';
1786 static int parse_u64(const char *value, __u64 *res)
1792 *res = strtoull(value, &value_end, 0);
1795 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1799 pr_warn("failed to parse '%s' as integer completely\n", value);
1805 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1807 int bit_sz = ext->kcfg.sz * 8;
1809 if (ext->kcfg.sz == 8)
1812 /* Validate that value stored in u64 fits in integer of `ext->sz`
1813 * bytes size without any loss of information. If the target integer
1814 * is signed, we rely on the following limits of integer type of
1815 * Y bits and subsequent transformation:
1817 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1818 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1819 * 0 <= X + 2^(Y-1) < 2^Y
1821 * For unsigned target integer, check that all the (64 - Y) bits are
1824 if (ext->kcfg.is_signed)
1825 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1827 return (v >> bit_sz) == 0;
1830 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1833 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1834 ext->kcfg.type != KCFG_BOOL) {
1835 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1836 ext->name, (unsigned long long)value);
1839 if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1840 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1841 ext->name, (unsigned long long)value);
1845 if (!is_kcfg_value_in_range(ext, value)) {
1846 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1847 ext->name, (unsigned long long)value, ext->kcfg.sz);
1850 switch (ext->kcfg.sz) {
1852 *(__u8 *)ext_val = value;
1855 *(__u16 *)ext_val = value;
1858 *(__u32 *)ext_val = value;
1861 *(__u64 *)ext_val = value;
1870 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1871 char *buf, void *data)
1873 struct extern_desc *ext;
1879 if (!str_has_pfx(buf, "CONFIG_"))
1882 sep = strchr(buf, '=');
1884 pr_warn("failed to parse '%s': no separator\n", buf);
1888 /* Trim ending '\n' */
1890 if (buf[len - 1] == '\n')
1891 buf[len - 1] = '\0';
1892 /* Split on '=' and ensure that a value is present. */
1896 pr_warn("failed to parse '%s': no value\n", buf);
1900 ext = find_extern_by_name(obj, buf);
1901 if (!ext || ext->is_set)
1904 ext_val = data + ext->kcfg.data_off;
1908 case 'y': case 'n': case 'm':
1909 err = set_kcfg_value_tri(ext, ext_val, *value);
1912 err = set_kcfg_value_str(ext, ext_val, value);
1915 /* assume integer */
1916 err = parse_u64(value, &num);
1918 pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1921 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1922 pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1925 err = set_kcfg_value_num(ext, ext_val, num);
1930 pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1934 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1942 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1945 else if (len >= PATH_MAX)
1946 return -ENAMETOOLONG;
1948 /* gzopen also accepts uncompressed files. */
1949 file = gzopen(buf, "r");
1951 file = gzopen("/proc/config.gz", "r");
1954 pr_warn("failed to open system Kconfig\n");
1958 while (gzgets(file, buf, sizeof(buf))) {
1959 err = bpf_object__process_kconfig_line(obj, buf, data);
1961 pr_warn("error parsing system Kconfig line '%s': %d\n",
1972 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1973 const char *config, void *data)
1979 file = fmemopen((void *)config, strlen(config), "r");
1982 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1986 while (fgets(buf, sizeof(buf), file)) {
1987 err = bpf_object__process_kconfig_line(obj, buf, data);
1989 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1999 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2001 struct extern_desc *last_ext = NULL, *ext;
2005 for (i = 0; i < obj->nr_extern; i++) {
2006 ext = &obj->externs[i];
2007 if (ext->type == EXT_KCFG)
2014 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2015 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2016 ".kconfig", obj->efile.symbols_shndx,
2021 obj->kconfig_map_idx = obj->nr_maps - 1;
2026 const struct btf_type *
2027 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2029 const struct btf_type *t = btf__type_by_id(btf, id);
2034 while (btf_is_mod(t) || btf_is_typedef(t)) {
2037 t = btf__type_by_id(btf, t->type);
2043 static const struct btf_type *
2044 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2046 const struct btf_type *t;
2048 t = skip_mods_and_typedefs(btf, id, NULL);
2052 t = skip_mods_and_typedefs(btf, t->type, res_id);
2054 return btf_is_func_proto(t) ? t : NULL;
2057 static const char *__btf_kind_str(__u16 kind)
2060 case BTF_KIND_UNKN: return "void";
2061 case BTF_KIND_INT: return "int";
2062 case BTF_KIND_PTR: return "ptr";
2063 case BTF_KIND_ARRAY: return "array";
2064 case BTF_KIND_STRUCT: return "struct";
2065 case BTF_KIND_UNION: return "union";
2066 case BTF_KIND_ENUM: return "enum";
2067 case BTF_KIND_FWD: return "fwd";
2068 case BTF_KIND_TYPEDEF: return "typedef";
2069 case BTF_KIND_VOLATILE: return "volatile";
2070 case BTF_KIND_CONST: return "const";
2071 case BTF_KIND_RESTRICT: return "restrict";
2072 case BTF_KIND_FUNC: return "func";
2073 case BTF_KIND_FUNC_PROTO: return "func_proto";
2074 case BTF_KIND_VAR: return "var";
2075 case BTF_KIND_DATASEC: return "datasec";
2076 case BTF_KIND_FLOAT: return "float";
2077 case BTF_KIND_DECL_TAG: return "decl_tag";
2078 case BTF_KIND_TYPE_TAG: return "type_tag";
2079 case BTF_KIND_ENUM64: return "enum64";
2080 default: return "unknown";
2084 const char *btf_kind_str(const struct btf_type *t)
2086 return __btf_kind_str(btf_kind(t));
2090 * Fetch integer attribute of BTF map definition. Such attributes are
2091 * represented using a pointer to an array, in which dimensionality of array
2092 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2093 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2094 * type definition, while using only sizeof(void *) space in ELF data section.
2096 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2097 const struct btf_member *m, __u32 *res)
2099 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2100 const char *name = btf__name_by_offset(btf, m->name_off);
2101 const struct btf_array *arr_info;
2102 const struct btf_type *arr_t;
2104 if (!btf_is_ptr(t)) {
2105 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2106 map_name, name, btf_kind_str(t));
2110 arr_t = btf__type_by_id(btf, t->type);
2112 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2113 map_name, name, t->type);
2116 if (!btf_is_array(arr_t)) {
2117 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2118 map_name, name, btf_kind_str(arr_t));
2121 arr_info = btf_array(arr_t);
2122 *res = arr_info->nelems;
2126 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2130 len = snprintf(buf, buf_sz, "%s/%s", path, name);
2134 return -ENAMETOOLONG;
2139 static int build_map_pin_path(struct bpf_map *map, const char *path)
2145 path = "/sys/fs/bpf";
2147 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2151 return bpf_map__set_pin_path(map, buf);
2154 /* should match definition in bpf_helpers.h */
2155 enum libbpf_pin_type {
2157 /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2161 int parse_btf_map_def(const char *map_name, struct btf *btf,
2162 const struct btf_type *def_t, bool strict,
2163 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2165 const struct btf_type *t;
2166 const struct btf_member *m;
2167 bool is_inner = inner_def == NULL;
2170 vlen = btf_vlen(def_t);
2171 m = btf_members(def_t);
2172 for (i = 0; i < vlen; i++, m++) {
2173 const char *name = btf__name_by_offset(btf, m->name_off);
2176 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2179 if (strcmp(name, "type") == 0) {
2180 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2182 map_def->parts |= MAP_DEF_MAP_TYPE;
2183 } else if (strcmp(name, "max_entries") == 0) {
2184 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2186 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2187 } else if (strcmp(name, "map_flags") == 0) {
2188 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2190 map_def->parts |= MAP_DEF_MAP_FLAGS;
2191 } else if (strcmp(name, "numa_node") == 0) {
2192 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2194 map_def->parts |= MAP_DEF_NUMA_NODE;
2195 } else if (strcmp(name, "key_size") == 0) {
2198 if (!get_map_field_int(map_name, btf, m, &sz))
2200 if (map_def->key_size && map_def->key_size != sz) {
2201 pr_warn("map '%s': conflicting key size %u != %u.\n",
2202 map_name, map_def->key_size, sz);
2205 map_def->key_size = sz;
2206 map_def->parts |= MAP_DEF_KEY_SIZE;
2207 } else if (strcmp(name, "key") == 0) {
2210 t = btf__type_by_id(btf, m->type);
2212 pr_warn("map '%s': key type [%d] not found.\n",
2216 if (!btf_is_ptr(t)) {
2217 pr_warn("map '%s': key spec is not PTR: %s.\n",
2218 map_name, btf_kind_str(t));
2221 sz = btf__resolve_size(btf, t->type);
2223 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2224 map_name, t->type, (ssize_t)sz);
2227 if (map_def->key_size && map_def->key_size != sz) {
2228 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2229 map_name, map_def->key_size, (ssize_t)sz);
2232 map_def->key_size = sz;
2233 map_def->key_type_id = t->type;
2234 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2235 } else if (strcmp(name, "value_size") == 0) {
2238 if (!get_map_field_int(map_name, btf, m, &sz))
2240 if (map_def->value_size && map_def->value_size != sz) {
2241 pr_warn("map '%s': conflicting value size %u != %u.\n",
2242 map_name, map_def->value_size, sz);
2245 map_def->value_size = sz;
2246 map_def->parts |= MAP_DEF_VALUE_SIZE;
2247 } else if (strcmp(name, "value") == 0) {
2250 t = btf__type_by_id(btf, m->type);
2252 pr_warn("map '%s': value type [%d] not found.\n",
2256 if (!btf_is_ptr(t)) {
2257 pr_warn("map '%s': value spec is not PTR: %s.\n",
2258 map_name, btf_kind_str(t));
2261 sz = btf__resolve_size(btf, t->type);
2263 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2264 map_name, t->type, (ssize_t)sz);
2267 if (map_def->value_size && map_def->value_size != sz) {
2268 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2269 map_name, map_def->value_size, (ssize_t)sz);
2272 map_def->value_size = sz;
2273 map_def->value_type_id = t->type;
2274 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2276 else if (strcmp(name, "values") == 0) {
2277 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2278 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2279 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2280 char inner_map_name[128];
2284 pr_warn("map '%s': multi-level inner maps not supported.\n",
2288 if (i != vlen - 1) {
2289 pr_warn("map '%s': '%s' member should be last.\n",
2293 if (!is_map_in_map && !is_prog_array) {
2294 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2298 if (map_def->value_size && map_def->value_size != 4) {
2299 pr_warn("map '%s': conflicting value size %u != 4.\n",
2300 map_name, map_def->value_size);
2303 map_def->value_size = 4;
2304 t = btf__type_by_id(btf, m->type);
2306 pr_warn("map '%s': %s type [%d] not found.\n",
2307 map_name, desc, m->type);
2310 if (!btf_is_array(t) || btf_array(t)->nelems) {
2311 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2315 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2316 if (!btf_is_ptr(t)) {
2317 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2318 map_name, desc, btf_kind_str(t));
2321 t = skip_mods_and_typedefs(btf, t->type, NULL);
2322 if (is_prog_array) {
2323 if (!btf_is_func_proto(t)) {
2324 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2325 map_name, btf_kind_str(t));
2330 if (!btf_is_struct(t)) {
2331 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2332 map_name, btf_kind_str(t));
2336 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2337 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2341 map_def->parts |= MAP_DEF_INNER_MAP;
2342 } else if (strcmp(name, "pinning") == 0) {
2346 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2349 if (!get_map_field_int(map_name, btf, m, &val))
2351 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2352 pr_warn("map '%s': invalid pinning value %u.\n",
2356 map_def->pinning = val;
2357 map_def->parts |= MAP_DEF_PINNING;
2358 } else if (strcmp(name, "map_extra") == 0) {
2361 if (!get_map_field_int(map_name, btf, m, &map_extra))
2363 map_def->map_extra = map_extra;
2364 map_def->parts |= MAP_DEF_MAP_EXTRA;
2367 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2370 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2374 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2375 pr_warn("map '%s': map type isn't specified.\n", map_name);
2382 static size_t adjust_ringbuf_sz(size_t sz)
2384 __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2387 /* if user forgot to set any size, make sure they see error */
2390 /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2391 * a power-of-2 multiple of kernel's page size. If user diligently
2392 * satisified these conditions, pass the size through.
2394 if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2397 /* Otherwise find closest (page_sz * power_of_2) product bigger than
2398 * user-set size to satisfy both user size request and kernel
2399 * requirements and substitute correct max_entries for map creation.
2401 for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2402 if (mul * page_sz > sz)
2403 return mul * page_sz;
2406 /* if it's impossible to satisfy the conditions (i.e., user size is
2407 * very close to UINT_MAX but is not a power-of-2 multiple of
2408 * page_size) then just return original size and let kernel reject it
2413 static bool map_is_ringbuf(const struct bpf_map *map)
2415 return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2416 map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2419 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2421 map->def.type = def->map_type;
2422 map->def.key_size = def->key_size;
2423 map->def.value_size = def->value_size;
2424 map->def.max_entries = def->max_entries;
2425 map->def.map_flags = def->map_flags;
2426 map->map_extra = def->map_extra;
2428 map->numa_node = def->numa_node;
2429 map->btf_key_type_id = def->key_type_id;
2430 map->btf_value_type_id = def->value_type_id;
2432 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2433 if (map_is_ringbuf(map))
2434 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2436 if (def->parts & MAP_DEF_MAP_TYPE)
2437 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2439 if (def->parts & MAP_DEF_KEY_TYPE)
2440 pr_debug("map '%s': found key [%u], sz = %u.\n",
2441 map->name, def->key_type_id, def->key_size);
2442 else if (def->parts & MAP_DEF_KEY_SIZE)
2443 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2445 if (def->parts & MAP_DEF_VALUE_TYPE)
2446 pr_debug("map '%s': found value [%u], sz = %u.\n",
2447 map->name, def->value_type_id, def->value_size);
2448 else if (def->parts & MAP_DEF_VALUE_SIZE)
2449 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2451 if (def->parts & MAP_DEF_MAX_ENTRIES)
2452 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2453 if (def->parts & MAP_DEF_MAP_FLAGS)
2454 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2455 if (def->parts & MAP_DEF_MAP_EXTRA)
2456 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2457 (unsigned long long)def->map_extra);
2458 if (def->parts & MAP_DEF_PINNING)
2459 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2460 if (def->parts & MAP_DEF_NUMA_NODE)
2461 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2463 if (def->parts & MAP_DEF_INNER_MAP)
2464 pr_debug("map '%s': found inner map definition.\n", map->name);
2467 static const char *btf_var_linkage_str(__u32 linkage)
2470 case BTF_VAR_STATIC: return "static";
2471 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2472 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2473 default: return "unknown";
2477 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2478 const struct btf_type *sec,
2479 int var_idx, int sec_idx,
2480 const Elf_Data *data, bool strict,
2481 const char *pin_root_path)
2483 struct btf_map_def map_def = {}, inner_def = {};
2484 const struct btf_type *var, *def;
2485 const struct btf_var_secinfo *vi;
2486 const struct btf_var *var_extra;
2487 const char *map_name;
2488 struct bpf_map *map;
2491 vi = btf_var_secinfos(sec) + var_idx;
2492 var = btf__type_by_id(obj->btf, vi->type);
2493 var_extra = btf_var(var);
2494 map_name = btf__name_by_offset(obj->btf, var->name_off);
2496 if (map_name == NULL || map_name[0] == '\0') {
2497 pr_warn("map #%d: empty name.\n", var_idx);
2500 if ((__u64)vi->offset + vi->size > data->d_size) {
2501 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2504 if (!btf_is_var(var)) {
2505 pr_warn("map '%s': unexpected var kind %s.\n",
2506 map_name, btf_kind_str(var));
2509 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2510 pr_warn("map '%s': unsupported map linkage %s.\n",
2511 map_name, btf_var_linkage_str(var_extra->linkage));
2515 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2516 if (!btf_is_struct(def)) {
2517 pr_warn("map '%s': unexpected def kind %s.\n",
2518 map_name, btf_kind_str(var));
2521 if (def->size > vi->size) {
2522 pr_warn("map '%s': invalid def size.\n", map_name);
2526 map = bpf_object__add_map(obj);
2528 return PTR_ERR(map);
2529 map->name = strdup(map_name);
2531 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2534 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2535 map->def.type = BPF_MAP_TYPE_UNSPEC;
2536 map->sec_idx = sec_idx;
2537 map->sec_offset = vi->offset;
2538 map->btf_var_idx = var_idx;
2539 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2540 map_name, map->sec_idx, map->sec_offset);
2542 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2546 fill_map_from_def(map, &map_def);
2548 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2549 err = build_map_pin_path(map, pin_root_path);
2551 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2556 if (map_def.parts & MAP_DEF_INNER_MAP) {
2557 map->inner_map = calloc(1, sizeof(*map->inner_map));
2558 if (!map->inner_map)
2560 map->inner_map->fd = -1;
2561 map->inner_map->sec_idx = sec_idx;
2562 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2563 if (!map->inner_map->name)
2565 sprintf(map->inner_map->name, "%s.inner", map_name);
2567 fill_map_from_def(map->inner_map, &inner_def);
2570 err = map_fill_btf_type_info(obj, map);
2577 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2578 const char *pin_root_path)
2580 const struct btf_type *sec = NULL;
2581 int nr_types, i, vlen, err;
2582 const struct btf_type *t;
2587 if (obj->efile.btf_maps_shndx < 0)
2590 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2591 data = elf_sec_data(obj, scn);
2592 if (!scn || !data) {
2593 pr_warn("elf: failed to get %s map definitions for %s\n",
2594 MAPS_ELF_SEC, obj->path);
2598 nr_types = btf__type_cnt(obj->btf);
2599 for (i = 1; i < nr_types; i++) {
2600 t = btf__type_by_id(obj->btf, i);
2601 if (!btf_is_datasec(t))
2603 name = btf__name_by_offset(obj->btf, t->name_off);
2604 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2606 obj->efile.btf_maps_sec_btf_id = i;
2612 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2616 vlen = btf_vlen(sec);
2617 for (i = 0; i < vlen; i++) {
2618 err = bpf_object__init_user_btf_map(obj, sec, i,
2619 obj->efile.btf_maps_shndx,
2629 static int bpf_object__init_maps(struct bpf_object *obj,
2630 const struct bpf_object_open_opts *opts)
2632 const char *pin_root_path;
2636 strict = !OPTS_GET(opts, relaxed_maps, false);
2637 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2639 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2640 err = err ?: bpf_object__init_global_data_maps(obj);
2641 err = err ?: bpf_object__init_kconfig_map(obj);
2642 err = err ?: bpf_object_init_struct_ops(obj);
2647 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2651 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2655 return sh->sh_flags & SHF_EXECINSTR;
2658 static bool btf_needs_sanitization(struct bpf_object *obj)
2660 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2661 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2662 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2663 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2664 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2665 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2666 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2668 return !has_func || !has_datasec || !has_func_global || !has_float ||
2669 !has_decl_tag || !has_type_tag || !has_enum64;
2672 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2674 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2675 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2676 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2677 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2678 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2679 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2680 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2681 int enum64_placeholder_id = 0;
2685 for (i = 1; i < btf__type_cnt(btf); i++) {
2686 t = (struct btf_type *)btf__type_by_id(btf, i);
2688 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2689 /* replace VAR/DECL_TAG with INT */
2690 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2692 * using size = 1 is the safest choice, 4 will be too
2693 * big and cause kernel BTF validation failure if
2694 * original variable took less than 4 bytes
2697 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2698 } else if (!has_datasec && btf_is_datasec(t)) {
2699 /* replace DATASEC with STRUCT */
2700 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2701 struct btf_member *m = btf_members(t);
2702 struct btf_type *vt;
2705 name = (char *)btf__name_by_offset(btf, t->name_off);
2713 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2714 for (j = 0; j < vlen; j++, v++, m++) {
2715 /* order of field assignments is important */
2716 m->offset = v->offset * 8;
2718 /* preserve variable name as member name */
2719 vt = (void *)btf__type_by_id(btf, v->type);
2720 m->name_off = vt->name_off;
2722 } else if (!has_func && btf_is_func_proto(t)) {
2723 /* replace FUNC_PROTO with ENUM */
2725 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2726 t->size = sizeof(__u32); /* kernel enforced */
2727 } else if (!has_func && btf_is_func(t)) {
2728 /* replace FUNC with TYPEDEF */
2729 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2730 } else if (!has_func_global && btf_is_func(t)) {
2731 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2732 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2733 } else if (!has_float && btf_is_float(t)) {
2734 /* replace FLOAT with an equally-sized empty STRUCT;
2735 * since C compilers do not accept e.g. "float" as a
2736 * valid struct name, make it anonymous
2739 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2740 } else if (!has_type_tag && btf_is_type_tag(t)) {
2741 /* replace TYPE_TAG with a CONST */
2743 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2744 } else if (!has_enum64 && btf_is_enum(t)) {
2745 /* clear the kflag */
2746 t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2747 } else if (!has_enum64 && btf_is_enum64(t)) {
2748 /* replace ENUM64 with a union */
2749 struct btf_member *m;
2751 if (enum64_placeholder_id == 0) {
2752 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2753 if (enum64_placeholder_id < 0)
2754 return enum64_placeholder_id;
2756 t = (struct btf_type *)btf__type_by_id(btf, i);
2761 t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2762 for (j = 0; j < vlen; j++, m++) {
2763 m->type = enum64_placeholder_id;
2772 static bool libbpf_needs_btf(const struct bpf_object *obj)
2774 return obj->efile.btf_maps_shndx >= 0 ||
2775 obj->efile.st_ops_shndx >= 0 ||
2776 obj->efile.st_ops_link_shndx >= 0 ||
2780 static bool kernel_needs_btf(const struct bpf_object *obj)
2782 return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2785 static int bpf_object__init_btf(struct bpf_object *obj,
2787 Elf_Data *btf_ext_data)
2792 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2793 err = libbpf_get_error(obj->btf);
2796 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2799 /* enforce 8-byte pointers for BPF-targeted BTFs */
2800 btf__set_pointer_size(obj->btf, 8);
2803 struct btf_ext_info *ext_segs[3];
2804 int seg_num, sec_num;
2807 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2808 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2811 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2812 err = libbpf_get_error(obj->btf_ext);
2814 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2815 BTF_EXT_ELF_SEC, err);
2816 obj->btf_ext = NULL;
2820 /* setup .BTF.ext to ELF section mapping */
2821 ext_segs[0] = &obj->btf_ext->func_info;
2822 ext_segs[1] = &obj->btf_ext->line_info;
2823 ext_segs[2] = &obj->btf_ext->core_relo_info;
2824 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2825 struct btf_ext_info *seg = ext_segs[seg_num];
2826 const struct btf_ext_info_sec *sec;
2827 const char *sec_name;
2830 if (seg->sec_cnt == 0)
2833 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2834 if (!seg->sec_idxs) {
2840 for_each_btf_ext_sec(seg, sec) {
2841 /* preventively increment index to avoid doing
2842 * this before every continue below
2846 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2847 if (str_is_empty(sec_name))
2849 scn = elf_sec_by_name(obj, sec_name);
2853 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2858 if (err && libbpf_needs_btf(obj)) {
2859 pr_warn("BTF is required, but is missing or corrupted.\n");
2865 static int compare_vsi_off(const void *_a, const void *_b)
2867 const struct btf_var_secinfo *a = _a;
2868 const struct btf_var_secinfo *b = _b;
2870 return a->offset - b->offset;
2873 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2876 __u32 size = 0, i, vars = btf_vlen(t);
2877 const char *sec_name = btf__name_by_offset(btf, t->name_off);
2878 struct btf_var_secinfo *vsi;
2879 bool fixup_offsets = false;
2883 pr_debug("No name found in string section for DATASEC kind.\n");
2887 /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2888 * variable offsets set at the previous step. Further, not every
2889 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2890 * all fixups altogether for such sections and go straight to sorting
2891 * VARs within their DATASEC.
2893 if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2896 /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2897 * fix this up. But BPF static linker already fixes this up and fills
2898 * all the sizes and offsets during static linking. So this step has
2899 * to be optional. But the STV_HIDDEN handling is non-optional for any
2900 * non-extern DATASEC, so the variable fixup loop below handles both
2901 * functions at the same time, paying the cost of BTF VAR <-> ELF
2902 * symbol matching just once.
2905 err = find_elf_sec_sz(obj, sec_name, &size);
2907 pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2908 sec_name, size, err);
2913 fixup_offsets = true;
2916 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2917 const struct btf_type *t_var;
2918 struct btf_var *var;
2919 const char *var_name;
2922 t_var = btf__type_by_id(btf, vsi->type);
2923 if (!t_var || !btf_is_var(t_var)) {
2924 pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2928 var = btf_var(t_var);
2929 if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2932 var_name = btf__name_by_offset(btf, t_var->name_off);
2934 pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2939 sym = find_elf_var_sym(obj, var_name);
2941 pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2942 sec_name, var_name);
2947 vsi->offset = sym->st_value;
2949 /* if variable is a global/weak symbol, but has restricted
2950 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2951 * as static. This follows similar logic for functions (BPF
2952 * subprogs) and influences libbpf's further decisions about
2953 * whether to make global data BPF array maps as
2956 if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2957 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2958 var->linkage = BTF_VAR_STATIC;
2962 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2966 static int bpf_object_fixup_btf(struct bpf_object *obj)
2973 n = btf__type_cnt(obj->btf);
2974 for (i = 1; i < n; i++) {
2975 struct btf_type *t = btf_type_by_id(obj->btf, i);
2977 /* Loader needs to fix up some of the things compiler
2978 * couldn't get its hands on while emitting BTF. This
2979 * is section size and global variable offset. We use
2980 * the info from the ELF itself for this purpose.
2982 if (btf_is_datasec(t)) {
2983 err = btf_fixup_datasec(obj, obj->btf, t);
2992 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2994 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2995 prog->type == BPF_PROG_TYPE_LSM)
2998 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2999 * also need vmlinux BTF
3001 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3007 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3009 struct bpf_program *prog;
3012 /* CO-RE relocations need kernel BTF, only when btf_custom_path
3015 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3018 /* Support for typed ksyms needs kernel BTF */
3019 for (i = 0; i < obj->nr_extern; i++) {
3020 const struct extern_desc *ext;
3022 ext = &obj->externs[i];
3023 if (ext->type == EXT_KSYM && ext->ksym.type_id)
3027 bpf_object__for_each_program(prog, obj) {
3028 if (!prog->autoload)
3030 if (prog_needs_vmlinux_btf(prog))
3037 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3041 /* btf_vmlinux could be loaded earlier */
3042 if (obj->btf_vmlinux || obj->gen_loader)
3045 if (!force && !obj_needs_vmlinux_btf(obj))
3048 obj->btf_vmlinux = btf__load_vmlinux_btf();
3049 err = libbpf_get_error(obj->btf_vmlinux);
3051 pr_warn("Error loading vmlinux BTF: %d\n", err);
3052 obj->btf_vmlinux = NULL;
3058 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3060 struct btf *kern_btf = obj->btf;
3061 bool btf_mandatory, sanitize;
3067 if (!kernel_supports(obj, FEAT_BTF)) {
3068 if (kernel_needs_btf(obj)) {
3072 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3076 /* Even though some subprogs are global/weak, user might prefer more
3077 * permissive BPF verification process that BPF verifier performs for
3078 * static functions, taking into account more context from the caller
3079 * functions. In such case, they need to mark such subprogs with
3080 * __attribute__((visibility("hidden"))) and libbpf will adjust
3081 * corresponding FUNC BTF type to be marked as static and trigger more
3082 * involved BPF verification process.
3084 for (i = 0; i < obj->nr_programs; i++) {
3085 struct bpf_program *prog = &obj->programs[i];
3090 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3093 n = btf__type_cnt(obj->btf);
3094 for (j = 1; j < n; j++) {
3095 t = btf_type_by_id(obj->btf, j);
3096 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3099 name = btf__str_by_offset(obj->btf, t->name_off);
3100 if (strcmp(name, prog->name) != 0)
3103 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3108 sanitize = btf_needs_sanitization(obj);
3110 const void *raw_data;
3113 /* clone BTF to sanitize a copy and leave the original intact */
3114 raw_data = btf__raw_data(obj->btf, &sz);
3115 kern_btf = btf__new(raw_data, sz);
3116 err = libbpf_get_error(kern_btf);
3120 /* enforce 8-byte pointers for BPF-targeted BTFs */
3121 btf__set_pointer_size(obj->btf, 8);
3122 err = bpf_object__sanitize_btf(obj, kern_btf);
3127 if (obj->gen_loader) {
3129 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3133 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3134 /* Pretend to have valid FD to pass various fd >= 0 checks.
3135 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3137 btf__set_fd(kern_btf, 0);
3139 /* currently BPF_BTF_LOAD only supports log_level 1 */
3140 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3141 obj->log_level ? 1 : 0);
3145 /* move fd to libbpf's BTF */
3146 btf__set_fd(obj->btf, btf__fd(kern_btf));
3147 btf__set_fd(kern_btf, -1);
3149 btf__free(kern_btf);
3153 btf_mandatory = kernel_needs_btf(obj);
3154 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3155 btf_mandatory ? "BTF is mandatory, can't proceed."
3156 : "BTF is optional, ignoring.");
3163 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3167 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3169 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3170 off, obj->path, elf_errmsg(-1));
3177 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3181 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3183 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3184 off, obj->path, elf_errmsg(-1));
3191 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3195 scn = elf_getscn(obj->efile.elf, idx);
3197 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3198 idx, obj->path, elf_errmsg(-1));
3204 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3206 Elf_Scn *scn = NULL;
3207 Elf *elf = obj->efile.elf;
3208 const char *sec_name;
3210 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3211 sec_name = elf_sec_name(obj, scn);
3215 if (strcmp(sec_name, name) != 0)
3223 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3230 shdr = elf64_getshdr(scn);
3232 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3233 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3240 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3248 sh = elf_sec_hdr(obj, scn);
3252 name = elf_sec_str(obj, sh->sh_name);
3254 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3255 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3262 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3269 data = elf_getdata(scn, 0);
3271 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3272 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3273 obj->path, elf_errmsg(-1));
3280 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3282 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3285 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3288 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3290 if (idx >= data->d_size / sizeof(Elf64_Rel))
3293 return (Elf64_Rel *)data->d_buf + idx;
3296 static bool is_sec_name_dwarf(const char *name)
3298 /* approximation, but the actual list is too long */
3299 return str_has_pfx(name, ".debug_");
3302 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3304 /* no special handling of .strtab */
3305 if (hdr->sh_type == SHT_STRTAB)
3308 /* ignore .llvm_addrsig section as well */
3309 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3312 /* no subprograms will lead to an empty .text section, ignore it */
3313 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3314 strcmp(name, ".text") == 0)
3317 /* DWARF sections */
3318 if (is_sec_name_dwarf(name))
3321 if (str_has_pfx(name, ".rel")) {
3322 name += sizeof(".rel") - 1;
3323 /* DWARF section relocations */
3324 if (is_sec_name_dwarf(name))
3327 /* .BTF and .BTF.ext don't need relocations */
3328 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3329 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3336 static int cmp_progs(const void *_a, const void *_b)
3338 const struct bpf_program *a = _a;
3339 const struct bpf_program *b = _b;
3341 if (a->sec_idx != b->sec_idx)
3342 return a->sec_idx < b->sec_idx ? -1 : 1;
3344 /* sec_insn_off can't be the same within the section */
3345 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3348 static int bpf_object__elf_collect(struct bpf_object *obj)
3350 struct elf_sec_desc *sec_desc;
3351 Elf *elf = obj->efile.elf;
3352 Elf_Data *btf_ext_data = NULL;
3353 Elf_Data *btf_data = NULL;
3354 int idx = 0, err = 0;
3360 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3361 * section. Since section count retrieved by elf_getshdrnum() does
3362 * include sec #0, it is already the necessary size of an array to keep
3365 if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3366 pr_warn("elf: failed to get the number of sections for %s: %s\n",
3367 obj->path, elf_errmsg(-1));
3368 return -LIBBPF_ERRNO__FORMAT;
3370 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3371 if (!obj->efile.secs)
3374 /* a bunch of ELF parsing functionality depends on processing symbols,
3375 * so do the first pass and find the symbol table
3378 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3379 sh = elf_sec_hdr(obj, scn);
3381 return -LIBBPF_ERRNO__FORMAT;
3383 if (sh->sh_type == SHT_SYMTAB) {
3384 if (obj->efile.symbols) {
3385 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3386 return -LIBBPF_ERRNO__FORMAT;
3389 data = elf_sec_data(obj, scn);
3391 return -LIBBPF_ERRNO__FORMAT;
3393 idx = elf_ndxscn(scn);
3395 obj->efile.symbols = data;
3396 obj->efile.symbols_shndx = idx;
3397 obj->efile.strtabidx = sh->sh_link;
3401 if (!obj->efile.symbols) {
3402 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3408 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3409 idx = elf_ndxscn(scn);
3410 sec_desc = &obj->efile.secs[idx];
3412 sh = elf_sec_hdr(obj, scn);
3414 return -LIBBPF_ERRNO__FORMAT;
3416 name = elf_sec_str(obj, sh->sh_name);
3418 return -LIBBPF_ERRNO__FORMAT;
3420 if (ignore_elf_section(sh, name))
3423 data = elf_sec_data(obj, scn);
3425 return -LIBBPF_ERRNO__FORMAT;
3427 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3428 idx, name, (unsigned long)data->d_size,
3429 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3432 if (strcmp(name, "license") == 0) {
3433 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3436 } else if (strcmp(name, "version") == 0) {
3437 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3440 } else if (strcmp(name, "maps") == 0) {
3441 pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3443 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3444 obj->efile.btf_maps_shndx = idx;
3445 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3446 if (sh->sh_type != SHT_PROGBITS)
3447 return -LIBBPF_ERRNO__FORMAT;
3449 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3450 if (sh->sh_type != SHT_PROGBITS)
3451 return -LIBBPF_ERRNO__FORMAT;
3452 btf_ext_data = data;
3453 } else if (sh->sh_type == SHT_SYMTAB) {
3454 /* already processed during the first pass above */
3455 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3456 if (sh->sh_flags & SHF_EXECINSTR) {
3457 if (strcmp(name, ".text") == 0)
3458 obj->efile.text_shndx = idx;
3459 err = bpf_object__add_programs(obj, data, name, idx);
3462 } else if (strcmp(name, DATA_SEC) == 0 ||
3463 str_has_pfx(name, DATA_SEC ".")) {
3464 sec_desc->sec_type = SEC_DATA;
3465 sec_desc->shdr = sh;
3466 sec_desc->data = data;
3467 } else if (strcmp(name, RODATA_SEC) == 0 ||
3468 str_has_pfx(name, RODATA_SEC ".")) {
3469 sec_desc->sec_type = SEC_RODATA;
3470 sec_desc->shdr = sh;
3471 sec_desc->data = data;
3472 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3473 obj->efile.st_ops_data = data;
3474 obj->efile.st_ops_shndx = idx;
3475 } else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3476 obj->efile.st_ops_link_data = data;
3477 obj->efile.st_ops_link_shndx = idx;
3479 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3482 } else if (sh->sh_type == SHT_REL) {
3483 int targ_sec_idx = sh->sh_info; /* points to other section */
3485 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3486 targ_sec_idx >= obj->efile.sec_cnt)
3487 return -LIBBPF_ERRNO__FORMAT;
3489 /* Only do relo for section with exec instructions */
3490 if (!section_have_execinstr(obj, targ_sec_idx) &&
3491 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3492 strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3493 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3494 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3495 idx, name, targ_sec_idx,
3496 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3500 sec_desc->sec_type = SEC_RELO;
3501 sec_desc->shdr = sh;
3502 sec_desc->data = data;
3503 } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3504 str_has_pfx(name, BSS_SEC "."))) {
3505 sec_desc->sec_type = SEC_BSS;
3506 sec_desc->shdr = sh;
3507 sec_desc->data = data;
3509 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3510 (size_t)sh->sh_size);
3514 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3515 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3516 return -LIBBPF_ERRNO__FORMAT;
3519 /* sort BPF programs by section name and in-section instruction offset
3522 if (obj->nr_programs)
3523 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3525 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3528 static bool sym_is_extern(const Elf64_Sym *sym)
3530 int bind = ELF64_ST_BIND(sym->st_info);
3531 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3532 return sym->st_shndx == SHN_UNDEF &&
3533 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3534 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3537 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3539 int bind = ELF64_ST_BIND(sym->st_info);
3540 int type = ELF64_ST_TYPE(sym->st_info);
3542 /* in .text section */
3543 if (sym->st_shndx != text_shndx)
3546 /* local function */
3547 if (bind == STB_LOCAL && type == STT_SECTION)
3550 /* global function */
3551 return bind == STB_GLOBAL && type == STT_FUNC;
3554 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3556 const struct btf_type *t;
3563 n = btf__type_cnt(btf);
3564 for (i = 1; i < n; i++) {
3565 t = btf__type_by_id(btf, i);
3567 if (!btf_is_var(t) && !btf_is_func(t))
3570 tname = btf__name_by_offset(btf, t->name_off);
3571 if (strcmp(tname, ext_name))
3574 if (btf_is_var(t) &&
3575 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3578 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3587 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3588 const struct btf_var_secinfo *vs;
3589 const struct btf_type *t;
3595 n = btf__type_cnt(btf);
3596 for (i = 1; i < n; i++) {
3597 t = btf__type_by_id(btf, i);
3599 if (!btf_is_datasec(t))
3602 vs = btf_var_secinfos(t);
3603 for (j = 0; j < btf_vlen(t); j++, vs++) {
3604 if (vs->type == ext_btf_id)
3612 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3615 const struct btf_type *t;
3618 t = skip_mods_and_typedefs(btf, id, NULL);
3619 name = btf__name_by_offset(btf, t->name_off);
3623 switch (btf_kind(t)) {
3624 case BTF_KIND_INT: {
3625 int enc = btf_int_encoding(t);
3627 if (enc & BTF_INT_BOOL)
3628 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3630 *is_signed = enc & BTF_INT_SIGNED;
3633 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3634 return KCFG_UNKNOWN;
3639 return KCFG_UNKNOWN;
3640 if (strcmp(name, "libbpf_tristate"))
3641 return KCFG_UNKNOWN;
3642 return KCFG_TRISTATE;
3643 case BTF_KIND_ENUM64:
3644 if (strcmp(name, "libbpf_tristate"))
3645 return KCFG_UNKNOWN;
3646 return KCFG_TRISTATE;
3647 case BTF_KIND_ARRAY:
3648 if (btf_array(t)->nelems == 0)
3649 return KCFG_UNKNOWN;
3650 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3651 return KCFG_UNKNOWN;
3652 return KCFG_CHAR_ARR;
3654 return KCFG_UNKNOWN;
3658 static int cmp_externs(const void *_a, const void *_b)
3660 const struct extern_desc *a = _a;
3661 const struct extern_desc *b = _b;
3663 if (a->type != b->type)
3664 return a->type < b->type ? -1 : 1;
3666 if (a->type == EXT_KCFG) {
3667 /* descending order by alignment requirements */
3668 if (a->kcfg.align != b->kcfg.align)
3669 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3670 /* ascending order by size, within same alignment class */
3671 if (a->kcfg.sz != b->kcfg.sz)
3672 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3675 /* resolve ties by name */
3676 return strcmp(a->name, b->name);
3679 static int find_int_btf_id(const struct btf *btf)
3681 const struct btf_type *t;
3684 n = btf__type_cnt(btf);
3685 for (i = 1; i < n; i++) {
3686 t = btf__type_by_id(btf, i);
3688 if (btf_is_int(t) && btf_int_bits(t) == 32)
3695 static int add_dummy_ksym_var(struct btf *btf)
3697 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3698 const struct btf_var_secinfo *vs;
3699 const struct btf_type *sec;
3704 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3709 sec = btf__type_by_id(btf, sec_btf_id);
3710 vs = btf_var_secinfos(sec);
3711 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3712 const struct btf_type *vt;
3714 vt = btf__type_by_id(btf, vs->type);
3715 if (btf_is_func(vt))
3719 /* No func in ksyms sec. No need to add dummy var. */
3720 if (i == btf_vlen(sec))
3723 int_btf_id = find_int_btf_id(btf);
3724 dummy_var_btf_id = btf__add_var(btf,
3726 BTF_VAR_GLOBAL_ALLOCATED,
3728 if (dummy_var_btf_id < 0)
3729 pr_warn("cannot create a dummy_ksym var\n");
3731 return dummy_var_btf_id;
3734 static int bpf_object__collect_externs(struct bpf_object *obj)
3736 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3737 const struct btf_type *t;
3738 struct extern_desc *ext;
3739 int i, n, off, dummy_var_btf_id;
3740 const char *ext_name, *sec_name;
3744 if (!obj->efile.symbols)
3747 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3748 sh = elf_sec_hdr(obj, scn);
3749 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3750 return -LIBBPF_ERRNO__FORMAT;
3752 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3753 if (dummy_var_btf_id < 0)
3754 return dummy_var_btf_id;
3756 n = sh->sh_size / sh->sh_entsize;
3757 pr_debug("looking for externs among %d symbols...\n", n);
3759 for (i = 0; i < n; i++) {
3760 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3763 return -LIBBPF_ERRNO__FORMAT;
3764 if (!sym_is_extern(sym))
3766 ext_name = elf_sym_str(obj, sym->st_name);
3767 if (!ext_name || !ext_name[0])
3771 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3775 ext = &ext[obj->nr_extern];
3776 memset(ext, 0, sizeof(*ext));
3779 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3780 if (ext->btf_id <= 0) {
3781 pr_warn("failed to find BTF for extern '%s': %d\n",
3782 ext_name, ext->btf_id);
3785 t = btf__type_by_id(obj->btf, ext->btf_id);
3786 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3788 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3790 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3791 if (ext->sec_btf_id <= 0) {
3792 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3793 ext_name, ext->btf_id, ext->sec_btf_id);
3794 return ext->sec_btf_id;
3796 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3797 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3799 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3800 if (btf_is_func(t)) {
3801 pr_warn("extern function %s is unsupported under %s section\n",
3802 ext->name, KCONFIG_SEC);
3806 ext->type = EXT_KCFG;
3807 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3808 if (ext->kcfg.sz <= 0) {
3809 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3810 ext_name, ext->kcfg.sz);
3811 return ext->kcfg.sz;
3813 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3814 if (ext->kcfg.align <= 0) {
3815 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3816 ext_name, ext->kcfg.align);
3819 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3820 &ext->kcfg.is_signed);
3821 if (ext->kcfg.type == KCFG_UNKNOWN) {
3822 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3825 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3827 ext->type = EXT_KSYM;
3828 skip_mods_and_typedefs(obj->btf, t->type,
3829 &ext->ksym.type_id);
3831 pr_warn("unrecognized extern section '%s'\n", sec_name);
3835 pr_debug("collected %d externs total\n", obj->nr_extern);
3837 if (!obj->nr_extern)
3840 /* sort externs by type, for kcfg ones also by (align, size, name) */
3841 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3843 /* for .ksyms section, we need to turn all externs into allocated
3844 * variables in BTF to pass kernel verification; we do this by
3845 * pretending that each extern is a 8-byte variable
3848 /* find existing 4-byte integer type in BTF to use for fake
3849 * extern variables in DATASEC
3851 int int_btf_id = find_int_btf_id(obj->btf);
3852 /* For extern function, a dummy_var added earlier
3853 * will be used to replace the vs->type and
3854 * its name string will be used to refill
3855 * the missing param's name.
3857 const struct btf_type *dummy_var;
3859 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3860 for (i = 0; i < obj->nr_extern; i++) {
3861 ext = &obj->externs[i];
3862 if (ext->type != EXT_KSYM)
3864 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3865 i, ext->sym_idx, ext->name);
3870 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3871 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3872 struct btf_type *vt;
3874 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3875 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3876 ext = find_extern_by_name(obj, ext_name);
3878 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3879 btf_kind_str(vt), ext_name);
3882 if (btf_is_func(vt)) {
3883 const struct btf_type *func_proto;
3884 struct btf_param *param;
3887 func_proto = btf__type_by_id(obj->btf,
3889 param = btf_params(func_proto);
3890 /* Reuse the dummy_var string if the
3891 * func proto does not have param name.
3893 for (j = 0; j < btf_vlen(func_proto); j++)
3894 if (param[j].type && !param[j].name_off)
3896 dummy_var->name_off;
3897 vs->type = dummy_var_btf_id;
3898 vt->info &= ~0xffff;
3899 vt->info |= BTF_FUNC_GLOBAL;
3901 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3902 vt->type = int_btf_id;
3905 vs->size = sizeof(int);
3912 /* for kcfg externs calculate their offsets within a .kconfig map */
3914 for (i = 0; i < obj->nr_extern; i++) {
3915 ext = &obj->externs[i];
3916 if (ext->type != EXT_KCFG)
3919 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3920 off = ext->kcfg.data_off + ext->kcfg.sz;
3921 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3922 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3926 for (i = 0; i < n; i++) {
3927 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3929 t = btf__type_by_id(obj->btf, vs->type);
3930 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3931 ext = find_extern_by_name(obj, ext_name);
3933 pr_warn("failed to find extern definition for BTF var '%s'\n",
3937 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3938 vs->offset = ext->kcfg.data_off;
3944 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3946 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3949 struct bpf_program *
3950 bpf_object__find_program_by_name(const struct bpf_object *obj,
3953 struct bpf_program *prog;
3955 bpf_object__for_each_program(prog, obj) {
3956 if (prog_is_subprog(obj, prog))
3958 if (!strcmp(prog->name, name))
3961 return errno = ENOENT, NULL;
3964 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3967 switch (obj->efile.secs[shndx].sec_type) {
3977 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3980 return shndx == obj->efile.btf_maps_shndx;
3983 static enum libbpf_map_type
3984 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3986 if (shndx == obj->efile.symbols_shndx)
3987 return LIBBPF_MAP_KCONFIG;
3989 switch (obj->efile.secs[shndx].sec_type) {
3991 return LIBBPF_MAP_BSS;
3993 return LIBBPF_MAP_DATA;
3995 return LIBBPF_MAP_RODATA;
3997 return LIBBPF_MAP_UNSPEC;
4001 static int bpf_program__record_reloc(struct bpf_program *prog,
4002 struct reloc_desc *reloc_desc,
4003 __u32 insn_idx, const char *sym_name,
4004 const Elf64_Sym *sym, const Elf64_Rel *rel)
4006 struct bpf_insn *insn = &prog->insns[insn_idx];
4007 size_t map_idx, nr_maps = prog->obj->nr_maps;
4008 struct bpf_object *obj = prog->obj;
4009 __u32 shdr_idx = sym->st_shndx;
4010 enum libbpf_map_type type;
4011 const char *sym_sec_name;
4012 struct bpf_map *map;
4014 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4015 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4016 prog->name, sym_name, insn_idx, insn->code);
4017 return -LIBBPF_ERRNO__RELOC;
4020 if (sym_is_extern(sym)) {
4021 int sym_idx = ELF64_R_SYM(rel->r_info);
4022 int i, n = obj->nr_extern;
4023 struct extern_desc *ext;
4025 for (i = 0; i < n; i++) {
4026 ext = &obj->externs[i];
4027 if (ext->sym_idx == sym_idx)
4031 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4032 prog->name, sym_name, sym_idx);
4033 return -LIBBPF_ERRNO__RELOC;
4035 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4036 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4037 if (insn->code == (BPF_JMP | BPF_CALL))
4038 reloc_desc->type = RELO_EXTERN_CALL;
4040 reloc_desc->type = RELO_EXTERN_LD64;
4041 reloc_desc->insn_idx = insn_idx;
4042 reloc_desc->sym_off = i; /* sym_off stores extern index */
4046 /* sub-program call relocation */
4047 if (is_call_insn(insn)) {
4048 if (insn->src_reg != BPF_PSEUDO_CALL) {
4049 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4050 return -LIBBPF_ERRNO__RELOC;
4052 /* text_shndx can be 0, if no default "main" program exists */
4053 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4054 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4055 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4056 prog->name, sym_name, sym_sec_name);
4057 return -LIBBPF_ERRNO__RELOC;
4059 if (sym->st_value % BPF_INSN_SZ) {
4060 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4061 prog->name, sym_name, (size_t)sym->st_value);
4062 return -LIBBPF_ERRNO__RELOC;
4064 reloc_desc->type = RELO_CALL;
4065 reloc_desc->insn_idx = insn_idx;
4066 reloc_desc->sym_off = sym->st_value;
4070 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4071 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4072 prog->name, sym_name, shdr_idx);
4073 return -LIBBPF_ERRNO__RELOC;
4076 /* loading subprog addresses */
4077 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4078 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4079 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4081 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4082 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4083 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4084 return -LIBBPF_ERRNO__RELOC;
4087 reloc_desc->type = RELO_SUBPROG_ADDR;
4088 reloc_desc->insn_idx = insn_idx;
4089 reloc_desc->sym_off = sym->st_value;
4093 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4094 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4096 /* generic map reference relocation */
4097 if (type == LIBBPF_MAP_UNSPEC) {
4098 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4099 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4100 prog->name, sym_name, sym_sec_name);
4101 return -LIBBPF_ERRNO__RELOC;
4103 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4104 map = &obj->maps[map_idx];
4105 if (map->libbpf_type != type ||
4106 map->sec_idx != sym->st_shndx ||
4107 map->sec_offset != sym->st_value)
4109 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4110 prog->name, map_idx, map->name, map->sec_idx,
4111 map->sec_offset, insn_idx);
4114 if (map_idx >= nr_maps) {
4115 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4116 prog->name, sym_sec_name, (size_t)sym->st_value);
4117 return -LIBBPF_ERRNO__RELOC;
4119 reloc_desc->type = RELO_LD64;
4120 reloc_desc->insn_idx = insn_idx;
4121 reloc_desc->map_idx = map_idx;
4122 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4126 /* global data map relocation */
4127 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4128 pr_warn("prog '%s': bad data relo against section '%s'\n",
4129 prog->name, sym_sec_name);
4130 return -LIBBPF_ERRNO__RELOC;
4132 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4133 map = &obj->maps[map_idx];
4134 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4136 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4137 prog->name, map_idx, map->name, map->sec_idx,
4138 map->sec_offset, insn_idx);
4141 if (map_idx >= nr_maps) {
4142 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4143 prog->name, sym_sec_name);
4144 return -LIBBPF_ERRNO__RELOC;
4147 reloc_desc->type = RELO_DATA;
4148 reloc_desc->insn_idx = insn_idx;
4149 reloc_desc->map_idx = map_idx;
4150 reloc_desc->sym_off = sym->st_value;
4154 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4156 return insn_idx >= prog->sec_insn_off &&
4157 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4160 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4161 size_t sec_idx, size_t insn_idx)
4163 int l = 0, r = obj->nr_programs - 1, m;
4164 struct bpf_program *prog;
4166 if (!obj->nr_programs)
4170 m = l + (r - l + 1) / 2;
4171 prog = &obj->programs[m];
4173 if (prog->sec_idx < sec_idx ||
4174 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4179 /* matching program could be at index l, but it still might be the
4180 * wrong one, so we need to double check conditions for the last time
4182 prog = &obj->programs[l];
4183 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4189 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4191 const char *relo_sec_name, *sec_name;
4192 size_t sec_idx = shdr->sh_info, sym_idx;
4193 struct bpf_program *prog;
4194 struct reloc_desc *relos;
4196 const char *sym_name;
4203 if (sec_idx >= obj->efile.sec_cnt)
4206 scn = elf_sec_by_idx(obj, sec_idx);
4207 scn_data = elf_sec_data(obj, scn);
4209 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4210 sec_name = elf_sec_name(obj, scn);
4211 if (!relo_sec_name || !sec_name)
4214 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4215 relo_sec_name, sec_idx, sec_name);
4216 nrels = shdr->sh_size / shdr->sh_entsize;
4218 for (i = 0; i < nrels; i++) {
4219 rel = elf_rel_by_idx(data, i);
4221 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4222 return -LIBBPF_ERRNO__FORMAT;
4225 sym_idx = ELF64_R_SYM(rel->r_info);
4226 sym = elf_sym_by_idx(obj, sym_idx);
4228 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4229 relo_sec_name, sym_idx, i);
4230 return -LIBBPF_ERRNO__FORMAT;
4233 if (sym->st_shndx >= obj->efile.sec_cnt) {
4234 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4235 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4236 return -LIBBPF_ERRNO__FORMAT;
4239 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4240 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4241 relo_sec_name, (size_t)rel->r_offset, i);
4242 return -LIBBPF_ERRNO__FORMAT;
4245 insn_idx = rel->r_offset / BPF_INSN_SZ;
4246 /* relocations against static functions are recorded as
4247 * relocations against the section that contains a function;
4248 * in such case, symbol will be STT_SECTION and sym.st_name
4249 * will point to empty string (0), so fetch section name
4252 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4253 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4255 sym_name = elf_sym_str(obj, sym->st_name);
4256 sym_name = sym_name ?: "<?";
4258 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4259 relo_sec_name, i, insn_idx, sym_name);
4261 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4263 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4264 relo_sec_name, i, sec_name, insn_idx);
4268 relos = libbpf_reallocarray(prog->reloc_desc,
4269 prog->nr_reloc + 1, sizeof(*relos));
4272 prog->reloc_desc = relos;
4274 /* adjust insn_idx to local BPF program frame of reference */
4275 insn_idx -= prog->sec_insn_off;
4276 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4277 insn_idx, sym_name, sym, rel);
4286 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4293 /* if it's BTF-defined map, we don't need to search for type IDs.
4294 * For struct_ops map, it does not need btf_key_type_id and
4295 * btf_value_type_id.
4297 if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4301 * LLVM annotates global data differently in BTF, that is,
4302 * only as '.data', '.bss' or '.rodata'.
4304 if (!bpf_map__is_internal(map))
4307 id = btf__find_by_name(obj->btf, map->real_name);
4311 map->btf_key_type_id = 0;
4312 map->btf_value_type_id = id;
4316 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4318 char file[PATH_MAX], buff[4096];
4323 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4324 memset(info, 0, sizeof(*info));
4326 fp = fopen(file, "r");
4329 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4334 while (fgets(buff, sizeof(buff), fp)) {
4335 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4337 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4338 info->key_size = val;
4339 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4340 info->value_size = val;
4341 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4342 info->max_entries = val;
4343 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4344 info->map_flags = val;
4352 bool bpf_map__autocreate(const struct bpf_map *map)
4354 return map->autocreate;
4357 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4359 if (map->obj->loaded)
4360 return libbpf_err(-EBUSY);
4362 map->autocreate = autocreate;
4366 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4368 struct bpf_map_info info;
4369 __u32 len = sizeof(info), name_len;
4373 memset(&info, 0, len);
4374 err = bpf_map_get_info_by_fd(fd, &info, &len);
4375 if (err && errno == EINVAL)
4376 err = bpf_get_map_info_from_fdinfo(fd, &info);
4378 return libbpf_err(err);
4380 name_len = strlen(info.name);
4381 if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4382 new_name = strdup(map->name);
4384 new_name = strdup(info.name);
4387 return libbpf_err(-errno);
4389 new_fd = open("/", O_RDONLY | O_CLOEXEC);
4392 goto err_free_new_name;
4395 new_fd = dup3(fd, new_fd, O_CLOEXEC);
4398 goto err_close_new_fd;
4401 err = zclose(map->fd);
4404 goto err_close_new_fd;
4409 map->name = new_name;
4410 map->def.type = info.type;
4411 map->def.key_size = info.key_size;
4412 map->def.value_size = info.value_size;
4413 map->def.max_entries = info.max_entries;
4414 map->def.map_flags = info.map_flags;
4415 map->btf_key_type_id = info.btf_key_type_id;
4416 map->btf_value_type_id = info.btf_value_type_id;
4418 map->map_extra = info.map_extra;
4426 return libbpf_err(err);
4429 __u32 bpf_map__max_entries(const struct bpf_map *map)
4431 return map->def.max_entries;
4434 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4436 if (!bpf_map_type__is_map_in_map(map->def.type))
4437 return errno = EINVAL, NULL;
4439 return map->inner_map;
4442 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4444 if (map->obj->loaded)
4445 return libbpf_err(-EBUSY);
4447 map->def.max_entries = max_entries;
4449 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4450 if (map_is_ringbuf(map))
4451 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4457 bpf_object__probe_loading(struct bpf_object *obj)
4459 char *cp, errmsg[STRERR_BUFSIZE];
4460 struct bpf_insn insns[] = {
4461 BPF_MOV64_IMM(BPF_REG_0, 0),
4464 int ret, insn_cnt = ARRAY_SIZE(insns);
4466 if (obj->gen_loader)
4469 ret = bump_rlimit_memlock();
4471 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4473 /* make sure basic loading works */
4474 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4476 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4479 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4480 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4481 "program. Make sure your kernel supports BPF "
4482 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4483 "set to big enough value.\n", __func__, cp, ret);
4491 static int probe_fd(int fd)
4498 static int probe_kern_prog_name(void)
4500 const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4501 struct bpf_insn insns[] = {
4502 BPF_MOV64_IMM(BPF_REG_0, 0),
4505 union bpf_attr attr;
4508 memset(&attr, 0, attr_sz);
4509 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4510 attr.license = ptr_to_u64("GPL");
4511 attr.insns = ptr_to_u64(insns);
4512 attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4513 libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4515 /* make sure loading with name works */
4516 ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4517 return probe_fd(ret);
4520 static int probe_kern_global_data(void)
4522 char *cp, errmsg[STRERR_BUFSIZE];
4523 struct bpf_insn insns[] = {
4524 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4525 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4526 BPF_MOV64_IMM(BPF_REG_0, 0),
4529 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4531 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4534 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4535 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4536 __func__, cp, -ret);
4542 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4544 return probe_fd(ret);
4547 static int probe_kern_btf(void)
4549 static const char strs[] = "\0int";
4552 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4555 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4556 strs, sizeof(strs)));
4559 static int probe_kern_btf_func(void)
4561 static const char strs[] = "\0int\0x\0a";
4562 /* void x(int a) {} */
4565 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4566 /* FUNC_PROTO */ /* [2] */
4567 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4568 BTF_PARAM_ENC(7, 1),
4569 /* FUNC x */ /* [3] */
4570 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4573 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4574 strs, sizeof(strs)));
4577 static int probe_kern_btf_func_global(void)
4579 static const char strs[] = "\0int\0x\0a";
4580 /* static void x(int a) {} */
4583 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4584 /* FUNC_PROTO */ /* [2] */
4585 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4586 BTF_PARAM_ENC(7, 1),
4587 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4588 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4591 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4592 strs, sizeof(strs)));
4595 static int probe_kern_btf_datasec(void)
4597 static const char strs[] = "\0x\0.data";
4601 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4602 /* VAR x */ /* [2] */
4603 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4605 /* DATASEC val */ /* [3] */
4606 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4607 BTF_VAR_SECINFO_ENC(2, 0, 4),
4610 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4611 strs, sizeof(strs)));
4614 static int probe_kern_btf_float(void)
4616 static const char strs[] = "\0float";
4619 BTF_TYPE_FLOAT_ENC(1, 4),
4622 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4623 strs, sizeof(strs)));
4626 static int probe_kern_btf_decl_tag(void)
4628 static const char strs[] = "\0tag";
4631 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4632 /* VAR x */ /* [2] */
4633 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4636 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4639 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4640 strs, sizeof(strs)));
4643 static int probe_kern_btf_type_tag(void)
4645 static const char strs[] = "\0tag";
4648 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4650 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4652 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4655 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4656 strs, sizeof(strs)));
4659 static int probe_kern_array_mmap(void)
4661 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4664 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4665 return probe_fd(fd);
4668 static int probe_kern_exp_attach_type(void)
4670 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4671 struct bpf_insn insns[] = {
4672 BPF_MOV64_IMM(BPF_REG_0, 0),
4675 int fd, insn_cnt = ARRAY_SIZE(insns);
4677 /* use any valid combination of program type and (optional)
4678 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4679 * to see if kernel supports expected_attach_type field for
4680 * BPF_PROG_LOAD command
4682 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4683 return probe_fd(fd);
4686 static int probe_kern_probe_read_kernel(void)
4688 struct bpf_insn insns[] = {
4689 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4690 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4691 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4692 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4693 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4696 int fd, insn_cnt = ARRAY_SIZE(insns);
4698 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4699 return probe_fd(fd);
4702 static int probe_prog_bind_map(void)
4704 char *cp, errmsg[STRERR_BUFSIZE];
4705 struct bpf_insn insns[] = {
4706 BPF_MOV64_IMM(BPF_REG_0, 0),
4709 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4711 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4714 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4715 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4716 __func__, cp, -ret);
4720 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4726 ret = bpf_prog_bind_map(prog, map, NULL);
4734 static int probe_module_btf(void)
4736 static const char strs[] = "\0int";
4739 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4741 struct bpf_btf_info info;
4742 __u32 len = sizeof(info);
4746 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4748 return 0; /* BTF not supported at all */
4750 memset(&info, 0, sizeof(info));
4751 info.name = ptr_to_u64(name);
4752 info.name_len = sizeof(name);
4754 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4755 * kernel's module BTF support coincides with support for
4756 * name/name_len fields in struct bpf_btf_info.
4758 err = bpf_btf_get_info_by_fd(fd, &info, &len);
4763 static int probe_perf_link(void)
4765 struct bpf_insn insns[] = {
4766 BPF_MOV64_IMM(BPF_REG_0, 0),
4769 int prog_fd, link_fd, err;
4771 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4772 insns, ARRAY_SIZE(insns), NULL);
4776 /* use invalid perf_event FD to get EBADF, if link is supported;
4777 * otherwise EINVAL should be returned
4779 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4780 err = -errno; /* close() can clobber errno */
4786 return link_fd < 0 && err == -EBADF;
4789 static int probe_kern_bpf_cookie(void)
4791 struct bpf_insn insns[] = {
4792 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4795 int ret, insn_cnt = ARRAY_SIZE(insns);
4797 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4798 return probe_fd(ret);
4801 static int probe_kern_btf_enum64(void)
4803 static const char strs[] = "\0enum64";
4805 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4808 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4809 strs, sizeof(strs)));
4812 static int probe_kern_syscall_wrapper(void);
4814 enum kern_feature_result {
4820 typedef int (*feature_probe_fn)(void);
4822 static struct kern_feature_desc {
4824 feature_probe_fn probe;
4825 enum kern_feature_result res;
4826 } feature_probes[__FEAT_CNT] = {
4827 [FEAT_PROG_NAME] = {
4828 "BPF program name", probe_kern_prog_name,
4830 [FEAT_GLOBAL_DATA] = {
4831 "global variables", probe_kern_global_data,
4834 "minimal BTF", probe_kern_btf,
4837 "BTF functions", probe_kern_btf_func,
4839 [FEAT_BTF_GLOBAL_FUNC] = {
4840 "BTF global function", probe_kern_btf_func_global,
4842 [FEAT_BTF_DATASEC] = {
4843 "BTF data section and variable", probe_kern_btf_datasec,
4845 [FEAT_ARRAY_MMAP] = {
4846 "ARRAY map mmap()", probe_kern_array_mmap,
4848 [FEAT_EXP_ATTACH_TYPE] = {
4849 "BPF_PROG_LOAD expected_attach_type attribute",
4850 probe_kern_exp_attach_type,
4852 [FEAT_PROBE_READ_KERN] = {
4853 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4855 [FEAT_PROG_BIND_MAP] = {
4856 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4858 [FEAT_MODULE_BTF] = {
4859 "module BTF support", probe_module_btf,
4861 [FEAT_BTF_FLOAT] = {
4862 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4864 [FEAT_PERF_LINK] = {
4865 "BPF perf link support", probe_perf_link,
4867 [FEAT_BTF_DECL_TAG] = {
4868 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4870 [FEAT_BTF_TYPE_TAG] = {
4871 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4873 [FEAT_MEMCG_ACCOUNT] = {
4874 "memcg-based memory accounting", probe_memcg_account,
4876 [FEAT_BPF_COOKIE] = {
4877 "BPF cookie support", probe_kern_bpf_cookie,
4879 [FEAT_BTF_ENUM64] = {
4880 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4882 [FEAT_SYSCALL_WRAPPER] = {
4883 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4887 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4889 struct kern_feature_desc *feat = &feature_probes[feat_id];
4892 if (obj && obj->gen_loader)
4893 /* To generate loader program assume the latest kernel
4894 * to avoid doing extra prog_load, map_create syscalls.
4898 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4899 ret = feat->probe();
4901 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4902 } else if (ret == 0) {
4903 WRITE_ONCE(feat->res, FEAT_MISSING);
4905 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4906 WRITE_ONCE(feat->res, FEAT_MISSING);
4910 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4913 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4915 struct bpf_map_info map_info;
4916 char msg[STRERR_BUFSIZE];
4917 __u32 map_info_len = sizeof(map_info);
4920 memset(&map_info, 0, map_info_len);
4921 err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4922 if (err && errno == EINVAL)
4923 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4925 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4926 libbpf_strerror_r(errno, msg, sizeof(msg)));
4930 return (map_info.type == map->def.type &&
4931 map_info.key_size == map->def.key_size &&
4932 map_info.value_size == map->def.value_size &&
4933 map_info.max_entries == map->def.max_entries &&
4934 map_info.map_flags == map->def.map_flags &&
4935 map_info.map_extra == map->map_extra);
4939 bpf_object__reuse_map(struct bpf_map *map)
4941 char *cp, errmsg[STRERR_BUFSIZE];
4944 pin_fd = bpf_obj_get(map->pin_path);
4947 if (err == -ENOENT) {
4948 pr_debug("found no pinned map to reuse at '%s'\n",
4953 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4954 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4959 if (!map_is_reuse_compat(map, pin_fd)) {
4960 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4966 err = bpf_map__reuse_fd(map, pin_fd);
4972 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4978 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4980 enum libbpf_map_type map_type = map->libbpf_type;
4981 char *cp, errmsg[STRERR_BUFSIZE];
4984 if (obj->gen_loader) {
4985 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4986 map->mmaped, map->def.value_size);
4987 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4988 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4991 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4994 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4995 pr_warn("Error setting initial map(%s) contents: %s\n",
5000 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
5001 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5002 err = bpf_map_freeze(map->fd);
5005 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5006 pr_warn("Error freezing map(%s) as read-only: %s\n",
5014 static void bpf_map__destroy(struct bpf_map *map);
5016 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5018 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5019 struct bpf_map_def *def = &map->def;
5020 const char *map_name = NULL;
5023 if (kernel_supports(obj, FEAT_PROG_NAME))
5024 map_name = map->name;
5025 create_attr.map_ifindex = map->map_ifindex;
5026 create_attr.map_flags = def->map_flags;
5027 create_attr.numa_node = map->numa_node;
5028 create_attr.map_extra = map->map_extra;
5030 if (bpf_map__is_struct_ops(map))
5031 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5033 if (obj->btf && btf__fd(obj->btf) >= 0) {
5034 create_attr.btf_fd = btf__fd(obj->btf);
5035 create_attr.btf_key_type_id = map->btf_key_type_id;
5036 create_attr.btf_value_type_id = map->btf_value_type_id;
5039 if (bpf_map_type__is_map_in_map(def->type)) {
5040 if (map->inner_map) {
5041 err = bpf_object__create_map(obj, map->inner_map, true);
5043 pr_warn("map '%s': failed to create inner map: %d\n",
5047 map->inner_map_fd = bpf_map__fd(map->inner_map);
5049 if (map->inner_map_fd >= 0)
5050 create_attr.inner_map_fd = map->inner_map_fd;
5053 switch (def->type) {
5054 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5055 case BPF_MAP_TYPE_CGROUP_ARRAY:
5056 case BPF_MAP_TYPE_STACK_TRACE:
5057 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5058 case BPF_MAP_TYPE_HASH_OF_MAPS:
5059 case BPF_MAP_TYPE_DEVMAP:
5060 case BPF_MAP_TYPE_DEVMAP_HASH:
5061 case BPF_MAP_TYPE_CPUMAP:
5062 case BPF_MAP_TYPE_XSKMAP:
5063 case BPF_MAP_TYPE_SOCKMAP:
5064 case BPF_MAP_TYPE_SOCKHASH:
5065 case BPF_MAP_TYPE_QUEUE:
5066 case BPF_MAP_TYPE_STACK:
5067 create_attr.btf_fd = 0;
5068 create_attr.btf_key_type_id = 0;
5069 create_attr.btf_value_type_id = 0;
5070 map->btf_key_type_id = 0;
5071 map->btf_value_type_id = 0;
5076 if (obj->gen_loader) {
5077 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5078 def->key_size, def->value_size, def->max_entries,
5079 &create_attr, is_inner ? -1 : map - obj->maps);
5080 /* Pretend to have valid FD to pass various fd >= 0 checks.
5081 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5085 map->fd = bpf_map_create(def->type, map_name,
5086 def->key_size, def->value_size,
5087 def->max_entries, &create_attr);
5089 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5090 create_attr.btf_value_type_id)) {
5091 char *cp, errmsg[STRERR_BUFSIZE];
5094 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5095 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5096 map->name, cp, err);
5097 create_attr.btf_fd = 0;
5098 create_attr.btf_key_type_id = 0;
5099 create_attr.btf_value_type_id = 0;
5100 map->btf_key_type_id = 0;
5101 map->btf_value_type_id = 0;
5102 map->fd = bpf_map_create(def->type, map_name,
5103 def->key_size, def->value_size,
5104 def->max_entries, &create_attr);
5107 err = map->fd < 0 ? -errno : 0;
5109 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5110 if (obj->gen_loader)
5111 map->inner_map->fd = -1;
5112 bpf_map__destroy(map->inner_map);
5113 zfree(&map->inner_map);
5119 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5121 const struct bpf_map *targ_map;
5125 for (i = 0; i < map->init_slots_sz; i++) {
5126 if (!map->init_slots[i])
5129 targ_map = map->init_slots[i];
5130 fd = bpf_map__fd(targ_map);
5132 if (obj->gen_loader) {
5133 bpf_gen__populate_outer_map(obj->gen_loader,
5135 targ_map - obj->maps);
5137 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5141 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5142 map->name, i, targ_map->name, fd, err);
5145 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5146 map->name, i, targ_map->name, fd);
5149 zfree(&map->init_slots);
5150 map->init_slots_sz = 0;
5155 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5157 const struct bpf_program *targ_prog;
5161 if (obj->gen_loader)
5164 for (i = 0; i < map->init_slots_sz; i++) {
5165 if (!map->init_slots[i])
5168 targ_prog = map->init_slots[i];
5169 fd = bpf_program__fd(targ_prog);
5171 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5174 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5175 map->name, i, targ_prog->name, fd, err);
5178 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5179 map->name, i, targ_prog->name, fd);
5182 zfree(&map->init_slots);
5183 map->init_slots_sz = 0;
5188 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5190 struct bpf_map *map;
5193 for (i = 0; i < obj->nr_maps; i++) {
5194 map = &obj->maps[i];
5196 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5199 err = init_prog_array_slots(obj, map);
5208 static int map_set_def_max_entries(struct bpf_map *map)
5210 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5213 nr_cpus = libbpf_num_possible_cpus();
5215 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5216 map->name, nr_cpus);
5219 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5220 map->def.max_entries = nr_cpus;
5227 bpf_object__create_maps(struct bpf_object *obj)
5229 struct bpf_map *map;
5230 char *cp, errmsg[STRERR_BUFSIZE];
5235 for (i = 0; i < obj->nr_maps; i++) {
5236 map = &obj->maps[i];
5238 /* To support old kernels, we skip creating global data maps
5239 * (.rodata, .data, .kconfig, etc); later on, during program
5240 * loading, if we detect that at least one of the to-be-loaded
5241 * programs is referencing any global data map, we'll error
5242 * out with program name and relocation index logged.
5243 * This approach allows to accommodate Clang emitting
5244 * unnecessary .rodata.str1.1 sections for string literals,
5245 * but also it allows to have CO-RE applications that use
5246 * global variables in some of BPF programs, but not others.
5247 * If those global variable-using programs are not loaded at
5248 * runtime due to bpf_program__set_autoload(prog, false),
5249 * bpf_object loading will succeed just fine even on old
5252 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5253 map->autocreate = false;
5255 if (!map->autocreate) {
5256 pr_debug("map '%s': skipped auto-creating...\n", map->name);
5260 err = map_set_def_max_entries(map);
5266 if (map->pin_path) {
5267 err = bpf_object__reuse_map(map);
5269 pr_warn("map '%s': error reusing pinned map\n",
5273 if (retried && map->fd < 0) {
5274 pr_warn("map '%s': cannot find pinned map\n",
5282 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5283 map->name, map->fd);
5285 err = bpf_object__create_map(obj, map, false);
5289 pr_debug("map '%s': created successfully, fd=%d\n",
5290 map->name, map->fd);
5292 if (bpf_map__is_internal(map)) {
5293 err = bpf_object__populate_internal_map(obj, map);
5300 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5301 err = init_map_in_map_slots(obj, map);
5309 if (map->pin_path && !map->pinned) {
5310 err = bpf_map__pin(map, NULL);
5313 if (!retried && err == -EEXIST) {
5317 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5318 map->name, map->pin_path, err);
5327 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5328 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5330 for (j = 0; j < i; j++)
5331 zclose(obj->maps[j].fd);
5335 static bool bpf_core_is_flavor_sep(const char *s)
5337 /* check X___Y name pattern, where X and Y are not underscores */
5338 return s[0] != '_' && /* X */
5339 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5340 s[4] != '_'; /* Y */
5343 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5344 * before last triple underscore. Struct name part after last triple
5345 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5347 size_t bpf_core_essential_name_len(const char *name)
5349 size_t n = strlen(name);
5352 for (i = n - 5; i >= 0; i--) {
5353 if (bpf_core_is_flavor_sep(name + i))
5359 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5368 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5369 size_t local_essent_len,
5370 const struct btf *targ_btf,
5371 const char *targ_btf_name,
5373 struct bpf_core_cand_list *cands)
5375 struct bpf_core_cand *new_cands, *cand;
5376 const struct btf_type *t, *local_t;
5377 const char *targ_name, *local_name;
5378 size_t targ_essent_len;
5381 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5382 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5384 n = btf__type_cnt(targ_btf);
5385 for (i = targ_start_id; i < n; i++) {
5386 t = btf__type_by_id(targ_btf, i);
5387 if (!btf_kind_core_compat(t, local_t))
5390 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5391 if (str_is_empty(targ_name))
5394 targ_essent_len = bpf_core_essential_name_len(targ_name);
5395 if (targ_essent_len != local_essent_len)
5398 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5401 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5402 local_cand->id, btf_kind_str(local_t),
5403 local_name, i, btf_kind_str(t), targ_name,
5405 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5406 sizeof(*cands->cands));
5410 cand = &new_cands[cands->len];
5411 cand->btf = targ_btf;
5414 cands->cands = new_cands;
5420 static int load_module_btfs(struct bpf_object *obj)
5422 struct bpf_btf_info info;
5423 struct module_btf *mod_btf;
5429 if (obj->btf_modules_loaded)
5432 if (obj->gen_loader)
5435 /* don't do this again, even if we find no module BTFs */
5436 obj->btf_modules_loaded = true;
5438 /* kernel too old to support module BTFs */
5439 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5443 err = bpf_btf_get_next_id(id, &id);
5444 if (err && errno == ENOENT)
5448 pr_warn("failed to iterate BTF objects: %d\n", err);
5452 fd = bpf_btf_get_fd_by_id(id);
5454 if (errno == ENOENT)
5455 continue; /* expected race: BTF was unloaded */
5457 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5462 memset(&info, 0, sizeof(info));
5463 info.name = ptr_to_u64(name);
5464 info.name_len = sizeof(name);
5466 err = bpf_btf_get_info_by_fd(fd, &info, &len);
5469 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5473 /* ignore non-module BTFs */
5474 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5479 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5480 err = libbpf_get_error(btf);
5482 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5487 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5488 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5492 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5497 mod_btf->name = strdup(name);
5498 if (!mod_btf->name) {
5512 static struct bpf_core_cand_list *
5513 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5515 struct bpf_core_cand local_cand = {};
5516 struct bpf_core_cand_list *cands;
5517 const struct btf *main_btf;
5518 const struct btf_type *local_t;
5519 const char *local_name;
5520 size_t local_essent_len;
5523 local_cand.btf = local_btf;
5524 local_cand.id = local_type_id;
5525 local_t = btf__type_by_id(local_btf, local_type_id);
5527 return ERR_PTR(-EINVAL);
5529 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5530 if (str_is_empty(local_name))
5531 return ERR_PTR(-EINVAL);
5532 local_essent_len = bpf_core_essential_name_len(local_name);
5534 cands = calloc(1, sizeof(*cands));
5536 return ERR_PTR(-ENOMEM);
5538 /* Attempt to find target candidates in vmlinux BTF first */
5539 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5540 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5544 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5548 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5549 if (obj->btf_vmlinux_override)
5552 /* now look through module BTFs, trying to still find candidates */
5553 err = load_module_btfs(obj);
5557 for (i = 0; i < obj->btf_module_cnt; i++) {
5558 err = bpf_core_add_cands(&local_cand, local_essent_len,
5559 obj->btf_modules[i].btf,
5560 obj->btf_modules[i].name,
5561 btf__type_cnt(obj->btf_vmlinux),
5569 bpf_core_free_cands(cands);
5570 return ERR_PTR(err);
5573 /* Check local and target types for compatibility. This check is used for
5574 * type-based CO-RE relocations and follow slightly different rules than
5575 * field-based relocations. This function assumes that root types were already
5576 * checked for name match. Beyond that initial root-level name check, names
5577 * are completely ignored. Compatibility rules are as follows:
5578 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5579 * kind should match for local and target types (i.e., STRUCT is not
5580 * compatible with UNION);
5581 * - for ENUMs, the size is ignored;
5582 * - for INT, size and signedness are ignored;
5583 * - for ARRAY, dimensionality is ignored, element types are checked for
5584 * compatibility recursively;
5585 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5586 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5587 * - FUNC_PROTOs are compatible if they have compatible signature: same
5588 * number of input args and compatible return and argument types.
5589 * These rules are not set in stone and probably will be adjusted as we get
5590 * more experience with using BPF CO-RE relocations.
5592 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5593 const struct btf *targ_btf, __u32 targ_id)
5595 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5598 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5599 const struct btf *targ_btf, __u32 targ_id)
5601 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5604 static size_t bpf_core_hash_fn(const long key, void *ctx)
5609 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5614 static int record_relo_core(struct bpf_program *prog,
5615 const struct bpf_core_relo *core_relo, int insn_idx)
5617 struct reloc_desc *relos, *relo;
5619 relos = libbpf_reallocarray(prog->reloc_desc,
5620 prog->nr_reloc + 1, sizeof(*relos));
5623 relo = &relos[prog->nr_reloc];
5624 relo->type = RELO_CORE;
5625 relo->insn_idx = insn_idx;
5626 relo->core_relo = core_relo;
5627 prog->reloc_desc = relos;
5632 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5634 struct reloc_desc *relo;
5637 for (i = 0; i < prog->nr_reloc; i++) {
5638 relo = &prog->reloc_desc[i];
5639 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5642 return relo->core_relo;
5648 static int bpf_core_resolve_relo(struct bpf_program *prog,
5649 const struct bpf_core_relo *relo,
5651 const struct btf *local_btf,
5652 struct hashmap *cand_cache,
5653 struct bpf_core_relo_res *targ_res)
5655 struct bpf_core_spec specs_scratch[3] = {};
5656 struct bpf_core_cand_list *cands = NULL;
5657 const char *prog_name = prog->name;
5658 const struct btf_type *local_type;
5659 const char *local_name;
5660 __u32 local_id = relo->type_id;
5663 local_type = btf__type_by_id(local_btf, local_id);
5667 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5671 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5672 !hashmap__find(cand_cache, local_id, &cands)) {
5673 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5674 if (IS_ERR(cands)) {
5675 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5676 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5677 local_name, PTR_ERR(cands));
5678 return PTR_ERR(cands);
5680 err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5682 bpf_core_free_cands(cands);
5687 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5692 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5694 const struct btf_ext_info_sec *sec;
5695 struct bpf_core_relo_res targ_res;
5696 const struct bpf_core_relo *rec;
5697 const struct btf_ext_info *seg;
5698 struct hashmap_entry *entry;
5699 struct hashmap *cand_cache = NULL;
5700 struct bpf_program *prog;
5701 struct bpf_insn *insn;
5702 const char *sec_name;
5703 int i, err = 0, insn_idx, sec_idx, sec_num;
5705 if (obj->btf_ext->core_relo_info.len == 0)
5708 if (targ_btf_path) {
5709 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5710 err = libbpf_get_error(obj->btf_vmlinux_override);
5712 pr_warn("failed to parse target BTF: %d\n", err);
5717 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5718 if (IS_ERR(cand_cache)) {
5719 err = PTR_ERR(cand_cache);
5723 seg = &obj->btf_ext->core_relo_info;
5725 for_each_btf_ext_sec(seg, sec) {
5726 sec_idx = seg->sec_idxs[sec_num];
5729 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5730 if (str_is_empty(sec_name)) {
5735 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5737 for_each_btf_ext_rec(seg, sec, i, rec) {
5738 if (rec->insn_off % BPF_INSN_SZ)
5740 insn_idx = rec->insn_off / BPF_INSN_SZ;
5741 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5743 /* When __weak subprog is "overridden" by another instance
5744 * of the subprog from a different object file, linker still
5745 * appends all the .BTF.ext info that used to belong to that
5746 * eliminated subprogram.
5747 * This is similar to what x86-64 linker does for relocations.
5748 * So just ignore such relocations just like we ignore
5749 * subprog instructions when discovering subprograms.
5751 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5752 sec_name, i, insn_idx);
5755 /* no need to apply CO-RE relocation if the program is
5756 * not going to be loaded
5758 if (!prog->autoload)
5761 /* adjust insn_idx from section frame of reference to the local
5762 * program's frame of reference; (sub-)program code is not yet
5763 * relocated, so it's enough to just subtract in-section offset
5765 insn_idx = insn_idx - prog->sec_insn_off;
5766 if (insn_idx >= prog->insns_cnt)
5768 insn = &prog->insns[insn_idx];
5770 err = record_relo_core(prog, rec, insn_idx);
5772 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5773 prog->name, i, err);
5777 if (prog->obj->gen_loader)
5780 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5782 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5783 prog->name, i, err);
5787 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5789 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5790 prog->name, i, insn_idx, err);
5797 /* obj->btf_vmlinux and module BTFs are freed after object load */
5798 btf__free(obj->btf_vmlinux_override);
5799 obj->btf_vmlinux_override = NULL;
5801 if (!IS_ERR_OR_NULL(cand_cache)) {
5802 hashmap__for_each_entry(cand_cache, entry, i) {
5803 bpf_core_free_cands(entry->pvalue);
5805 hashmap__free(cand_cache);
5810 /* base map load ldimm64 special constant, used also for log fixup logic */
5811 #define MAP_LDIMM64_POISON_BASE 2001000000
5812 #define MAP_LDIMM64_POISON_PFX "200100"
5814 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5815 int insn_idx, struct bpf_insn *insn,
5816 int map_idx, const struct bpf_map *map)
5820 pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5821 prog->name, relo_idx, insn_idx, map_idx, map->name);
5823 /* we turn single ldimm64 into two identical invalid calls */
5824 for (i = 0; i < 2; i++) {
5825 insn->code = BPF_JMP | BPF_CALL;
5829 /* if this instruction is reachable (not a dead code),
5830 * verifier will complain with something like:
5831 * invalid func unknown#2001000123
5832 * where lower 123 is map index into obj->maps[] array
5834 insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5840 /* Relocate data references within program code:
5842 * - global variable references;
5843 * - extern references.
5846 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5850 for (i = 0; i < prog->nr_reloc; i++) {
5851 struct reloc_desc *relo = &prog->reloc_desc[i];
5852 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5853 const struct bpf_map *map;
5854 struct extern_desc *ext;
5856 switch (relo->type) {
5858 map = &obj->maps[relo->map_idx];
5859 if (obj->gen_loader) {
5860 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5861 insn[0].imm = relo->map_idx;
5862 } else if (map->autocreate) {
5863 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5864 insn[0].imm = map->fd;
5866 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5867 relo->map_idx, map);
5871 map = &obj->maps[relo->map_idx];
5872 insn[1].imm = insn[0].imm + relo->sym_off;
5873 if (obj->gen_loader) {
5874 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5875 insn[0].imm = relo->map_idx;
5876 } else if (map->autocreate) {
5877 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5878 insn[0].imm = map->fd;
5880 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5881 relo->map_idx, map);
5884 case RELO_EXTERN_LD64:
5885 ext = &obj->externs[relo->sym_off];
5886 if (ext->type == EXT_KCFG) {
5887 if (obj->gen_loader) {
5888 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5889 insn[0].imm = obj->kconfig_map_idx;
5891 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5892 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5894 insn[1].imm = ext->kcfg.data_off;
5895 } else /* EXT_KSYM */ {
5896 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5897 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5898 insn[0].imm = ext->ksym.kernel_btf_id;
5899 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5900 } else { /* typeless ksyms or unresolved typed ksyms */
5901 insn[0].imm = (__u32)ext->ksym.addr;
5902 insn[1].imm = ext->ksym.addr >> 32;
5906 case RELO_EXTERN_CALL:
5907 ext = &obj->externs[relo->sym_off];
5908 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5910 insn[0].imm = ext->ksym.kernel_btf_id;
5911 insn[0].off = ext->ksym.btf_fd_idx;
5912 } else { /* unresolved weak kfunc */
5917 case RELO_SUBPROG_ADDR:
5918 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5919 pr_warn("prog '%s': relo #%d: bad insn\n",
5923 /* handled already */
5926 /* handled already */
5929 /* will be handled by bpf_program_record_relos() */
5932 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5933 prog->name, i, relo->type);
5941 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5942 const struct bpf_program *prog,
5943 const struct btf_ext_info *ext_info,
5944 void **prog_info, __u32 *prog_rec_cnt,
5947 void *copy_start = NULL, *copy_end = NULL;
5948 void *rec, *rec_end, *new_prog_info;
5949 const struct btf_ext_info_sec *sec;
5950 size_t old_sz, new_sz;
5951 int i, sec_num, sec_idx, off_adj;
5954 for_each_btf_ext_sec(ext_info, sec) {
5955 sec_idx = ext_info->sec_idxs[sec_num];
5957 if (prog->sec_idx != sec_idx)
5960 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5961 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5963 if (insn_off < prog->sec_insn_off)
5965 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5970 copy_end = rec + ext_info->rec_size;
5976 /* append func/line info of a given (sub-)program to the main
5977 * program func/line info
5979 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5980 new_sz = old_sz + (copy_end - copy_start);
5981 new_prog_info = realloc(*prog_info, new_sz);
5984 *prog_info = new_prog_info;
5985 *prog_rec_cnt = new_sz / ext_info->rec_size;
5986 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5988 /* Kernel instruction offsets are in units of 8-byte
5989 * instructions, while .BTF.ext instruction offsets generated
5990 * by Clang are in units of bytes. So convert Clang offsets
5991 * into kernel offsets and adjust offset according to program
5992 * relocated position.
5994 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5995 rec = new_prog_info + old_sz;
5996 rec_end = new_prog_info + new_sz;
5997 for (; rec < rec_end; rec += ext_info->rec_size) {
5998 __u32 *insn_off = rec;
6000 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6002 *prog_rec_sz = ext_info->rec_size;
6010 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6011 struct bpf_program *main_prog,
6012 const struct bpf_program *prog)
6016 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6017 * supprot func/line info
6019 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6022 /* only attempt func info relocation if main program's func_info
6023 * relocation was successful
6025 if (main_prog != prog && !main_prog->func_info)
6028 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6029 &main_prog->func_info,
6030 &main_prog->func_info_cnt,
6031 &main_prog->func_info_rec_size);
6033 if (err != -ENOENT) {
6034 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6038 if (main_prog->func_info) {
6040 * Some info has already been found but has problem
6041 * in the last btf_ext reloc. Must have to error out.
6043 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6046 /* Have problem loading the very first info. Ignore the rest. */
6047 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6052 /* don't relocate line info if main program's relocation failed */
6053 if (main_prog != prog && !main_prog->line_info)
6056 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6057 &main_prog->line_info,
6058 &main_prog->line_info_cnt,
6059 &main_prog->line_info_rec_size);
6061 if (err != -ENOENT) {
6062 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6066 if (main_prog->line_info) {
6068 * Some info has already been found but has problem
6069 * in the last btf_ext reloc. Must have to error out.
6071 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6074 /* Have problem loading the very first info. Ignore the rest. */
6075 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6081 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6083 size_t insn_idx = *(const size_t *)key;
6084 const struct reloc_desc *relo = elem;
6086 if (insn_idx == relo->insn_idx)
6088 return insn_idx < relo->insn_idx ? -1 : 1;
6091 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6093 if (!prog->nr_reloc)
6095 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6096 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6099 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6101 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6102 struct reloc_desc *relos;
6105 if (main_prog == subprog)
6107 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6110 if (subprog->nr_reloc)
6111 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6112 sizeof(*relos) * subprog->nr_reloc);
6114 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6115 relos[i].insn_idx += subprog->sub_insn_off;
6116 /* After insn_idx adjustment the 'relos' array is still sorted
6117 * by insn_idx and doesn't break bsearch.
6119 main_prog->reloc_desc = relos;
6120 main_prog->nr_reloc = new_cnt;
6125 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6126 struct bpf_program *prog)
6128 size_t sub_insn_idx, insn_idx, new_cnt;
6129 struct bpf_program *subprog;
6130 struct bpf_insn *insns, *insn;
6131 struct reloc_desc *relo;
6134 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6138 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6139 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6140 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6143 relo = find_prog_insn_relo(prog, insn_idx);
6144 if (relo && relo->type == RELO_EXTERN_CALL)
6145 /* kfunc relocations will be handled later
6146 * in bpf_object__relocate_data()
6149 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6150 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6151 prog->name, insn_idx, relo->type);
6152 return -LIBBPF_ERRNO__RELOC;
6155 /* sub-program instruction index is a combination of
6156 * an offset of a symbol pointed to by relocation and
6157 * call instruction's imm field; for global functions,
6158 * call always has imm = -1, but for static functions
6159 * relocation is against STT_SECTION and insn->imm
6160 * points to a start of a static function
6162 * for subprog addr relocation, the relo->sym_off + insn->imm is
6163 * the byte offset in the corresponding section.
6165 if (relo->type == RELO_CALL)
6166 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6168 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6169 } else if (insn_is_pseudo_func(insn)) {
6171 * RELO_SUBPROG_ADDR relo is always emitted even if both
6172 * functions are in the same section, so it shouldn't reach here.
6174 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6175 prog->name, insn_idx);
6176 return -LIBBPF_ERRNO__RELOC;
6178 /* if subprogram call is to a static function within
6179 * the same ELF section, there won't be any relocation
6180 * emitted, but it also means there is no additional
6181 * offset necessary, insns->imm is relative to
6182 * instruction's original position within the section
6184 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6187 /* we enforce that sub-programs should be in .text section */
6188 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6190 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6192 return -LIBBPF_ERRNO__RELOC;
6195 /* if it's the first call instruction calling into this
6196 * subprogram (meaning this subprog hasn't been processed
6197 * yet) within the context of current main program:
6198 * - append it at the end of main program's instructions blog;
6199 * - process is recursively, while current program is put on hold;
6200 * - if that subprogram calls some other not yet processes
6201 * subprogram, same thing will happen recursively until
6202 * there are no more unprocesses subprograms left to append
6205 if (subprog->sub_insn_off == 0) {
6206 subprog->sub_insn_off = main_prog->insns_cnt;
6208 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6209 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6211 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6214 main_prog->insns = insns;
6215 main_prog->insns_cnt = new_cnt;
6217 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6218 subprog->insns_cnt * sizeof(*insns));
6220 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6221 main_prog->name, subprog->insns_cnt, subprog->name);
6223 /* The subprog insns are now appended. Append its relos too. */
6224 err = append_subprog_relos(main_prog, subprog);
6227 err = bpf_object__reloc_code(obj, main_prog, subprog);
6232 /* main_prog->insns memory could have been re-allocated, so
6233 * calculate pointer again
6235 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6236 /* calculate correct instruction position within current main
6237 * prog; each main prog can have a different set of
6238 * subprograms appended (potentially in different order as
6239 * well), so position of any subprog can be different for
6240 * different main programs
6242 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6244 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6245 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6252 * Relocate sub-program calls.
6254 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6255 * main prog) is processed separately. For each subprog (non-entry functions,
6256 * that can be called from either entry progs or other subprogs) gets their
6257 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6258 * hasn't been yet appended and relocated within current main prog. Once its
6259 * relocated, sub_insn_off will point at the position within current main prog
6260 * where given subprog was appended. This will further be used to relocate all
6261 * the call instructions jumping into this subprog.
6263 * We start with main program and process all call instructions. If the call
6264 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6265 * is zero), subprog instructions are appended at the end of main program's
6266 * instruction array. Then main program is "put on hold" while we recursively
6267 * process newly appended subprogram. If that subprogram calls into another
6268 * subprogram that hasn't been appended, new subprogram is appended again to
6269 * the *main* prog's instructions (subprog's instructions are always left
6270 * untouched, as they need to be in unmodified state for subsequent main progs
6271 * and subprog instructions are always sent only as part of a main prog) and
6272 * the process continues recursively. Once all the subprogs called from a main
6273 * prog or any of its subprogs are appended (and relocated), all their
6274 * positions within finalized instructions array are known, so it's easy to
6275 * rewrite call instructions with correct relative offsets, corresponding to
6276 * desired target subprog.
6278 * Its important to realize that some subprogs might not be called from some
6279 * main prog and any of its called/used subprogs. Those will keep their
6280 * subprog->sub_insn_off as zero at all times and won't be appended to current
6281 * main prog and won't be relocated within the context of current main prog.
6282 * They might still be used from other main progs later.
6284 * Visually this process can be shown as below. Suppose we have two main
6285 * programs mainA and mainB and BPF object contains three subprogs: subA,
6286 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6287 * subC both call subB:
6289 * +--------+ +-------+
6291 * +--+---+ +--+-+-+ +---+--+
6292 * | subA | | subB | | subC |
6293 * +--+---+ +------+ +---+--+
6296 * +---+-------+ +------+----+
6297 * | mainA | | mainB |
6298 * +-----------+ +-----------+
6300 * We'll start relocating mainA, will find subA, append it and start
6301 * processing sub A recursively:
6303 * +-----------+------+
6305 * +-----------+------+
6307 * At this point we notice that subB is used from subA, so we append it and
6308 * relocate (there are no further subcalls from subB):
6310 * +-----------+------+------+
6311 * | mainA | subA | subB |
6312 * +-----------+------+------+
6314 * At this point, we relocate subA calls, then go one level up and finish with
6315 * relocatin mainA calls. mainA is done.
6317 * For mainB process is similar but results in different order. We start with
6318 * mainB and skip subA and subB, as mainB never calls them (at least
6319 * directly), but we see subC is needed, so we append and start processing it:
6321 * +-----------+------+
6323 * +-----------+------+
6324 * Now we see subC needs subB, so we go back to it, append and relocate it:
6326 * +-----------+------+------+
6327 * | mainB | subC | subB |
6328 * +-----------+------+------+
6330 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6333 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6335 struct bpf_program *subprog;
6338 /* mark all subprogs as not relocated (yet) within the context of
6339 * current main program
6341 for (i = 0; i < obj->nr_programs; i++) {
6342 subprog = &obj->programs[i];
6343 if (!prog_is_subprog(obj, subprog))
6346 subprog->sub_insn_off = 0;
6349 err = bpf_object__reloc_code(obj, prog, prog);
6357 bpf_object__free_relocs(struct bpf_object *obj)
6359 struct bpf_program *prog;
6362 /* free up relocation descriptors */
6363 for (i = 0; i < obj->nr_programs; i++) {
6364 prog = &obj->programs[i];
6365 zfree(&prog->reloc_desc);
6370 static int cmp_relocs(const void *_a, const void *_b)
6372 const struct reloc_desc *a = _a;
6373 const struct reloc_desc *b = _b;
6375 if (a->insn_idx != b->insn_idx)
6376 return a->insn_idx < b->insn_idx ? -1 : 1;
6378 /* no two relocations should have the same insn_idx, but ... */
6379 if (a->type != b->type)
6380 return a->type < b->type ? -1 : 1;
6385 static void bpf_object__sort_relos(struct bpf_object *obj)
6389 for (i = 0; i < obj->nr_programs; i++) {
6390 struct bpf_program *p = &obj->programs[i];
6395 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6400 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6402 struct bpf_program *prog;
6407 err = bpf_object__relocate_core(obj, targ_btf_path);
6409 pr_warn("failed to perform CO-RE relocations: %d\n",
6413 bpf_object__sort_relos(obj);
6416 /* Before relocating calls pre-process relocations and mark
6417 * few ld_imm64 instructions that points to subprogs.
6418 * Otherwise bpf_object__reloc_code() later would have to consider
6419 * all ld_imm64 insns as relocation candidates. That would
6420 * reduce relocation speed, since amount of find_prog_insn_relo()
6421 * would increase and most of them will fail to find a relo.
6423 for (i = 0; i < obj->nr_programs; i++) {
6424 prog = &obj->programs[i];
6425 for (j = 0; j < prog->nr_reloc; j++) {
6426 struct reloc_desc *relo = &prog->reloc_desc[j];
6427 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6429 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6430 if (relo->type == RELO_SUBPROG_ADDR)
6431 insn[0].src_reg = BPF_PSEUDO_FUNC;
6435 /* relocate subprogram calls and append used subprograms to main
6436 * programs; each copy of subprogram code needs to be relocated
6437 * differently for each main program, because its code location might
6439 * Append subprog relos to main programs to allow data relos to be
6440 * processed after text is completely relocated.
6442 for (i = 0; i < obj->nr_programs; i++) {
6443 prog = &obj->programs[i];
6444 /* sub-program's sub-calls are relocated within the context of
6445 * its main program only
6447 if (prog_is_subprog(obj, prog))
6449 if (!prog->autoload)
6452 err = bpf_object__relocate_calls(obj, prog);
6454 pr_warn("prog '%s': failed to relocate calls: %d\n",
6459 /* Process data relos for main programs */
6460 for (i = 0; i < obj->nr_programs; i++) {
6461 prog = &obj->programs[i];
6462 if (prog_is_subprog(obj, prog))
6464 if (!prog->autoload)
6466 err = bpf_object__relocate_data(obj, prog);
6468 pr_warn("prog '%s': failed to relocate data references: %d\n",
6477 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6478 Elf64_Shdr *shdr, Elf_Data *data);
6480 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6481 Elf64_Shdr *shdr, Elf_Data *data)
6483 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6484 int i, j, nrels, new_sz;
6485 const struct btf_var_secinfo *vi = NULL;
6486 const struct btf_type *sec, *var, *def;
6487 struct bpf_map *map = NULL, *targ_map = NULL;
6488 struct bpf_program *targ_prog = NULL;
6489 bool is_prog_array, is_map_in_map;
6490 const struct btf_member *member;
6491 const char *name, *mname, *type;
6497 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6499 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6503 nrels = shdr->sh_size / shdr->sh_entsize;
6504 for (i = 0; i < nrels; i++) {
6505 rel = elf_rel_by_idx(data, i);
6507 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6508 return -LIBBPF_ERRNO__FORMAT;
6511 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6513 pr_warn(".maps relo #%d: symbol %zx not found\n",
6514 i, (size_t)ELF64_R_SYM(rel->r_info));
6515 return -LIBBPF_ERRNO__FORMAT;
6517 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6519 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6520 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6521 (size_t)rel->r_offset, sym->st_name, name);
6523 for (j = 0; j < obj->nr_maps; j++) {
6524 map = &obj->maps[j];
6525 if (map->sec_idx != obj->efile.btf_maps_shndx)
6528 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6529 if (vi->offset <= rel->r_offset &&
6530 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6533 if (j == obj->nr_maps) {
6534 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6535 i, name, (size_t)rel->r_offset);
6539 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6540 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6541 type = is_map_in_map ? "map" : "prog";
6542 if (is_map_in_map) {
6543 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6544 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6546 return -LIBBPF_ERRNO__RELOC;
6548 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6549 map->def.key_size != sizeof(int)) {
6550 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6551 i, map->name, sizeof(int));
6554 targ_map = bpf_object__find_map_by_name(obj, name);
6556 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6560 } else if (is_prog_array) {
6561 targ_prog = bpf_object__find_program_by_name(obj, name);
6563 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6567 if (targ_prog->sec_idx != sym->st_shndx ||
6568 targ_prog->sec_insn_off * 8 != sym->st_value ||
6569 prog_is_subprog(obj, targ_prog)) {
6570 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6572 return -LIBBPF_ERRNO__RELOC;
6578 var = btf__type_by_id(obj->btf, vi->type);
6579 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6580 if (btf_vlen(def) == 0)
6582 member = btf_members(def) + btf_vlen(def) - 1;
6583 mname = btf__name_by_offset(obj->btf, member->name_off);
6584 if (strcmp(mname, "values"))
6587 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6588 if (rel->r_offset - vi->offset < moff)
6591 moff = rel->r_offset - vi->offset - moff;
6592 /* here we use BPF pointer size, which is always 64 bit, as we
6593 * are parsing ELF that was built for BPF target
6595 if (moff % bpf_ptr_sz)
6598 if (moff >= map->init_slots_sz) {
6600 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6603 map->init_slots = tmp;
6604 memset(map->init_slots + map->init_slots_sz, 0,
6605 (new_sz - map->init_slots_sz) * host_ptr_sz);
6606 map->init_slots_sz = new_sz;
6608 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6610 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6611 i, map->name, moff, type, name);
6617 static int bpf_object__collect_relos(struct bpf_object *obj)
6621 for (i = 0; i < obj->efile.sec_cnt; i++) {
6622 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6627 if (sec_desc->sec_type != SEC_RELO)
6630 shdr = sec_desc->shdr;
6631 data = sec_desc->data;
6632 idx = shdr->sh_info;
6634 if (shdr->sh_type != SHT_REL) {
6635 pr_warn("internal error at %d\n", __LINE__);
6636 return -LIBBPF_ERRNO__INTERNAL;
6639 if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6640 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6641 else if (idx == obj->efile.btf_maps_shndx)
6642 err = bpf_object__collect_map_relos(obj, shdr, data);
6644 err = bpf_object__collect_prog_relos(obj, shdr, data);
6649 bpf_object__sort_relos(obj);
6653 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6655 if (BPF_CLASS(insn->code) == BPF_JMP &&
6656 BPF_OP(insn->code) == BPF_CALL &&
6657 BPF_SRC(insn->code) == BPF_K &&
6658 insn->src_reg == 0 &&
6659 insn->dst_reg == 0) {
6660 *func_id = insn->imm;
6666 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6668 struct bpf_insn *insn = prog->insns;
6669 enum bpf_func_id func_id;
6672 if (obj->gen_loader)
6675 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6676 if (!insn_is_helper_call(insn, &func_id))
6679 /* on kernels that don't yet support
6680 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6681 * to bpf_probe_read() which works well for old kernels
6684 case BPF_FUNC_probe_read_kernel:
6685 case BPF_FUNC_probe_read_user:
6686 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6687 insn->imm = BPF_FUNC_probe_read;
6689 case BPF_FUNC_probe_read_kernel_str:
6690 case BPF_FUNC_probe_read_user_str:
6691 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6692 insn->imm = BPF_FUNC_probe_read_str;
6701 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6702 int *btf_obj_fd, int *btf_type_id);
6704 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6705 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6706 struct bpf_prog_load_opts *opts, long cookie)
6708 enum sec_def_flags def = cookie;
6710 /* old kernels might not support specifying expected_attach_type */
6711 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6712 opts->expected_attach_type = 0;
6714 if (def & SEC_SLEEPABLE)
6715 opts->prog_flags |= BPF_F_SLEEPABLE;
6717 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6718 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6720 if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6721 int btf_obj_fd = 0, btf_type_id = 0, err;
6722 const char *attach_name;
6724 attach_name = strchr(prog->sec_name, '/');
6726 /* if BPF program is annotated with just SEC("fentry")
6727 * (or similar) without declaratively specifying
6728 * target, then it is expected that target will be
6729 * specified with bpf_program__set_attach_target() at
6730 * runtime before BPF object load step. If not, then
6731 * there is nothing to load into the kernel as BPF
6732 * verifier won't be able to validate BPF program
6733 * correctness anyways.
6735 pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6739 attach_name++; /* skip over / */
6741 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6745 /* cache resolved BTF FD and BTF type ID in the prog */
6746 prog->attach_btf_obj_fd = btf_obj_fd;
6747 prog->attach_btf_id = btf_type_id;
6749 /* but by now libbpf common logic is not utilizing
6750 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6751 * this callback is called after opts were populated by
6752 * libbpf, so this callback has to update opts explicitly here
6754 opts->attach_btf_obj_fd = btf_obj_fd;
6755 opts->attach_btf_id = btf_type_id;
6760 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6762 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6763 struct bpf_insn *insns, int insns_cnt,
6764 const char *license, __u32 kern_version, int *prog_fd)
6766 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6767 const char *prog_name = NULL;
6768 char *cp, errmsg[STRERR_BUFSIZE];
6769 size_t log_buf_size = 0;
6770 char *log_buf = NULL, *tmp;
6771 int btf_fd, ret, err;
6772 bool own_log_buf = true;
6773 __u32 log_level = prog->log_level;
6775 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6777 * The program type must be set. Most likely we couldn't find a proper
6778 * section definition at load time, and thus we didn't infer the type.
6780 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6781 prog->name, prog->sec_name);
6785 if (!insns || !insns_cnt)
6788 load_attr.expected_attach_type = prog->expected_attach_type;
6789 if (kernel_supports(obj, FEAT_PROG_NAME))
6790 prog_name = prog->name;
6791 load_attr.attach_prog_fd = prog->attach_prog_fd;
6792 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6793 load_attr.attach_btf_id = prog->attach_btf_id;
6794 load_attr.kern_version = kern_version;
6795 load_attr.prog_ifindex = prog->prog_ifindex;
6797 /* specify func_info/line_info only if kernel supports them */
6798 btf_fd = bpf_object__btf_fd(obj);
6799 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6800 load_attr.prog_btf_fd = btf_fd;
6801 load_attr.func_info = prog->func_info;
6802 load_attr.func_info_rec_size = prog->func_info_rec_size;
6803 load_attr.func_info_cnt = prog->func_info_cnt;
6804 load_attr.line_info = prog->line_info;
6805 load_attr.line_info_rec_size = prog->line_info_rec_size;
6806 load_attr.line_info_cnt = prog->line_info_cnt;
6808 load_attr.log_level = log_level;
6809 load_attr.prog_flags = prog->prog_flags;
6810 load_attr.fd_array = obj->fd_array;
6812 /* adjust load_attr if sec_def provides custom preload callback */
6813 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6814 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6816 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6820 insns = prog->insns;
6821 insns_cnt = prog->insns_cnt;
6824 if (obj->gen_loader) {
6825 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6826 license, insns, insns_cnt, &load_attr,
6827 prog - obj->programs);
6833 /* if log_level is zero, we don't request logs initially even if
6834 * custom log_buf is specified; if the program load fails, then we'll
6835 * bump log_level to 1 and use either custom log_buf or we'll allocate
6836 * our own and retry the load to get details on what failed
6839 if (prog->log_buf) {
6840 log_buf = prog->log_buf;
6841 log_buf_size = prog->log_size;
6842 own_log_buf = false;
6843 } else if (obj->log_buf) {
6844 log_buf = obj->log_buf;
6845 log_buf_size = obj->log_size;
6846 own_log_buf = false;
6848 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6849 tmp = realloc(log_buf, log_buf_size);
6860 load_attr.log_buf = log_buf;
6861 load_attr.log_size = log_buf_size;
6862 load_attr.log_level = log_level;
6864 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6866 if (log_level && own_log_buf) {
6867 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6868 prog->name, log_buf);
6871 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6872 struct bpf_map *map;
6875 for (i = 0; i < obj->nr_maps; i++) {
6876 map = &prog->obj->maps[i];
6877 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6880 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6881 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6882 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6883 prog->name, map->real_name, cp);
6884 /* Don't fail hard if can't bind rodata. */
6894 if (log_level == 0) {
6898 /* On ENOSPC, increase log buffer size and retry, unless custom
6899 * log_buf is specified.
6900 * Be careful to not overflow u32, though. Kernel's log buf size limit
6901 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6902 * multiply by 2 unless we are sure we'll fit within 32 bits.
6903 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6905 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6910 /* post-process verifier log to improve error descriptions */
6911 fixup_verifier_log(prog, log_buf, log_buf_size);
6913 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6914 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6917 if (own_log_buf && log_buf && log_buf[0] != '\0') {
6918 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6919 prog->name, log_buf);
6928 static char *find_prev_line(char *buf, char *cur)
6932 if (cur == buf) /* end of a log buf */
6936 while (p - 1 >= buf && *(p - 1) != '\n')
6942 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6943 char *orig, size_t orig_sz, const char *patch)
6945 /* size of the remaining log content to the right from the to-be-replaced part */
6946 size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6947 size_t patch_sz = strlen(patch);
6949 if (patch_sz != orig_sz) {
6950 /* If patch line(s) are longer than original piece of verifier log,
6951 * shift log contents by (patch_sz - orig_sz) bytes to the right
6952 * starting from after to-be-replaced part of the log.
6954 * If patch line(s) are shorter than original piece of verifier log,
6955 * shift log contents by (orig_sz - patch_sz) bytes to the left
6956 * starting from after to-be-replaced part of the log
6958 * We need to be careful about not overflowing available
6959 * buf_sz capacity. If that's the case, we'll truncate the end
6960 * of the original log, as necessary.
6962 if (patch_sz > orig_sz) {
6963 if (orig + patch_sz >= buf + buf_sz) {
6964 /* patch is big enough to cover remaining space completely */
6965 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6967 } else if (patch_sz - orig_sz > buf_sz - log_sz) {
6968 /* patch causes part of remaining log to be truncated */
6969 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6972 /* shift remaining log to the right by calculated amount */
6973 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6976 memcpy(orig, patch, patch_sz);
6979 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6980 char *buf, size_t buf_sz, size_t log_sz,
6981 char *line1, char *line2, char *line3)
6983 /* Expected log for failed and not properly guarded CO-RE relocation:
6984 * line1 -> 123: (85) call unknown#195896080
6985 * line2 -> invalid func unknown#195896080
6986 * line3 -> <anything else or end of buffer>
6988 * "123" is the index of the instruction that was poisoned. We extract
6989 * instruction index to find corresponding CO-RE relocation and
6990 * replace this part of the log with more relevant information about
6991 * failed CO-RE relocation.
6993 const struct bpf_core_relo *relo;
6994 struct bpf_core_spec spec;
6995 char patch[512], spec_buf[256];
6996 int insn_idx, err, spec_len;
6998 if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7001 relo = find_relo_core(prog, insn_idx);
7005 err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7009 spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7010 snprintf(patch, sizeof(patch),
7011 "%d: <invalid CO-RE relocation>\n"
7012 "failed to resolve CO-RE relocation %s%s\n",
7013 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7015 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7018 static void fixup_log_missing_map_load(struct bpf_program *prog,
7019 char *buf, size_t buf_sz, size_t log_sz,
7020 char *line1, char *line2, char *line3)
7022 /* Expected log for failed and not properly guarded CO-RE relocation:
7023 * line1 -> 123: (85) call unknown#2001000345
7024 * line2 -> invalid func unknown#2001000345
7025 * line3 -> <anything else or end of buffer>
7027 * "123" is the index of the instruction that was poisoned.
7028 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7030 struct bpf_object *obj = prog->obj;
7031 const struct bpf_map *map;
7032 int insn_idx, map_idx;
7035 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7038 map_idx -= MAP_LDIMM64_POISON_BASE;
7039 if (map_idx < 0 || map_idx >= obj->nr_maps)
7041 map = &obj->maps[map_idx];
7043 snprintf(patch, sizeof(patch),
7044 "%d: <invalid BPF map reference>\n"
7045 "BPF map '%s' is referenced but wasn't created\n",
7046 insn_idx, map->name);
7048 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7051 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7053 /* look for familiar error patterns in last N lines of the log */
7054 const size_t max_last_line_cnt = 10;
7055 char *prev_line, *cur_line, *next_line;
7062 log_sz = strlen(buf) + 1;
7063 next_line = buf + log_sz - 1;
7065 for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7066 cur_line = find_prev_line(buf, next_line);
7070 /* failed CO-RE relocation case */
7071 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7072 prev_line = find_prev_line(buf, cur_line);
7076 fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7077 prev_line, cur_line, next_line);
7079 } else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7080 prev_line = find_prev_line(buf, cur_line);
7084 fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7085 prev_line, cur_line, next_line);
7091 static int bpf_program_record_relos(struct bpf_program *prog)
7093 struct bpf_object *obj = prog->obj;
7096 for (i = 0; i < prog->nr_reloc; i++) {
7097 struct reloc_desc *relo = &prog->reloc_desc[i];
7098 struct extern_desc *ext = &obj->externs[relo->sym_off];
7101 switch (relo->type) {
7102 case RELO_EXTERN_LD64:
7103 if (ext->type != EXT_KSYM)
7105 kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7106 BTF_KIND_VAR : BTF_KIND_FUNC;
7107 bpf_gen__record_extern(obj->gen_loader, ext->name,
7108 ext->is_weak, !ext->ksym.type_id,
7109 true, kind, relo->insn_idx);
7111 case RELO_EXTERN_CALL:
7112 bpf_gen__record_extern(obj->gen_loader, ext->name,
7113 ext->is_weak, false, false, BTF_KIND_FUNC,
7117 struct bpf_core_relo cr = {
7118 .insn_off = relo->insn_idx * 8,
7119 .type_id = relo->core_relo->type_id,
7120 .access_str_off = relo->core_relo->access_str_off,
7121 .kind = relo->core_relo->kind,
7124 bpf_gen__record_relo_core(obj->gen_loader, &cr);
7135 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7137 struct bpf_program *prog;
7141 for (i = 0; i < obj->nr_programs; i++) {
7142 prog = &obj->programs[i];
7143 err = bpf_object__sanitize_prog(obj, prog);
7148 for (i = 0; i < obj->nr_programs; i++) {
7149 prog = &obj->programs[i];
7150 if (prog_is_subprog(obj, prog))
7152 if (!prog->autoload) {
7153 pr_debug("prog '%s': skipped loading\n", prog->name);
7156 prog->log_level |= log_level;
7158 if (obj->gen_loader)
7159 bpf_program_record_relos(prog);
7161 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7162 obj->license, obj->kern_version, &prog->fd);
7164 pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7169 bpf_object__free_relocs(obj);
7173 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7175 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7177 struct bpf_program *prog;
7180 bpf_object__for_each_program(prog, obj) {
7181 prog->sec_def = find_sec_def(prog->sec_name);
7182 if (!prog->sec_def) {
7183 /* couldn't guess, but user might manually specify */
7184 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7185 prog->name, prog->sec_name);
7189 prog->type = prog->sec_def->prog_type;
7190 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7192 /* sec_def can have custom callback which should be called
7193 * after bpf_program is initialized to adjust its properties
7195 if (prog->sec_def->prog_setup_fn) {
7196 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7198 pr_warn("prog '%s': failed to initialize: %d\n",
7208 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7209 const struct bpf_object_open_opts *opts)
7211 const char *obj_name, *kconfig, *btf_tmp_path;
7212 struct bpf_object *obj;
7219 if (elf_version(EV_CURRENT) == EV_NONE) {
7220 pr_warn("failed to init libelf for %s\n",
7221 path ? : "(mem buf)");
7222 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7225 if (!OPTS_VALID(opts, bpf_object_open_opts))
7226 return ERR_PTR(-EINVAL);
7228 obj_name = OPTS_GET(opts, object_name, NULL);
7231 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7232 (unsigned long)obj_buf,
7233 (unsigned long)obj_buf_sz);
7234 obj_name = tmp_name;
7237 pr_debug("loading object '%s' from buffer\n", obj_name);
7240 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7241 log_size = OPTS_GET(opts, kernel_log_size, 0);
7242 log_level = OPTS_GET(opts, kernel_log_level, 0);
7243 if (log_size > UINT_MAX)
7244 return ERR_PTR(-EINVAL);
7245 if (log_size && !log_buf)
7246 return ERR_PTR(-EINVAL);
7248 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7252 obj->log_buf = log_buf;
7253 obj->log_size = log_size;
7254 obj->log_level = log_level;
7256 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7258 if (strlen(btf_tmp_path) >= PATH_MAX) {
7259 err = -ENAMETOOLONG;
7262 obj->btf_custom_path = strdup(btf_tmp_path);
7263 if (!obj->btf_custom_path) {
7269 kconfig = OPTS_GET(opts, kconfig, NULL);
7271 obj->kconfig = strdup(kconfig);
7272 if (!obj->kconfig) {
7278 err = bpf_object__elf_init(obj);
7279 err = err ? : bpf_object__check_endianness(obj);
7280 err = err ? : bpf_object__elf_collect(obj);
7281 err = err ? : bpf_object__collect_externs(obj);
7282 err = err ? : bpf_object_fixup_btf(obj);
7283 err = err ? : bpf_object__init_maps(obj, opts);
7284 err = err ? : bpf_object_init_progs(obj, opts);
7285 err = err ? : bpf_object__collect_relos(obj);
7289 bpf_object__elf_finish(obj);
7293 bpf_object__close(obj);
7294 return ERR_PTR(err);
7298 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7301 return libbpf_err_ptr(-EINVAL);
7303 pr_debug("loading %s\n", path);
7305 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7308 struct bpf_object *bpf_object__open(const char *path)
7310 return bpf_object__open_file(path, NULL);
7314 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7315 const struct bpf_object_open_opts *opts)
7317 if (!obj_buf || obj_buf_sz == 0)
7318 return libbpf_err_ptr(-EINVAL);
7320 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7323 static int bpf_object_unload(struct bpf_object *obj)
7328 return libbpf_err(-EINVAL);
7330 for (i = 0; i < obj->nr_maps; i++) {
7331 zclose(obj->maps[i].fd);
7332 if (obj->maps[i].st_ops)
7333 zfree(&obj->maps[i].st_ops->kern_vdata);
7336 for (i = 0; i < obj->nr_programs; i++)
7337 bpf_program__unload(&obj->programs[i]);
7342 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7346 bpf_object__for_each_map(m, obj) {
7347 if (!bpf_map__is_internal(m))
7349 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7350 m->def.map_flags &= ~BPF_F_MMAPABLE;
7356 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7358 char sym_type, sym_name[500];
7359 unsigned long long sym_addr;
7363 f = fopen("/proc/kallsyms", "r");
7366 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7371 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7372 &sym_addr, &sym_type, sym_name);
7373 if (ret == EOF && feof(f))
7376 pr_warn("failed to read kallsyms entry: %d\n", ret);
7381 err = cb(sym_addr, sym_type, sym_name, ctx);
7390 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7391 const char *sym_name, void *ctx)
7393 struct bpf_object *obj = ctx;
7394 const struct btf_type *t;
7395 struct extern_desc *ext;
7397 ext = find_extern_by_name(obj, sym_name);
7398 if (!ext || ext->type != EXT_KSYM)
7401 t = btf__type_by_id(obj->btf, ext->btf_id);
7405 if (ext->is_set && ext->ksym.addr != sym_addr) {
7406 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7407 sym_name, ext->ksym.addr, sym_addr);
7412 ext->ksym.addr = sym_addr;
7413 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7418 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7420 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7423 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7424 __u16 kind, struct btf **res_btf,
7425 struct module_btf **res_mod_btf)
7427 struct module_btf *mod_btf;
7431 btf = obj->btf_vmlinux;
7433 id = btf__find_by_name_kind(btf, ksym_name, kind);
7435 if (id == -ENOENT) {
7436 err = load_module_btfs(obj);
7440 for (i = 0; i < obj->btf_module_cnt; i++) {
7441 /* we assume module_btf's BTF FD is always >0 */
7442 mod_btf = &obj->btf_modules[i];
7444 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7453 *res_mod_btf = mod_btf;
7457 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7458 struct extern_desc *ext)
7460 const struct btf_type *targ_var, *targ_type;
7461 __u32 targ_type_id, local_type_id;
7462 struct module_btf *mod_btf = NULL;
7463 const char *targ_var_name;
7464 struct btf *btf = NULL;
7467 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7469 if (id == -ESRCH && ext->is_weak)
7471 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7476 /* find local type_id */
7477 local_type_id = ext->ksym.type_id;
7479 /* find target type_id */
7480 targ_var = btf__type_by_id(btf, id);
7481 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7482 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7484 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7487 const struct btf_type *local_type;
7488 const char *targ_name, *local_name;
7490 local_type = btf__type_by_id(obj->btf, local_type_id);
7491 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7492 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7494 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7495 ext->name, local_type_id,
7496 btf_kind_str(local_type), local_name, targ_type_id,
7497 btf_kind_str(targ_type), targ_name);
7502 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7503 ext->ksym.kernel_btf_id = id;
7504 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7505 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7510 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7511 struct extern_desc *ext)
7513 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7514 struct module_btf *mod_btf = NULL;
7515 const struct btf_type *kern_func;
7516 struct btf *kern_btf = NULL;
7519 local_func_proto_id = ext->ksym.type_id;
7521 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7523 if (kfunc_id == -ESRCH && ext->is_weak)
7525 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7530 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7531 kfunc_proto_id = kern_func->type;
7533 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7534 kern_btf, kfunc_proto_id);
7536 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7537 ext->name, local_func_proto_id, kfunc_proto_id);
7541 /* set index for module BTF fd in fd_array, if unset */
7542 if (mod_btf && !mod_btf->fd_array_idx) {
7543 /* insn->off is s16 */
7544 if (obj->fd_array_cnt == INT16_MAX) {
7545 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7546 ext->name, mod_btf->fd_array_idx);
7549 /* Cannot use index 0 for module BTF fd */
7550 if (!obj->fd_array_cnt)
7551 obj->fd_array_cnt = 1;
7553 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7554 obj->fd_array_cnt + 1);
7557 mod_btf->fd_array_idx = obj->fd_array_cnt;
7558 /* we assume module BTF FD is always >0 */
7559 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7563 ext->ksym.kernel_btf_id = kfunc_id;
7564 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7565 /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7566 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7567 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7568 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7570 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7571 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7572 ext->name, kfunc_id);
7577 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7579 const struct btf_type *t;
7580 struct extern_desc *ext;
7583 for (i = 0; i < obj->nr_extern; i++) {
7584 ext = &obj->externs[i];
7585 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7588 if (obj->gen_loader) {
7590 ext->ksym.kernel_btf_obj_fd = 0;
7591 ext->ksym.kernel_btf_id = 0;
7594 t = btf__type_by_id(obj->btf, ext->btf_id);
7596 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7598 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7605 static int bpf_object__resolve_externs(struct bpf_object *obj,
7606 const char *extra_kconfig)
7608 bool need_config = false, need_kallsyms = false;
7609 bool need_vmlinux_btf = false;
7610 struct extern_desc *ext;
7611 void *kcfg_data = NULL;
7614 if (obj->nr_extern == 0)
7617 if (obj->kconfig_map_idx >= 0)
7618 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7620 for (i = 0; i < obj->nr_extern; i++) {
7621 ext = &obj->externs[i];
7623 if (ext->type == EXT_KSYM) {
7624 if (ext->ksym.type_id)
7625 need_vmlinux_btf = true;
7627 need_kallsyms = true;
7629 } else if (ext->type == EXT_KCFG) {
7630 void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7633 /* Kconfig externs need actual /proc/config.gz */
7634 if (str_has_pfx(ext->name, "CONFIG_")) {
7639 /* Virtual kcfg externs are customly handled by libbpf */
7640 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7641 value = get_kernel_version();
7643 pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7646 } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7647 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7648 } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7649 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7650 } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7651 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7652 * __kconfig externs, where LINUX_ ones are virtual and filled out
7653 * customly by libbpf (their values don't come from Kconfig).
7654 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7655 * __weak, it defaults to zero value, just like for CONFIG_xxx
7658 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7662 err = set_kcfg_value_num(ext, ext_ptr, value);
7665 pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7666 ext->name, (long long)value);
7668 pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7672 if (need_config && extra_kconfig) {
7673 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7676 need_config = false;
7677 for (i = 0; i < obj->nr_extern; i++) {
7678 ext = &obj->externs[i];
7679 if (ext->type == EXT_KCFG && !ext->is_set) {
7686 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7690 if (need_kallsyms) {
7691 err = bpf_object__read_kallsyms_file(obj);
7695 if (need_vmlinux_btf) {
7696 err = bpf_object__resolve_ksyms_btf_id(obj);
7700 for (i = 0; i < obj->nr_extern; i++) {
7701 ext = &obj->externs[i];
7703 if (!ext->is_set && !ext->is_weak) {
7704 pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7706 } else if (!ext->is_set) {
7707 pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7715 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7717 struct bpf_struct_ops *st_ops;
7720 st_ops = map->st_ops;
7721 for (i = 0; i < btf_vlen(st_ops->type); i++) {
7722 struct bpf_program *prog = st_ops->progs[i];
7729 prog_fd = bpf_program__fd(prog);
7730 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7731 *(unsigned long *)kern_data = prog_fd;
7735 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7739 for (i = 0; i < obj->nr_maps; i++)
7740 if (bpf_map__is_struct_ops(&obj->maps[i]))
7741 bpf_map_prepare_vdata(&obj->maps[i]);
7746 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7751 return libbpf_err(-EINVAL);
7754 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7755 return libbpf_err(-EINVAL);
7758 if (obj->gen_loader)
7759 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7761 err = bpf_object__probe_loading(obj);
7762 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7763 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7764 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7765 err = err ? : bpf_object__sanitize_maps(obj);
7766 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7767 err = err ? : bpf_object__create_maps(obj);
7768 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7769 err = err ? : bpf_object__load_progs(obj, extra_log_level);
7770 err = err ? : bpf_object_init_prog_arrays(obj);
7771 err = err ? : bpf_object_prepare_struct_ops(obj);
7773 if (obj->gen_loader) {
7776 btf__set_fd(obj->btf, -1);
7777 for (i = 0; i < obj->nr_maps; i++)
7778 obj->maps[i].fd = -1;
7780 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7783 /* clean up fd_array */
7784 zfree(&obj->fd_array);
7786 /* clean up module BTFs */
7787 for (i = 0; i < obj->btf_module_cnt; i++) {
7788 close(obj->btf_modules[i].fd);
7789 btf__free(obj->btf_modules[i].btf);
7790 free(obj->btf_modules[i].name);
7792 free(obj->btf_modules);
7794 /* clean up vmlinux BTF */
7795 btf__free(obj->btf_vmlinux);
7796 obj->btf_vmlinux = NULL;
7798 obj->loaded = true; /* doesn't matter if successfully or not */
7805 /* unpin any maps that were auto-pinned during load */
7806 for (i = 0; i < obj->nr_maps; i++)
7807 if (obj->maps[i].pinned && !obj->maps[i].reused)
7808 bpf_map__unpin(&obj->maps[i], NULL);
7810 bpf_object_unload(obj);
7811 pr_warn("failed to load object '%s'\n", obj->path);
7812 return libbpf_err(err);
7815 int bpf_object__load(struct bpf_object *obj)
7817 return bpf_object_load(obj, 0, NULL);
7820 static int make_parent_dir(const char *path)
7822 char *cp, errmsg[STRERR_BUFSIZE];
7826 dname = strdup(path);
7830 dir = dirname(dname);
7831 if (mkdir(dir, 0700) && errno != EEXIST)
7836 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7837 pr_warn("failed to mkdir %s: %s\n", path, cp);
7842 static int check_path(const char *path)
7844 char *cp, errmsg[STRERR_BUFSIZE];
7845 struct statfs st_fs;
7852 dname = strdup(path);
7856 dir = dirname(dname);
7857 if (statfs(dir, &st_fs)) {
7858 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7859 pr_warn("failed to statfs %s: %s\n", dir, cp);
7864 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7865 pr_warn("specified path %s is not on BPF FS\n", path);
7872 int bpf_program__pin(struct bpf_program *prog, const char *path)
7874 char *cp, errmsg[STRERR_BUFSIZE];
7878 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7879 return libbpf_err(-EINVAL);
7882 err = make_parent_dir(path);
7884 return libbpf_err(err);
7886 err = check_path(path);
7888 return libbpf_err(err);
7890 if (bpf_obj_pin(prog->fd, path)) {
7892 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7893 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7894 return libbpf_err(err);
7897 pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7901 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7906 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7907 return libbpf_err(-EINVAL);
7910 err = check_path(path);
7912 return libbpf_err(err);
7916 return libbpf_err(-errno);
7918 pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7922 int bpf_map__pin(struct bpf_map *map, const char *path)
7924 char *cp, errmsg[STRERR_BUFSIZE];
7928 pr_warn("invalid map pointer\n");
7929 return libbpf_err(-EINVAL);
7932 if (map->pin_path) {
7933 if (path && strcmp(path, map->pin_path)) {
7934 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7935 bpf_map__name(map), map->pin_path, path);
7936 return libbpf_err(-EINVAL);
7937 } else if (map->pinned) {
7938 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7939 bpf_map__name(map), map->pin_path);
7944 pr_warn("missing a path to pin map '%s' at\n",
7945 bpf_map__name(map));
7946 return libbpf_err(-EINVAL);
7947 } else if (map->pinned) {
7948 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7949 return libbpf_err(-EEXIST);
7952 map->pin_path = strdup(path);
7953 if (!map->pin_path) {
7959 err = make_parent_dir(map->pin_path);
7961 return libbpf_err(err);
7963 err = check_path(map->pin_path);
7965 return libbpf_err(err);
7967 if (bpf_obj_pin(map->fd, map->pin_path)) {
7973 pr_debug("pinned map '%s'\n", map->pin_path);
7978 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7979 pr_warn("failed to pin map: %s\n", cp);
7980 return libbpf_err(err);
7983 int bpf_map__unpin(struct bpf_map *map, const char *path)
7988 pr_warn("invalid map pointer\n");
7989 return libbpf_err(-EINVAL);
7992 if (map->pin_path) {
7993 if (path && strcmp(path, map->pin_path)) {
7994 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7995 bpf_map__name(map), map->pin_path, path);
7996 return libbpf_err(-EINVAL);
7998 path = map->pin_path;
8000 pr_warn("no path to unpin map '%s' from\n",
8001 bpf_map__name(map));
8002 return libbpf_err(-EINVAL);
8005 err = check_path(path);
8007 return libbpf_err(err);
8011 return libbpf_err(-errno);
8013 map->pinned = false;
8014 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8019 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8026 return libbpf_err(-errno);
8029 free(map->pin_path);
8030 map->pin_path = new;
8034 __alias(bpf_map__pin_path)
8035 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8037 const char *bpf_map__pin_path(const struct bpf_map *map)
8039 return map->pin_path;
8042 bool bpf_map__is_pinned(const struct bpf_map *map)
8047 static void sanitize_pin_path(char *s)
8049 /* bpffs disallows periods in path names */
8057 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8059 struct bpf_map *map;
8063 return libbpf_err(-ENOENT);
8066 pr_warn("object not yet loaded; load it first\n");
8067 return libbpf_err(-ENOENT);
8070 bpf_object__for_each_map(map, obj) {
8071 char *pin_path = NULL;
8074 if (!map->autocreate)
8078 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8080 goto err_unpin_maps;
8081 sanitize_pin_path(buf);
8083 } else if (!map->pin_path) {
8087 err = bpf_map__pin(map, pin_path);
8089 goto err_unpin_maps;
8095 while ((map = bpf_object__prev_map(obj, map))) {
8099 bpf_map__unpin(map, NULL);
8102 return libbpf_err(err);
8105 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8107 struct bpf_map *map;
8111 return libbpf_err(-ENOENT);
8113 bpf_object__for_each_map(map, obj) {
8114 char *pin_path = NULL;
8118 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8120 return libbpf_err(err);
8121 sanitize_pin_path(buf);
8123 } else if (!map->pin_path) {
8127 err = bpf_map__unpin(map, pin_path);
8129 return libbpf_err(err);
8135 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8137 struct bpf_program *prog;
8142 return libbpf_err(-ENOENT);
8145 pr_warn("object not yet loaded; load it first\n");
8146 return libbpf_err(-ENOENT);
8149 bpf_object__for_each_program(prog, obj) {
8150 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8152 goto err_unpin_programs;
8154 err = bpf_program__pin(prog, buf);
8156 goto err_unpin_programs;
8162 while ((prog = bpf_object__prev_program(obj, prog))) {
8163 if (pathname_concat(buf, sizeof(buf), path, prog->name))
8166 bpf_program__unpin(prog, buf);
8169 return libbpf_err(err);
8172 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8174 struct bpf_program *prog;
8178 return libbpf_err(-ENOENT);
8180 bpf_object__for_each_program(prog, obj) {
8183 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8185 return libbpf_err(err);
8187 err = bpf_program__unpin(prog, buf);
8189 return libbpf_err(err);
8195 int bpf_object__pin(struct bpf_object *obj, const char *path)
8199 err = bpf_object__pin_maps(obj, path);
8201 return libbpf_err(err);
8203 err = bpf_object__pin_programs(obj, path);
8205 bpf_object__unpin_maps(obj, path);
8206 return libbpf_err(err);
8212 static void bpf_map__destroy(struct bpf_map *map)
8214 if (map->inner_map) {
8215 bpf_map__destroy(map->inner_map);
8216 zfree(&map->inner_map);
8219 zfree(&map->init_slots);
8220 map->init_slots_sz = 0;
8223 munmap(map->mmaped, bpf_map_mmap_sz(map));
8228 zfree(&map->st_ops->data);
8229 zfree(&map->st_ops->progs);
8230 zfree(&map->st_ops->kern_func_off);
8231 zfree(&map->st_ops);
8235 zfree(&map->real_name);
8236 zfree(&map->pin_path);
8242 void bpf_object__close(struct bpf_object *obj)
8246 if (IS_ERR_OR_NULL(obj))
8249 usdt_manager_free(obj->usdt_man);
8250 obj->usdt_man = NULL;
8252 bpf_gen__free(obj->gen_loader);
8253 bpf_object__elf_finish(obj);
8254 bpf_object_unload(obj);
8255 btf__free(obj->btf);
8256 btf_ext__free(obj->btf_ext);
8258 for (i = 0; i < obj->nr_maps; i++)
8259 bpf_map__destroy(&obj->maps[i]);
8261 zfree(&obj->btf_custom_path);
8262 zfree(&obj->kconfig);
8263 zfree(&obj->externs);
8269 if (obj->programs && obj->nr_programs) {
8270 for (i = 0; i < obj->nr_programs; i++)
8271 bpf_program__exit(&obj->programs[i]);
8273 zfree(&obj->programs);
8278 const char *bpf_object__name(const struct bpf_object *obj)
8280 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8283 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8285 return obj ? obj->kern_version : 0;
8288 struct btf *bpf_object__btf(const struct bpf_object *obj)
8290 return obj ? obj->btf : NULL;
8293 int bpf_object__btf_fd(const struct bpf_object *obj)
8295 return obj->btf ? btf__fd(obj->btf) : -1;
8298 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8301 return libbpf_err(-EINVAL);
8303 obj->kern_version = kern_version;
8308 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8310 struct bpf_gen *gen;
8314 if (!OPTS_VALID(opts, gen_loader_opts))
8316 gen = calloc(sizeof(*gen), 1);
8320 obj->gen_loader = gen;
8324 static struct bpf_program *
8325 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8328 size_t nr_programs = obj->nr_programs;
8335 /* Iter from the beginning */
8336 return forward ? &obj->programs[0] :
8337 &obj->programs[nr_programs - 1];
8339 if (p->obj != obj) {
8340 pr_warn("error: program handler doesn't match object\n");
8341 return errno = EINVAL, NULL;
8344 idx = (p - obj->programs) + (forward ? 1 : -1);
8345 if (idx >= obj->nr_programs || idx < 0)
8347 return &obj->programs[idx];
8350 struct bpf_program *
8351 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8353 struct bpf_program *prog = prev;
8356 prog = __bpf_program__iter(prog, obj, true);
8357 } while (prog && prog_is_subprog(obj, prog));
8362 struct bpf_program *
8363 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8365 struct bpf_program *prog = next;
8368 prog = __bpf_program__iter(prog, obj, false);
8369 } while (prog && prog_is_subprog(obj, prog));
8374 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8376 prog->prog_ifindex = ifindex;
8379 const char *bpf_program__name(const struct bpf_program *prog)
8384 const char *bpf_program__section_name(const struct bpf_program *prog)
8386 return prog->sec_name;
8389 bool bpf_program__autoload(const struct bpf_program *prog)
8391 return prog->autoload;
8394 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8396 if (prog->obj->loaded)
8397 return libbpf_err(-EINVAL);
8399 prog->autoload = autoload;
8403 bool bpf_program__autoattach(const struct bpf_program *prog)
8405 return prog->autoattach;
8408 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8410 prog->autoattach = autoattach;
8413 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8418 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8420 return prog->insns_cnt;
8423 int bpf_program__set_insns(struct bpf_program *prog,
8424 struct bpf_insn *new_insns, size_t new_insn_cnt)
8426 struct bpf_insn *insns;
8428 if (prog->obj->loaded)
8431 insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8433 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8436 memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8438 prog->insns = insns;
8439 prog->insns_cnt = new_insn_cnt;
8443 int bpf_program__fd(const struct bpf_program *prog)
8446 return libbpf_err(-EINVAL);
8449 return libbpf_err(-ENOENT);
8454 __alias(bpf_program__type)
8455 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8457 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8462 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8464 if (prog->obj->loaded)
8465 return libbpf_err(-EBUSY);
8471 __alias(bpf_program__expected_attach_type)
8472 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8474 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8476 return prog->expected_attach_type;
8479 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8480 enum bpf_attach_type type)
8482 if (prog->obj->loaded)
8483 return libbpf_err(-EBUSY);
8485 prog->expected_attach_type = type;
8489 __u32 bpf_program__flags(const struct bpf_program *prog)
8491 return prog->prog_flags;
8494 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8496 if (prog->obj->loaded)
8497 return libbpf_err(-EBUSY);
8499 prog->prog_flags = flags;
8503 __u32 bpf_program__log_level(const struct bpf_program *prog)
8505 return prog->log_level;
8508 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8510 if (prog->obj->loaded)
8511 return libbpf_err(-EBUSY);
8513 prog->log_level = log_level;
8517 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8519 *log_size = prog->log_size;
8520 return prog->log_buf;
8523 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8525 if (log_size && !log_buf)
8527 if (prog->log_size > UINT_MAX)
8529 if (prog->obj->loaded)
8532 prog->log_buf = log_buf;
8533 prog->log_size = log_size;
8537 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8538 .sec = (char *)sec_pfx, \
8539 .prog_type = BPF_PROG_TYPE_##ptype, \
8540 .expected_attach_type = atype, \
8541 .cookie = (long)(flags), \
8542 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
8546 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8547 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8548 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8549 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8550 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8551 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8552 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8553 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8554 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8555 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8557 static const struct bpf_sec_def section_defs[] = {
8558 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8559 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8560 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8561 SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8562 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8563 SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8564 SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8565 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8566 SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8567 SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8568 SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8569 SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8570 SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8571 SEC_DEF("usdt+", KPROBE, 0, SEC_NONE, attach_usdt),
8572 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
8573 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE),
8574 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE),
8575 SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8576 SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8577 SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8578 SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8579 SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8580 SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8581 SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8582 SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8583 SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8584 SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8585 SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8586 SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8587 SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8588 SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8589 SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8590 SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8591 SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8592 SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8593 SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8594 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8595 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8596 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8597 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8598 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8599 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
8600 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8601 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8602 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8603 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8604 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8605 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8606 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8607 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8608 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8609 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8610 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8611 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8612 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8613 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8614 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8615 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8616 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8617 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8618 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8619 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8620 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8621 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8622 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8623 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8624 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8625 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8626 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8627 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8628 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8629 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8630 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8631 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8632 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8633 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8634 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8635 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8636 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8637 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8638 SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
8639 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8642 static size_t custom_sec_def_cnt;
8643 static struct bpf_sec_def *custom_sec_defs;
8644 static struct bpf_sec_def custom_fallback_def;
8645 static bool has_custom_fallback_def;
8647 static int last_custom_sec_def_handler_id;
8649 int libbpf_register_prog_handler(const char *sec,
8650 enum bpf_prog_type prog_type,
8651 enum bpf_attach_type exp_attach_type,
8652 const struct libbpf_prog_handler_opts *opts)
8654 struct bpf_sec_def *sec_def;
8656 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8657 return libbpf_err(-EINVAL);
8659 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8660 return libbpf_err(-E2BIG);
8663 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8666 return libbpf_err(-ENOMEM);
8668 custom_sec_defs = sec_def;
8669 sec_def = &custom_sec_defs[custom_sec_def_cnt];
8671 if (has_custom_fallback_def)
8672 return libbpf_err(-EBUSY);
8674 sec_def = &custom_fallback_def;
8677 sec_def->sec = sec ? strdup(sec) : NULL;
8678 if (sec && !sec_def->sec)
8679 return libbpf_err(-ENOMEM);
8681 sec_def->prog_type = prog_type;
8682 sec_def->expected_attach_type = exp_attach_type;
8683 sec_def->cookie = OPTS_GET(opts, cookie, 0);
8685 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8686 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8687 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8689 sec_def->handler_id = ++last_custom_sec_def_handler_id;
8692 custom_sec_def_cnt++;
8694 has_custom_fallback_def = true;
8696 return sec_def->handler_id;
8699 int libbpf_unregister_prog_handler(int handler_id)
8701 struct bpf_sec_def *sec_defs;
8704 if (handler_id <= 0)
8705 return libbpf_err(-EINVAL);
8707 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8708 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8709 has_custom_fallback_def = false;
8713 for (i = 0; i < custom_sec_def_cnt; i++) {
8714 if (custom_sec_defs[i].handler_id == handler_id)
8718 if (i == custom_sec_def_cnt)
8719 return libbpf_err(-ENOENT);
8721 free(custom_sec_defs[i].sec);
8722 for (i = i + 1; i < custom_sec_def_cnt; i++)
8723 custom_sec_defs[i - 1] = custom_sec_defs[i];
8724 custom_sec_def_cnt--;
8726 /* try to shrink the array, but it's ok if we couldn't */
8727 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8729 custom_sec_defs = sec_defs;
8734 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8736 size_t len = strlen(sec_def->sec);
8738 /* "type/" always has to have proper SEC("type/extras") form */
8739 if (sec_def->sec[len - 1] == '/') {
8740 if (str_has_pfx(sec_name, sec_def->sec))
8745 /* "type+" means it can be either exact SEC("type") or
8746 * well-formed SEC("type/extras") with proper '/' separator
8748 if (sec_def->sec[len - 1] == '+') {
8750 /* not even a prefix */
8751 if (strncmp(sec_name, sec_def->sec, len) != 0)
8753 /* exact match or has '/' separator */
8754 if (sec_name[len] == '\0' || sec_name[len] == '/')
8759 return strcmp(sec_name, sec_def->sec) == 0;
8762 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8764 const struct bpf_sec_def *sec_def;
8767 n = custom_sec_def_cnt;
8768 for (i = 0; i < n; i++) {
8769 sec_def = &custom_sec_defs[i];
8770 if (sec_def_matches(sec_def, sec_name))
8774 n = ARRAY_SIZE(section_defs);
8775 for (i = 0; i < n; i++) {
8776 sec_def = §ion_defs[i];
8777 if (sec_def_matches(sec_def, sec_name))
8781 if (has_custom_fallback_def)
8782 return &custom_fallback_def;
8787 #define MAX_TYPE_NAME_SIZE 32
8789 static char *libbpf_get_type_names(bool attach_type)
8791 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8799 /* Forge string buf with all available names */
8800 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8801 const struct bpf_sec_def *sec_def = §ion_defs[i];
8804 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8807 if (!(sec_def->cookie & SEC_ATTACHABLE))
8811 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8816 strcat(buf, section_defs[i].sec);
8822 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8823 enum bpf_attach_type *expected_attach_type)
8825 const struct bpf_sec_def *sec_def;
8829 return libbpf_err(-EINVAL);
8831 sec_def = find_sec_def(name);
8833 *prog_type = sec_def->prog_type;
8834 *expected_attach_type = sec_def->expected_attach_type;
8838 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8839 type_names = libbpf_get_type_names(false);
8840 if (type_names != NULL) {
8841 pr_debug("supported section(type) names are:%s\n", type_names);
8845 return libbpf_err(-ESRCH);
8848 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8850 if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8853 return attach_type_name[t];
8856 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8858 if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8861 return link_type_name[t];
8864 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8866 if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8869 return map_type_name[t];
8872 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8874 if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8877 return prog_type_name[t];
8880 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8884 struct bpf_map *map;
8887 for (i = 0; i < obj->nr_maps; i++) {
8888 map = &obj->maps[i];
8889 if (!bpf_map__is_struct_ops(map))
8891 if (map->sec_idx == sec_idx &&
8892 map->sec_offset <= offset &&
8893 offset - map->sec_offset < map->def.value_size)
8900 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8901 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8902 Elf64_Shdr *shdr, Elf_Data *data)
8904 const struct btf_member *member;
8905 struct bpf_struct_ops *st_ops;
8906 struct bpf_program *prog;
8907 unsigned int shdr_idx;
8908 const struct btf *btf;
8909 struct bpf_map *map;
8910 unsigned int moff, insn_idx;
8918 nrels = shdr->sh_size / shdr->sh_entsize;
8919 for (i = 0; i < nrels; i++) {
8920 rel = elf_rel_by_idx(data, i);
8922 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8923 return -LIBBPF_ERRNO__FORMAT;
8926 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8928 pr_warn("struct_ops reloc: symbol %zx not found\n",
8929 (size_t)ELF64_R_SYM(rel->r_info));
8930 return -LIBBPF_ERRNO__FORMAT;
8933 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8934 map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
8936 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8937 (size_t)rel->r_offset);
8941 moff = rel->r_offset - map->sec_offset;
8942 shdr_idx = sym->st_shndx;
8943 st_ops = map->st_ops;
8944 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",
8946 (long long)(rel->r_info >> 32),
8947 (long long)sym->st_value,
8948 shdr_idx, (size_t)rel->r_offset,
8949 map->sec_offset, sym->st_name, name);
8951 if (shdr_idx >= SHN_LORESERVE) {
8952 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8953 map->name, (size_t)rel->r_offset, shdr_idx);
8954 return -LIBBPF_ERRNO__RELOC;
8956 if (sym->st_value % BPF_INSN_SZ) {
8957 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8958 map->name, (unsigned long long)sym->st_value);
8959 return -LIBBPF_ERRNO__FORMAT;
8961 insn_idx = sym->st_value / BPF_INSN_SZ;
8963 member = find_member_by_offset(st_ops->type, moff * 8);
8965 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8969 member_idx = member - btf_members(st_ops->type);
8970 name = btf__name_by_offset(btf, member->name_off);
8972 if (!resolve_func_ptr(btf, member->type, NULL)) {
8973 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8978 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8980 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8981 map->name, shdr_idx, name);
8985 /* prevent the use of BPF prog with invalid type */
8986 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8987 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8988 map->name, prog->name);
8992 /* if we haven't yet processed this BPF program, record proper
8993 * attach_btf_id and member_idx
8995 if (!prog->attach_btf_id) {
8996 prog->attach_btf_id = st_ops->type_id;
8997 prog->expected_attach_type = member_idx;
9000 /* struct_ops BPF prog can be re-used between multiple
9001 * .struct_ops & .struct_ops.link as long as it's the
9002 * same struct_ops struct definition and the same
9003 * function pointer field
9005 if (prog->attach_btf_id != st_ops->type_id ||
9006 prog->expected_attach_type != member_idx) {
9007 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",
9008 map->name, prog->name, prog->sec_name, prog->type,
9009 prog->attach_btf_id, prog->expected_attach_type, name);
9013 st_ops->progs[member_idx] = prog;
9019 #define BTF_TRACE_PREFIX "btf_trace_"
9020 #define BTF_LSM_PREFIX "bpf_lsm_"
9021 #define BTF_ITER_PREFIX "bpf_iter_"
9022 #define BTF_MAX_NAME_SIZE 128
9024 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9025 const char **prefix, int *kind)
9027 switch (attach_type) {
9028 case BPF_TRACE_RAW_TP:
9029 *prefix = BTF_TRACE_PREFIX;
9030 *kind = BTF_KIND_TYPEDEF;
9033 case BPF_LSM_CGROUP:
9034 *prefix = BTF_LSM_PREFIX;
9035 *kind = BTF_KIND_FUNC;
9037 case BPF_TRACE_ITER:
9038 *prefix = BTF_ITER_PREFIX;
9039 *kind = BTF_KIND_FUNC;
9043 *kind = BTF_KIND_FUNC;
9047 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9048 const char *name, __u32 kind)
9050 char btf_type_name[BTF_MAX_NAME_SIZE];
9053 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9054 "%s%s", prefix, name);
9055 /* snprintf returns the number of characters written excluding the
9056 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9057 * indicates truncation.
9059 if (ret < 0 || ret >= sizeof(btf_type_name))
9060 return -ENAMETOOLONG;
9061 return btf__find_by_name_kind(btf, btf_type_name, kind);
9064 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9065 enum bpf_attach_type attach_type)
9070 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9071 return find_btf_by_prefix_kind(btf, prefix, name, kind);
9074 int libbpf_find_vmlinux_btf_id(const char *name,
9075 enum bpf_attach_type attach_type)
9080 btf = btf__load_vmlinux_btf();
9081 err = libbpf_get_error(btf);
9083 pr_warn("vmlinux BTF is not found\n");
9084 return libbpf_err(err);
9087 err = find_attach_btf_id(btf, name, attach_type);
9089 pr_warn("%s is not found in vmlinux BTF\n", name);
9092 return libbpf_err(err);
9095 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9097 struct bpf_prog_info info;
9098 __u32 info_len = sizeof(info);
9102 memset(&info, 0, info_len);
9103 err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9105 pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9106 attach_prog_fd, err);
9112 pr_warn("The target program doesn't have BTF\n");
9115 btf = btf__load_from_kernel_by_id(info.btf_id);
9116 err = libbpf_get_error(btf);
9118 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9121 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9124 pr_warn("%s is not found in prog's BTF\n", name);
9131 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9132 enum bpf_attach_type attach_type,
9133 int *btf_obj_fd, int *btf_type_id)
9137 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9139 *btf_obj_fd = 0; /* vmlinux BTF */
9146 ret = load_module_btfs(obj);
9150 for (i = 0; i < obj->btf_module_cnt; i++) {
9151 const struct module_btf *mod = &obj->btf_modules[i];
9153 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9155 *btf_obj_fd = mod->fd;
9168 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9169 int *btf_obj_fd, int *btf_type_id)
9171 enum bpf_attach_type attach_type = prog->expected_attach_type;
9172 __u32 attach_prog_fd = prog->attach_prog_fd;
9175 /* BPF program's BTF ID */
9176 if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9177 if (!attach_prog_fd) {
9178 pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9181 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9183 pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9184 prog->name, attach_prog_fd, attach_name, err);
9192 /* kernel/module BTF ID */
9193 if (prog->obj->gen_loader) {
9194 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9198 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9201 pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9202 prog->name, attach_name, err);
9208 int libbpf_attach_type_by_name(const char *name,
9209 enum bpf_attach_type *attach_type)
9212 const struct bpf_sec_def *sec_def;
9215 return libbpf_err(-EINVAL);
9217 sec_def = find_sec_def(name);
9219 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9220 type_names = libbpf_get_type_names(true);
9221 if (type_names != NULL) {
9222 pr_debug("attachable section(type) names are:%s\n", type_names);
9226 return libbpf_err(-EINVAL);
9229 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9230 return libbpf_err(-EINVAL);
9231 if (!(sec_def->cookie & SEC_ATTACHABLE))
9232 return libbpf_err(-EINVAL);
9234 *attach_type = sec_def->expected_attach_type;
9238 int bpf_map__fd(const struct bpf_map *map)
9240 return map ? map->fd : libbpf_err(-EINVAL);
9243 static bool map_uses_real_name(const struct bpf_map *map)
9245 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9246 * their user-visible name differs from kernel-visible name. Users see
9247 * such map's corresponding ELF section name as a map name.
9248 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9249 * maps to know which name has to be returned to the user.
9251 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9253 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9258 const char *bpf_map__name(const struct bpf_map *map)
9263 if (map_uses_real_name(map))
9264 return map->real_name;
9269 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9271 return map->def.type;
9274 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9277 return libbpf_err(-EBUSY);
9278 map->def.type = type;
9282 __u32 bpf_map__map_flags(const struct bpf_map *map)
9284 return map->def.map_flags;
9287 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9290 return libbpf_err(-EBUSY);
9291 map->def.map_flags = flags;
9295 __u64 bpf_map__map_extra(const struct bpf_map *map)
9297 return map->map_extra;
9300 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9303 return libbpf_err(-EBUSY);
9304 map->map_extra = map_extra;
9308 __u32 bpf_map__numa_node(const struct bpf_map *map)
9310 return map->numa_node;
9313 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9316 return libbpf_err(-EBUSY);
9317 map->numa_node = numa_node;
9321 __u32 bpf_map__key_size(const struct bpf_map *map)
9323 return map->def.key_size;
9326 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9329 return libbpf_err(-EBUSY);
9330 map->def.key_size = size;
9334 __u32 bpf_map__value_size(const struct bpf_map *map)
9336 return map->def.value_size;
9339 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9342 return libbpf_err(-EBUSY);
9343 map->def.value_size = size;
9347 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9349 return map ? map->btf_key_type_id : 0;
9352 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9354 return map ? map->btf_value_type_id : 0;
9357 int bpf_map__set_initial_value(struct bpf_map *map,
9358 const void *data, size_t size)
9360 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9361 size != map->def.value_size || map->fd >= 0)
9362 return libbpf_err(-EINVAL);
9364 memcpy(map->mmaped, data, size);
9368 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9372 *psize = map->def.value_size;
9376 bool bpf_map__is_internal(const struct bpf_map *map)
9378 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9381 __u32 bpf_map__ifindex(const struct bpf_map *map)
9383 return map->map_ifindex;
9386 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9389 return libbpf_err(-EBUSY);
9390 map->map_ifindex = ifindex;
9394 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9396 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9397 pr_warn("error: unsupported map type\n");
9398 return libbpf_err(-EINVAL);
9400 if (map->inner_map_fd != -1) {
9401 pr_warn("error: inner_map_fd already specified\n");
9402 return libbpf_err(-EINVAL);
9404 if (map->inner_map) {
9405 bpf_map__destroy(map->inner_map);
9406 zfree(&map->inner_map);
9408 map->inner_map_fd = fd;
9412 static struct bpf_map *
9413 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9416 struct bpf_map *s, *e;
9418 if (!obj || !obj->maps)
9419 return errno = EINVAL, NULL;
9422 e = obj->maps + obj->nr_maps;
9424 if ((m < s) || (m >= e)) {
9425 pr_warn("error in %s: map handler doesn't belong to object\n",
9427 return errno = EINVAL, NULL;
9430 idx = (m - obj->maps) + i;
9431 if (idx >= obj->nr_maps || idx < 0)
9433 return &obj->maps[idx];
9437 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9442 return __bpf_map__iter(prev, obj, 1);
9446 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9451 return obj->maps + obj->nr_maps - 1;
9454 return __bpf_map__iter(next, obj, -1);
9458 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9460 struct bpf_map *pos;
9462 bpf_object__for_each_map(pos, obj) {
9463 /* if it's a special internal map name (which always starts
9464 * with dot) then check if that special name matches the
9465 * real map name (ELF section name)
9467 if (name[0] == '.') {
9468 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9472 /* otherwise map name has to be an exact match */
9473 if (map_uses_real_name(pos)) {
9474 if (strcmp(pos->real_name, name) == 0)
9478 if (strcmp(pos->name, name) == 0)
9481 return errno = ENOENT, NULL;
9485 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9487 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9490 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9491 size_t value_sz, bool check_value_sz)
9496 if (map->def.key_size != key_sz) {
9497 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9498 map->name, key_sz, map->def.key_size);
9502 if (!check_value_sz)
9505 switch (map->def.type) {
9506 case BPF_MAP_TYPE_PERCPU_ARRAY:
9507 case BPF_MAP_TYPE_PERCPU_HASH:
9508 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9509 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9510 int num_cpu = libbpf_num_possible_cpus();
9511 size_t elem_sz = roundup(map->def.value_size, 8);
9513 if (value_sz != num_cpu * elem_sz) {
9514 pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9515 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9521 if (map->def.value_size != value_sz) {
9522 pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9523 map->name, value_sz, map->def.value_size);
9531 int bpf_map__lookup_elem(const struct bpf_map *map,
9532 const void *key, size_t key_sz,
9533 void *value, size_t value_sz, __u64 flags)
9537 err = validate_map_op(map, key_sz, value_sz, true);
9539 return libbpf_err(err);
9541 return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9544 int bpf_map__update_elem(const struct bpf_map *map,
9545 const void *key, size_t key_sz,
9546 const void *value, size_t value_sz, __u64 flags)
9550 err = validate_map_op(map, key_sz, value_sz, true);
9552 return libbpf_err(err);
9554 return bpf_map_update_elem(map->fd, key, value, flags);
9557 int bpf_map__delete_elem(const struct bpf_map *map,
9558 const void *key, size_t key_sz, __u64 flags)
9562 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9564 return libbpf_err(err);
9566 return bpf_map_delete_elem_flags(map->fd, key, flags);
9569 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9570 const void *key, size_t key_sz,
9571 void *value, size_t value_sz, __u64 flags)
9575 err = validate_map_op(map, key_sz, value_sz, true);
9577 return libbpf_err(err);
9579 return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9582 int bpf_map__get_next_key(const struct bpf_map *map,
9583 const void *cur_key, void *next_key, size_t key_sz)
9587 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9589 return libbpf_err(err);
9591 return bpf_map_get_next_key(map->fd, cur_key, next_key);
9594 long libbpf_get_error(const void *ptr)
9596 if (!IS_ERR_OR_NULL(ptr))
9600 errno = -PTR_ERR(ptr);
9602 /* If ptr == NULL, then errno should be already set by the failing
9603 * API, because libbpf never returns NULL on success and it now always
9604 * sets errno on error. So no extra errno handling for ptr == NULL
9610 /* Replace link's underlying BPF program with the new one */
9611 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9615 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9616 return libbpf_err_errno(ret);
9619 /* Release "ownership" of underlying BPF resource (typically, BPF program
9620 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9621 * link, when destructed through bpf_link__destroy() call won't attempt to
9622 * detach/unregisted that BPF resource. This is useful in situations where,
9623 * say, attached BPF program has to outlive userspace program that attached it
9624 * in the system. Depending on type of BPF program, though, there might be
9625 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9626 * exit of userspace program doesn't trigger automatic detachment and clean up
9627 * inside the kernel.
9629 void bpf_link__disconnect(struct bpf_link *link)
9631 link->disconnected = true;
9634 int bpf_link__destroy(struct bpf_link *link)
9638 if (IS_ERR_OR_NULL(link))
9641 if (!link->disconnected && link->detach)
9642 err = link->detach(link);
9644 free(link->pin_path);
9646 link->dealloc(link);
9650 return libbpf_err(err);
9653 int bpf_link__fd(const struct bpf_link *link)
9658 const char *bpf_link__pin_path(const struct bpf_link *link)
9660 return link->pin_path;
9663 static int bpf_link__detach_fd(struct bpf_link *link)
9665 return libbpf_err_errno(close(link->fd));
9668 struct bpf_link *bpf_link__open(const char *path)
9670 struct bpf_link *link;
9673 fd = bpf_obj_get(path);
9676 pr_warn("failed to open link at %s: %d\n", path, fd);
9677 return libbpf_err_ptr(fd);
9680 link = calloc(1, sizeof(*link));
9683 return libbpf_err_ptr(-ENOMEM);
9685 link->detach = &bpf_link__detach_fd;
9688 link->pin_path = strdup(path);
9689 if (!link->pin_path) {
9690 bpf_link__destroy(link);
9691 return libbpf_err_ptr(-ENOMEM);
9697 int bpf_link__detach(struct bpf_link *link)
9699 return bpf_link_detach(link->fd) ? -errno : 0;
9702 int bpf_link__pin(struct bpf_link *link, const char *path)
9707 return libbpf_err(-EBUSY);
9708 err = make_parent_dir(path);
9710 return libbpf_err(err);
9711 err = check_path(path);
9713 return libbpf_err(err);
9715 link->pin_path = strdup(path);
9716 if (!link->pin_path)
9717 return libbpf_err(-ENOMEM);
9719 if (bpf_obj_pin(link->fd, link->pin_path)) {
9721 zfree(&link->pin_path);
9722 return libbpf_err(err);
9725 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9729 int bpf_link__unpin(struct bpf_link *link)
9733 if (!link->pin_path)
9734 return libbpf_err(-EINVAL);
9736 err = unlink(link->pin_path);
9740 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9741 zfree(&link->pin_path);
9745 struct bpf_link_perf {
9746 struct bpf_link link;
9748 /* legacy kprobe support: keep track of probe identifier and type */
9749 char *legacy_probe_name;
9750 bool legacy_is_kprobe;
9751 bool legacy_is_retprobe;
9754 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9755 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9757 static int bpf_link_perf_detach(struct bpf_link *link)
9759 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9762 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9765 if (perf_link->perf_event_fd != link->fd)
9766 close(perf_link->perf_event_fd);
9769 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9770 if (perf_link->legacy_probe_name) {
9771 if (perf_link->legacy_is_kprobe) {
9772 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9773 perf_link->legacy_is_retprobe);
9775 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9776 perf_link->legacy_is_retprobe);
9783 static void bpf_link_perf_dealloc(struct bpf_link *link)
9785 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9787 free(perf_link->legacy_probe_name);
9791 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9792 const struct bpf_perf_event_opts *opts)
9794 char errmsg[STRERR_BUFSIZE];
9795 struct bpf_link_perf *link;
9796 int prog_fd, link_fd = -1, err;
9797 bool force_ioctl_attach;
9799 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9800 return libbpf_err_ptr(-EINVAL);
9803 pr_warn("prog '%s': invalid perf event FD %d\n",
9805 return libbpf_err_ptr(-EINVAL);
9807 prog_fd = bpf_program__fd(prog);
9809 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9811 return libbpf_err_ptr(-EINVAL);
9814 link = calloc(1, sizeof(*link));
9816 return libbpf_err_ptr(-ENOMEM);
9817 link->link.detach = &bpf_link_perf_detach;
9818 link->link.dealloc = &bpf_link_perf_dealloc;
9819 link->perf_event_fd = pfd;
9821 force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
9822 if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
9823 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9824 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9826 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9829 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9831 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9834 link->link.fd = link_fd;
9836 if (OPTS_GET(opts, bpf_cookie, 0)) {
9837 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9842 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9844 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9845 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9847 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9851 link->link.fd = pfd;
9853 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9855 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9856 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9865 return libbpf_err_ptr(err);
9868 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9870 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9874 * this function is expected to parse integer in the range of [0, 2^31-1] from
9875 * given file using scanf format string fmt. If actual parsed value is
9876 * negative, the result might be indistinguishable from error
9878 static int parse_uint_from_file(const char *file, const char *fmt)
9880 char buf[STRERR_BUFSIZE];
9884 f = fopen(file, "r");
9887 pr_debug("failed to open '%s': %s\n", file,
9888 libbpf_strerror_r(err, buf, sizeof(buf)));
9891 err = fscanf(f, fmt, &ret);
9893 err = err == EOF ? -EIO : -errno;
9894 pr_debug("failed to parse '%s': %s\n", file,
9895 libbpf_strerror_r(err, buf, sizeof(buf)));
9903 static int determine_kprobe_perf_type(void)
9905 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9907 return parse_uint_from_file(file, "%d\n");
9910 static int determine_uprobe_perf_type(void)
9912 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9914 return parse_uint_from_file(file, "%d\n");
9917 static int determine_kprobe_retprobe_bit(void)
9919 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9921 return parse_uint_from_file(file, "config:%d\n");
9924 static int determine_uprobe_retprobe_bit(void)
9926 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9928 return parse_uint_from_file(file, "config:%d\n");
9931 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9932 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9934 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9935 uint64_t offset, int pid, size_t ref_ctr_off)
9937 const size_t attr_sz = sizeof(struct perf_event_attr);
9938 struct perf_event_attr attr;
9939 char errmsg[STRERR_BUFSIZE];
9942 if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9945 memset(&attr, 0, attr_sz);
9947 type = uprobe ? determine_uprobe_perf_type()
9948 : determine_kprobe_perf_type();
9950 pr_warn("failed to determine %s perf type: %s\n",
9951 uprobe ? "uprobe" : "kprobe",
9952 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9956 int bit = uprobe ? determine_uprobe_retprobe_bit()
9957 : determine_kprobe_retprobe_bit();
9960 pr_warn("failed to determine %s retprobe bit: %s\n",
9961 uprobe ? "uprobe" : "kprobe",
9962 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9965 attr.config |= 1 << bit;
9967 attr.size = attr_sz;
9969 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9970 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9971 attr.config2 = offset; /* kprobe_addr or probe_offset */
9973 /* pid filter is meaningful only for uprobes */
9974 pfd = syscall(__NR_perf_event_open, &attr,
9975 pid < 0 ? -1 : pid /* pid */,
9976 pid == -1 ? 0 : -1 /* cpu */,
9977 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9978 return pfd >= 0 ? pfd : -errno;
9981 static int append_to_file(const char *file, const char *fmt, ...)
9988 n = vsnprintf(buf, sizeof(buf), fmt, ap);
9991 if (n < 0 || n >= sizeof(buf))
9994 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9998 if (write(fd, buf, n) < 0)
10005 #define DEBUGFS "/sys/kernel/debug/tracing"
10006 #define TRACEFS "/sys/kernel/tracing"
10008 static bool use_debugfs(void)
10010 static int has_debugfs = -1;
10012 if (has_debugfs < 0)
10013 has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10015 return has_debugfs == 1;
10018 static const char *tracefs_path(void)
10020 return use_debugfs() ? DEBUGFS : TRACEFS;
10023 static const char *tracefs_kprobe_events(void)
10025 return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10028 static const char *tracefs_uprobe_events(void)
10030 return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10033 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10034 const char *kfunc_name, size_t offset)
10036 static int index = 0;
10039 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10040 __sync_fetch_and_add(&index, 1));
10042 /* sanitize binary_path in the probe name */
10043 for (i = 0; buf[i]; i++) {
10044 if (!isalnum(buf[i]))
10049 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10050 const char *kfunc_name, size_t offset)
10052 return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10053 retprobe ? 'r' : 'p',
10054 retprobe ? "kretprobes" : "kprobes",
10055 probe_name, kfunc_name, offset);
10058 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10060 return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10061 retprobe ? "kretprobes" : "kprobes", probe_name);
10064 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10068 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10069 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10071 return parse_uint_from_file(file, "%d\n");
10074 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10075 const char *kfunc_name, size_t offset, int pid)
10077 const size_t attr_sz = sizeof(struct perf_event_attr);
10078 struct perf_event_attr attr;
10079 char errmsg[STRERR_BUFSIZE];
10080 int type, pfd, err;
10082 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10084 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10085 kfunc_name, offset,
10086 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10089 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10092 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10093 kfunc_name, offset,
10094 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10095 goto err_clean_legacy;
10098 memset(&attr, 0, attr_sz);
10099 attr.size = attr_sz;
10100 attr.config = type;
10101 attr.type = PERF_TYPE_TRACEPOINT;
10103 pfd = syscall(__NR_perf_event_open, &attr,
10104 pid < 0 ? -1 : pid, /* pid */
10105 pid == -1 ? 0 : -1, /* cpu */
10106 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10109 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10110 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10111 goto err_clean_legacy;
10116 /* Clear the newly added legacy kprobe_event */
10117 remove_kprobe_event_legacy(probe_name, retprobe);
10121 static const char *arch_specific_syscall_pfx(void)
10123 #if defined(__x86_64__)
10125 #elif defined(__i386__)
10127 #elif defined(__s390x__)
10129 #elif defined(__s390__)
10131 #elif defined(__arm__)
10133 #elif defined(__aarch64__)
10135 #elif defined(__mips__)
10137 #elif defined(__riscv)
10139 #elif defined(__powerpc__)
10141 #elif defined(__powerpc64__)
10142 return "powerpc64";
10148 static int probe_kern_syscall_wrapper(void)
10150 char syscall_name[64];
10151 const char *ksys_pfx;
10153 ksys_pfx = arch_specific_syscall_pfx();
10157 snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10159 if (determine_kprobe_perf_type() >= 0) {
10162 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10166 return pfd >= 0 ? 1 : 0;
10167 } else { /* legacy mode */
10168 char probe_name[128];
10170 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10171 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10174 (void)remove_kprobe_event_legacy(probe_name, false);
10180 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10181 const char *func_name,
10182 const struct bpf_kprobe_opts *opts)
10184 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10185 enum probe_attach_mode attach_mode;
10186 char errmsg[STRERR_BUFSIZE];
10187 char *legacy_probe = NULL;
10188 struct bpf_link *link;
10190 bool retprobe, legacy;
10193 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10194 return libbpf_err_ptr(-EINVAL);
10196 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10197 retprobe = OPTS_GET(opts, retprobe, false);
10198 offset = OPTS_GET(opts, offset, 0);
10199 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10201 legacy = determine_kprobe_perf_type() < 0;
10202 switch (attach_mode) {
10203 case PROBE_ATTACH_MODE_LEGACY:
10205 pe_opts.force_ioctl_attach = true;
10207 case PROBE_ATTACH_MODE_PERF:
10209 return libbpf_err_ptr(-ENOTSUP);
10210 pe_opts.force_ioctl_attach = true;
10212 case PROBE_ATTACH_MODE_LINK:
10213 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10214 return libbpf_err_ptr(-ENOTSUP);
10216 case PROBE_ATTACH_MODE_DEFAULT:
10219 return libbpf_err_ptr(-EINVAL);
10223 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10225 -1 /* pid */, 0 /* ref_ctr_off */);
10227 char probe_name[256];
10229 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10230 func_name, offset);
10232 legacy_probe = strdup(probe_name);
10234 return libbpf_err_ptr(-ENOMEM);
10236 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10237 offset, -1 /* pid */);
10241 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10242 prog->name, retprobe ? "kretprobe" : "kprobe",
10244 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10247 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10248 err = libbpf_get_error(link);
10251 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10252 prog->name, retprobe ? "kretprobe" : "kprobe",
10254 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10255 goto err_clean_legacy;
10258 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10260 perf_link->legacy_probe_name = legacy_probe;
10261 perf_link->legacy_is_kprobe = true;
10262 perf_link->legacy_is_retprobe = retprobe;
10269 remove_kprobe_event_legacy(legacy_probe, retprobe);
10271 free(legacy_probe);
10272 return libbpf_err_ptr(err);
10275 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10277 const char *func_name)
10279 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10280 .retprobe = retprobe,
10283 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10286 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10287 const char *syscall_name,
10288 const struct bpf_ksyscall_opts *opts)
10290 LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10291 char func_name[128];
10293 if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10294 return libbpf_err_ptr(-EINVAL);
10296 if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10297 /* arch_specific_syscall_pfx() should never return NULL here
10298 * because it is guarded by kernel_supports(). However, since
10299 * compiler does not know that we have an explicit conditional
10302 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10303 arch_specific_syscall_pfx() ? : "", syscall_name);
10305 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10308 kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10309 kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10311 return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10314 /* Adapted from perf/util/string.c */
10315 static bool glob_match(const char *str, const char *pat)
10317 while (*str && *pat && *pat != '*') {
10318 if (*pat == '?') { /* Matches any single character */
10328 /* Check wild card */
10330 while (*pat == '*')
10332 if (!*pat) /* Tail wild card matches all */
10335 if (glob_match(str++, pat))
10338 return !*str && !*pat;
10341 struct kprobe_multi_resolve {
10342 const char *pattern;
10343 unsigned long *addrs;
10349 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10350 const char *sym_name, void *ctx)
10352 struct kprobe_multi_resolve *res = ctx;
10355 if (!glob_match(sym_name, res->pattern))
10358 err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10363 res->addrs[res->cnt++] = (unsigned long) sym_addr;
10368 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10369 const char *pattern,
10370 const struct bpf_kprobe_multi_opts *opts)
10372 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10373 struct kprobe_multi_resolve res = {
10374 .pattern = pattern,
10376 struct bpf_link *link = NULL;
10377 char errmsg[STRERR_BUFSIZE];
10378 const unsigned long *addrs;
10379 int err, link_fd, prog_fd;
10380 const __u64 *cookies;
10385 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10386 return libbpf_err_ptr(-EINVAL);
10388 syms = OPTS_GET(opts, syms, false);
10389 addrs = OPTS_GET(opts, addrs, false);
10390 cnt = OPTS_GET(opts, cnt, false);
10391 cookies = OPTS_GET(opts, cookies, false);
10393 if (!pattern && !addrs && !syms)
10394 return libbpf_err_ptr(-EINVAL);
10395 if (pattern && (addrs || syms || cookies || cnt))
10396 return libbpf_err_ptr(-EINVAL);
10397 if (!pattern && !cnt)
10398 return libbpf_err_ptr(-EINVAL);
10400 return libbpf_err_ptr(-EINVAL);
10403 err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10414 retprobe = OPTS_GET(opts, retprobe, false);
10416 lopts.kprobe_multi.syms = syms;
10417 lopts.kprobe_multi.addrs = addrs;
10418 lopts.kprobe_multi.cookies = cookies;
10419 lopts.kprobe_multi.cnt = cnt;
10420 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10422 link = calloc(1, sizeof(*link));
10427 link->detach = &bpf_link__detach_fd;
10429 prog_fd = bpf_program__fd(prog);
10430 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10433 pr_warn("prog '%s': failed to attach: %s\n",
10434 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10437 link->fd = link_fd;
10444 return libbpf_err_ptr(err);
10447 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10449 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10450 unsigned long offset = 0;
10451 const char *func_name;
10457 /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10458 if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10461 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10463 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10465 func_name = prog->sec_name + sizeof("kprobe/") - 1;
10467 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10469 pr_warn("kprobe name is invalid: %s\n", func_name);
10472 if (opts.retprobe && offset != 0) {
10474 pr_warn("kretprobes do not support offset specification\n");
10478 opts.offset = offset;
10479 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10481 return libbpf_get_error(*link);
10484 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10486 LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10487 const char *syscall_name;
10491 /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10492 if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10495 opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10497 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10499 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10501 *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10502 return *link ? 0 : -errno;
10505 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10507 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10514 /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10515 if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10516 strcmp(prog->sec_name, "kretprobe.multi") == 0)
10519 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10521 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10523 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10525 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10527 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10531 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10533 return libbpf_get_error(*link);
10536 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10537 const char *binary_path, uint64_t offset)
10541 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10543 /* sanitize binary_path in the probe name */
10544 for (i = 0; buf[i]; i++) {
10545 if (!isalnum(buf[i]))
10550 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10551 const char *binary_path, size_t offset)
10553 return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10554 retprobe ? 'r' : 'p',
10555 retprobe ? "uretprobes" : "uprobes",
10556 probe_name, binary_path, offset);
10559 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10561 return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10562 retprobe ? "uretprobes" : "uprobes", probe_name);
10565 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10569 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10570 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10572 return parse_uint_from_file(file, "%d\n");
10575 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10576 const char *binary_path, size_t offset, int pid)
10578 const size_t attr_sz = sizeof(struct perf_event_attr);
10579 struct perf_event_attr attr;
10580 int type, pfd, err;
10582 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10584 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10585 binary_path, (size_t)offset, err);
10588 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10591 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10592 binary_path, offset, err);
10593 goto err_clean_legacy;
10596 memset(&attr, 0, attr_sz);
10597 attr.size = attr_sz;
10598 attr.config = type;
10599 attr.type = PERF_TYPE_TRACEPOINT;
10601 pfd = syscall(__NR_perf_event_open, &attr,
10602 pid < 0 ? -1 : pid, /* pid */
10603 pid == -1 ? 0 : -1, /* cpu */
10604 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10607 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10608 goto err_clean_legacy;
10613 /* Clear the newly added legacy uprobe_event */
10614 remove_uprobe_event_legacy(probe_name, retprobe);
10618 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10619 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10621 while ((scn = elf_nextscn(elf, scn)) != NULL) {
10624 if (!gelf_getshdr(scn, &sh))
10626 if (sh.sh_type == sh_type)
10632 /* Find offset of function name in the provided ELF object. "binary_path" is
10633 * the path to the ELF binary represented by "elf", and only used for error
10634 * reporting matters. "name" matches symbol name or name@@LIB for library
10637 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
10639 int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10640 bool is_shared_lib, is_name_qualified;
10641 long ret = -ENOENT;
10645 if (!gelf_getehdr(elf, &ehdr)) {
10646 pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10647 ret = -LIBBPF_ERRNO__FORMAT;
10650 /* for shared lib case, we do not need to calculate relative offset */
10651 is_shared_lib = ehdr.e_type == ET_DYN;
10653 name_len = strlen(name);
10654 /* Does name specify "@@LIB"? */
10655 is_name_qualified = strstr(name, "@@") != NULL;
10657 /* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10658 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10659 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10660 * reported as a warning/error.
10662 for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10663 size_t nr_syms, strtabidx, idx;
10664 Elf_Data *symbols = NULL;
10665 Elf_Scn *scn = NULL;
10666 int last_bind = -1;
10670 scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10672 pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10676 if (!gelf_getshdr(scn, &sh))
10678 strtabidx = sh.sh_link;
10679 symbols = elf_getdata(scn, 0);
10681 pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10682 binary_path, elf_errmsg(-1));
10683 ret = -LIBBPF_ERRNO__FORMAT;
10686 nr_syms = symbols->d_size / sh.sh_entsize;
10688 for (idx = 0; idx < nr_syms; idx++) {
10694 if (!gelf_getsym(symbols, idx, &sym))
10697 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10700 sname = elf_strptr(elf, strtabidx, sym.st_name);
10704 curr_bind = GELF_ST_BIND(sym.st_info);
10706 /* User can specify func, func@@LIB or func@@LIB_VERSION. */
10707 if (strncmp(sname, name, name_len) != 0)
10709 /* ...but we don't want a search for "foo" to match 'foo2" also, so any
10710 * additional characters in sname should be of the form "@@LIB".
10712 if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10716 /* handle multiple matches */
10717 if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10718 /* Only accept one non-weak bind. */
10719 pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10720 sname, name, binary_path);
10721 ret = -LIBBPF_ERRNO__FORMAT;
10723 } else if (curr_bind == STB_WEAK) {
10724 /* already have a non-weak bind, and
10725 * this is a weak bind, so ignore.
10731 /* Transform symbol's virtual address (absolute for
10732 * binaries and relative for shared libs) into file
10733 * offset, which is what kernel is expecting for
10734 * uprobe/uretprobe attachment.
10735 * See Documentation/trace/uprobetracer.rst for more
10737 * This is done by looking up symbol's containing
10738 * section's header and using it's virtual address
10739 * (sh_addr) and corresponding file offset (sh_offset)
10740 * to transform sym.st_value (virtual address) into
10741 * desired final file offset.
10743 sym_scn = elf_getscn(elf, sym.st_shndx);
10746 if (!gelf_getshdr(sym_scn, &sym_sh))
10749 ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10750 last_bind = curr_bind;
10757 pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10761 pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10762 is_shared_lib ? "should not be 0 in a shared library" :
10763 "try using shared library path instead");
10766 pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10773 /* Find offset of function name in ELF object specified by path. "name" matches
10774 * symbol name or name@@LIB for library functions.
10776 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
10778 char errmsg[STRERR_BUFSIZE];
10779 long ret = -ENOENT;
10783 fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10786 pr_warn("failed to open %s: %s\n", binary_path,
10787 libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10790 elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10792 pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10794 return -LIBBPF_ERRNO__FORMAT;
10797 ret = elf_find_func_offset(elf, binary_path, name);
10803 /* Find offset of function name in archive specified by path. Currently
10804 * supported are .zip files that do not compress their contents, as used on
10805 * Android in the form of APKs, for example. "file_name" is the name of the ELF
10806 * file inside the archive. "func_name" matches symbol name or name@@LIB for
10807 * library functions.
10809 * An overview of the APK format specifically provided here:
10810 * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
10812 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
10813 const char *func_name)
10815 struct zip_archive *archive;
10816 struct zip_entry entry;
10820 archive = zip_archive_open(archive_path);
10821 if (IS_ERR(archive)) {
10822 ret = PTR_ERR(archive);
10823 pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
10827 ret = zip_archive_find_entry(archive, file_name, &entry);
10829 pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
10830 archive_path, ret);
10833 pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
10834 (unsigned long)entry.data_offset);
10836 if (entry.compression) {
10837 pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
10839 ret = -LIBBPF_ERRNO__FORMAT;
10843 elf = elf_memory((void *)entry.data, entry.data_length);
10845 pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
10847 ret = -LIBBPF_ERRNO__LIBELF;
10851 ret = elf_find_func_offset(elf, file_name, func_name);
10853 pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
10854 func_name, file_name, archive_path, entry.data_offset, ret,
10855 ret + entry.data_offset);
10856 ret += entry.data_offset;
10861 zip_archive_close(archive);
10865 static const char *arch_specific_lib_paths(void)
10868 * Based on https://packages.debian.org/sid/libc6.
10870 * Assume that the traced program is built for the same architecture
10871 * as libbpf, which should cover the vast majority of cases.
10873 #if defined(__x86_64__)
10874 return "/lib/x86_64-linux-gnu";
10875 #elif defined(__i386__)
10876 return "/lib/i386-linux-gnu";
10877 #elif defined(__s390x__)
10878 return "/lib/s390x-linux-gnu";
10879 #elif defined(__s390__)
10880 return "/lib/s390-linux-gnu";
10881 #elif defined(__arm__) && defined(__SOFTFP__)
10882 return "/lib/arm-linux-gnueabi";
10883 #elif defined(__arm__) && !defined(__SOFTFP__)
10884 return "/lib/arm-linux-gnueabihf";
10885 #elif defined(__aarch64__)
10886 return "/lib/aarch64-linux-gnu";
10887 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10888 return "/lib/mips64el-linux-gnuabi64";
10889 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10890 return "/lib/mipsel-linux-gnu";
10891 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10892 return "/lib/powerpc64le-linux-gnu";
10893 #elif defined(__sparc__) && defined(__arch64__)
10894 return "/lib/sparc64-linux-gnu";
10895 #elif defined(__riscv) && __riscv_xlen == 64
10896 return "/lib/riscv64-linux-gnu";
10902 /* Get full path to program/shared library. */
10903 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10905 const char *search_paths[3] = {};
10908 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10909 search_paths[0] = getenv("LD_LIBRARY_PATH");
10910 search_paths[1] = "/usr/lib64:/usr/lib";
10911 search_paths[2] = arch_specific_lib_paths();
10914 search_paths[0] = getenv("PATH");
10915 search_paths[1] = "/usr/bin:/usr/sbin";
10916 perm = R_OK | X_OK;
10919 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10922 if (!search_paths[i])
10924 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10930 next_path = strchr(s, ':');
10931 seg_len = next_path ? next_path - s : strlen(s);
10934 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10935 /* ensure it has required permissions */
10936 if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
10938 pr_debug("resolved '%s' to '%s'\n", file, result);
10945 LIBBPF_API struct bpf_link *
10946 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10947 const char *binary_path, size_t func_offset,
10948 const struct bpf_uprobe_opts *opts)
10950 const char *archive_path = NULL, *archive_sep = NULL;
10951 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10952 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10953 enum probe_attach_mode attach_mode;
10954 char full_path[PATH_MAX];
10955 struct bpf_link *link;
10956 size_t ref_ctr_off;
10958 bool retprobe, legacy;
10959 const char *func_name;
10961 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10962 return libbpf_err_ptr(-EINVAL);
10964 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10965 retprobe = OPTS_GET(opts, retprobe, false);
10966 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10967 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10970 return libbpf_err_ptr(-EINVAL);
10972 /* Check if "binary_path" refers to an archive. */
10973 archive_sep = strstr(binary_path, "!/");
10975 full_path[0] = '\0';
10976 libbpf_strlcpy(full_path, binary_path,
10977 min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
10978 archive_path = full_path;
10979 binary_path = archive_sep + 2;
10980 } else if (!strchr(binary_path, '/')) {
10981 err = resolve_full_path(binary_path, full_path, sizeof(full_path));
10983 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10984 prog->name, binary_path, err);
10985 return libbpf_err_ptr(err);
10987 binary_path = full_path;
10989 func_name = OPTS_GET(opts, func_name, NULL);
10993 if (archive_path) {
10994 sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
10996 binary_path = archive_path;
10998 sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11001 return libbpf_err_ptr(sym_off);
11002 func_offset += sym_off;
11005 legacy = determine_uprobe_perf_type() < 0;
11006 switch (attach_mode) {
11007 case PROBE_ATTACH_MODE_LEGACY:
11009 pe_opts.force_ioctl_attach = true;
11011 case PROBE_ATTACH_MODE_PERF:
11013 return libbpf_err_ptr(-ENOTSUP);
11014 pe_opts.force_ioctl_attach = true;
11016 case PROBE_ATTACH_MODE_LINK:
11017 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11018 return libbpf_err_ptr(-ENOTSUP);
11020 case PROBE_ATTACH_MODE_DEFAULT:
11023 return libbpf_err_ptr(-EINVAL);
11027 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11028 func_offset, pid, ref_ctr_off);
11030 char probe_name[PATH_MAX + 64];
11033 return libbpf_err_ptr(-EINVAL);
11035 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11036 binary_path, func_offset);
11038 legacy_probe = strdup(probe_name);
11040 return libbpf_err_ptr(-ENOMEM);
11042 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11043 binary_path, func_offset, pid);
11047 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11048 prog->name, retprobe ? "uretprobe" : "uprobe",
11049 binary_path, func_offset,
11050 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11054 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11055 err = libbpf_get_error(link);
11058 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11059 prog->name, retprobe ? "uretprobe" : "uprobe",
11060 binary_path, func_offset,
11061 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11062 goto err_clean_legacy;
11065 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11067 perf_link->legacy_probe_name = legacy_probe;
11068 perf_link->legacy_is_kprobe = false;
11069 perf_link->legacy_is_retprobe = retprobe;
11075 remove_uprobe_event_legacy(legacy_probe, retprobe);
11077 free(legacy_probe);
11078 return libbpf_err_ptr(err);
11081 /* Format of u[ret]probe section definition supporting auto-attach:
11082 * u[ret]probe/binary:function[+offset]
11084 * binary can be an absolute/relative path or a filename; the latter is resolved to a
11085 * full binary path via bpf_program__attach_uprobe_opts.
11087 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11088 * specified (and auto-attach is not possible) or the above format is specified for
11091 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11093 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11094 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11095 int n, ret = -EINVAL;
11100 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11101 &probe_type, &binary_path, &func_name, &offset);
11104 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11108 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11109 prog->name, prog->sec_name);
11113 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11114 strcmp(probe_type, "uretprobe.s") == 0;
11115 if (opts.retprobe && offset != 0) {
11116 pr_warn("prog '%s': uretprobes do not support offset specification\n",
11120 opts.func_name = func_name;
11121 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11122 ret = libbpf_get_error(*link);
11125 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11136 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11137 bool retprobe, pid_t pid,
11138 const char *binary_path,
11139 size_t func_offset)
11141 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11143 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11146 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11147 pid_t pid, const char *binary_path,
11148 const char *usdt_provider, const char *usdt_name,
11149 const struct bpf_usdt_opts *opts)
11151 char resolved_path[512];
11152 struct bpf_object *obj = prog->obj;
11153 struct bpf_link *link;
11157 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11158 return libbpf_err_ptr(-EINVAL);
11160 if (bpf_program__fd(prog) < 0) {
11161 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11163 return libbpf_err_ptr(-EINVAL);
11167 return libbpf_err_ptr(-EINVAL);
11169 if (!strchr(binary_path, '/')) {
11170 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11172 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11173 prog->name, binary_path, err);
11174 return libbpf_err_ptr(err);
11176 binary_path = resolved_path;
11179 /* USDT manager is instantiated lazily on first USDT attach. It will
11180 * be destroyed together with BPF object in bpf_object__close().
11182 if (IS_ERR(obj->usdt_man))
11183 return libbpf_ptr(obj->usdt_man);
11184 if (!obj->usdt_man) {
11185 obj->usdt_man = usdt_manager_new(obj);
11186 if (IS_ERR(obj->usdt_man))
11187 return libbpf_ptr(obj->usdt_man);
11190 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11191 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11192 usdt_provider, usdt_name, usdt_cookie);
11193 err = libbpf_get_error(link);
11195 return libbpf_err_ptr(err);
11199 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11201 char *path = NULL, *provider = NULL, *name = NULL;
11202 const char *sec_name;
11205 sec_name = bpf_program__section_name(prog);
11206 if (strcmp(sec_name, "usdt") == 0) {
11207 /* no auto-attach for just SEC("usdt") */
11212 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11214 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11218 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11219 provider, name, NULL);
11220 err = libbpf_get_error(*link);
11228 static int determine_tracepoint_id(const char *tp_category,
11229 const char *tp_name)
11231 char file[PATH_MAX];
11234 ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11235 tracefs_path(), tp_category, tp_name);
11238 if (ret >= sizeof(file)) {
11239 pr_debug("tracepoint %s/%s path is too long\n",
11240 tp_category, tp_name);
11243 return parse_uint_from_file(file, "%d\n");
11246 static int perf_event_open_tracepoint(const char *tp_category,
11247 const char *tp_name)
11249 const size_t attr_sz = sizeof(struct perf_event_attr);
11250 struct perf_event_attr attr;
11251 char errmsg[STRERR_BUFSIZE];
11252 int tp_id, pfd, err;
11254 tp_id = determine_tracepoint_id(tp_category, tp_name);
11256 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11257 tp_category, tp_name,
11258 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11262 memset(&attr, 0, attr_sz);
11263 attr.type = PERF_TYPE_TRACEPOINT;
11264 attr.size = attr_sz;
11265 attr.config = tp_id;
11267 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11268 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11271 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11272 tp_category, tp_name,
11273 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11279 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11280 const char *tp_category,
11281 const char *tp_name,
11282 const struct bpf_tracepoint_opts *opts)
11284 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11285 char errmsg[STRERR_BUFSIZE];
11286 struct bpf_link *link;
11289 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11290 return libbpf_err_ptr(-EINVAL);
11292 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11294 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11296 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11297 prog->name, tp_category, tp_name,
11298 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11299 return libbpf_err_ptr(pfd);
11301 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11302 err = libbpf_get_error(link);
11305 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11306 prog->name, tp_category, tp_name,
11307 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11308 return libbpf_err_ptr(err);
11313 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11314 const char *tp_category,
11315 const char *tp_name)
11317 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11320 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11322 char *sec_name, *tp_cat, *tp_name;
11326 /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11327 if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11330 sec_name = strdup(prog->sec_name);
11334 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11335 if (str_has_pfx(prog->sec_name, "tp/"))
11336 tp_cat = sec_name + sizeof("tp/") - 1;
11338 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11339 tp_name = strchr(tp_cat, '/');
11347 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11349 return libbpf_get_error(*link);
11352 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11353 const char *tp_name)
11355 char errmsg[STRERR_BUFSIZE];
11356 struct bpf_link *link;
11359 prog_fd = bpf_program__fd(prog);
11361 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11362 return libbpf_err_ptr(-EINVAL);
11365 link = calloc(1, sizeof(*link));
11367 return libbpf_err_ptr(-ENOMEM);
11368 link->detach = &bpf_link__detach_fd;
11370 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11374 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11375 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11376 return libbpf_err_ptr(pfd);
11382 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11384 static const char *const prefixes[] = {
11388 "raw_tracepoint.w",
11391 const char *tp_name = NULL;
11395 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11398 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11401 pfx_len = strlen(prefixes[i]);
11402 /* no auto-attach case of, e.g., SEC("raw_tp") */
11403 if (prog->sec_name[pfx_len] == '\0')
11406 if (prog->sec_name[pfx_len] != '/')
11409 tp_name = prog->sec_name + pfx_len + 1;
11414 pr_warn("prog '%s': invalid section name '%s'\n",
11415 prog->name, prog->sec_name);
11419 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11420 return libbpf_get_error(*link);
11423 /* Common logic for all BPF program types that attach to a btf_id */
11424 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11425 const struct bpf_trace_opts *opts)
11427 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11428 char errmsg[STRERR_BUFSIZE];
11429 struct bpf_link *link;
11432 if (!OPTS_VALID(opts, bpf_trace_opts))
11433 return libbpf_err_ptr(-EINVAL);
11435 prog_fd = bpf_program__fd(prog);
11437 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11438 return libbpf_err_ptr(-EINVAL);
11441 link = calloc(1, sizeof(*link));
11443 return libbpf_err_ptr(-ENOMEM);
11444 link->detach = &bpf_link__detach_fd;
11446 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11447 link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11448 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11452 pr_warn("prog '%s': failed to attach: %s\n",
11453 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11454 return libbpf_err_ptr(pfd);
11460 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11462 return bpf_program__attach_btf_id(prog, NULL);
11465 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11466 const struct bpf_trace_opts *opts)
11468 return bpf_program__attach_btf_id(prog, opts);
11471 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11473 return bpf_program__attach_btf_id(prog, NULL);
11476 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11478 *link = bpf_program__attach_trace(prog);
11479 return libbpf_get_error(*link);
11482 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11484 *link = bpf_program__attach_lsm(prog);
11485 return libbpf_get_error(*link);
11488 static struct bpf_link *
11489 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11490 const char *target_name)
11492 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11493 .target_btf_id = btf_id);
11494 enum bpf_attach_type attach_type;
11495 char errmsg[STRERR_BUFSIZE];
11496 struct bpf_link *link;
11497 int prog_fd, link_fd;
11499 prog_fd = bpf_program__fd(prog);
11501 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11502 return libbpf_err_ptr(-EINVAL);
11505 link = calloc(1, sizeof(*link));
11507 return libbpf_err_ptr(-ENOMEM);
11508 link->detach = &bpf_link__detach_fd;
11510 attach_type = bpf_program__expected_attach_type(prog);
11511 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11515 pr_warn("prog '%s': failed to attach to %s: %s\n",
11516 prog->name, target_name,
11517 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11518 return libbpf_err_ptr(link_fd);
11520 link->fd = link_fd;
11525 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11527 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11531 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11533 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11536 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11538 /* target_fd/target_ifindex use the same field in LINK_CREATE */
11539 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11542 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11544 const char *attach_func_name)
11548 if (!!target_fd != !!attach_func_name) {
11549 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11551 return libbpf_err_ptr(-EINVAL);
11554 if (prog->type != BPF_PROG_TYPE_EXT) {
11555 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11557 return libbpf_err_ptr(-EINVAL);
11561 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11563 return libbpf_err_ptr(btf_id);
11565 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11567 /* no target, so use raw_tracepoint_open for compatibility
11570 return bpf_program__attach_trace(prog);
11575 bpf_program__attach_iter(const struct bpf_program *prog,
11576 const struct bpf_iter_attach_opts *opts)
11578 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11579 char errmsg[STRERR_BUFSIZE];
11580 struct bpf_link *link;
11581 int prog_fd, link_fd;
11582 __u32 target_fd = 0;
11584 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11585 return libbpf_err_ptr(-EINVAL);
11587 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11588 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11590 prog_fd = bpf_program__fd(prog);
11592 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11593 return libbpf_err_ptr(-EINVAL);
11596 link = calloc(1, sizeof(*link));
11598 return libbpf_err_ptr(-ENOMEM);
11599 link->detach = &bpf_link__detach_fd;
11601 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11602 &link_create_opts);
11606 pr_warn("prog '%s': failed to attach to iterator: %s\n",
11607 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11608 return libbpf_err_ptr(link_fd);
11610 link->fd = link_fd;
11614 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11616 *link = bpf_program__attach_iter(prog, NULL);
11617 return libbpf_get_error(*link);
11620 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11622 struct bpf_link *link = NULL;
11625 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11626 return libbpf_err_ptr(-EOPNOTSUPP);
11628 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11630 return libbpf_err_ptr(err);
11632 /* When calling bpf_program__attach() explicitly, auto-attach support
11633 * is expected to work, so NULL returned link is considered an error.
11634 * This is different for skeleton's attach, see comment in
11635 * bpf_object__attach_skeleton().
11638 return libbpf_err_ptr(-EOPNOTSUPP);
11643 struct bpf_link_struct_ops {
11644 struct bpf_link link;
11648 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11650 struct bpf_link_struct_ops *st_link;
11653 st_link = container_of(link, struct bpf_link_struct_ops, link);
11655 if (st_link->map_fd < 0)
11656 /* w/o a real link */
11657 return bpf_map_delete_elem(link->fd, &zero);
11659 return close(link->fd);
11662 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11664 struct bpf_link_struct_ops *link;
11668 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11669 return libbpf_err_ptr(-EINVAL);
11671 link = calloc(1, sizeof(*link));
11673 return libbpf_err_ptr(-EINVAL);
11675 /* kern_vdata should be prepared during the loading phase. */
11676 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11677 /* It can be EBUSY if the map has been used to create or
11678 * update a link before. We don't allow updating the value of
11679 * a struct_ops once it is set. That ensures that the value
11680 * never changed. So, it is safe to skip EBUSY.
11682 if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
11684 return libbpf_err_ptr(err);
11687 link->link.detach = bpf_link__detach_struct_ops;
11689 if (!(map->def.map_flags & BPF_F_LINK)) {
11690 /* w/o a real link */
11691 link->link.fd = map->fd;
11693 return &link->link;
11696 fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
11699 return libbpf_err_ptr(fd);
11702 link->link.fd = fd;
11703 link->map_fd = map->fd;
11705 return &link->link;
11709 * Swap the back struct_ops of a link with a new struct_ops map.
11711 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
11713 struct bpf_link_struct_ops *st_ops_link;
11717 if (!bpf_map__is_struct_ops(map) || map->fd < 0)
11720 st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
11721 /* Ensure the type of a link is correct */
11722 if (st_ops_link->map_fd < 0)
11725 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11726 /* It can be EBUSY if the map has been used to create or
11727 * update a link before. We don't allow updating the value of
11728 * a struct_ops once it is set. That ensures that the value
11729 * never changed. So, it is safe to skip EBUSY.
11731 if (err && err != -EBUSY)
11734 err = bpf_link_update(link->fd, map->fd, NULL);
11738 st_ops_link->map_fd = map->fd;
11743 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11744 void *private_data);
11746 static enum bpf_perf_event_ret
11747 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11748 void **copy_mem, size_t *copy_size,
11749 bpf_perf_event_print_t fn, void *private_data)
11751 struct perf_event_mmap_page *header = mmap_mem;
11752 __u64 data_head = ring_buffer_read_head(header);
11753 __u64 data_tail = header->data_tail;
11754 void *base = ((__u8 *)header) + page_size;
11755 int ret = LIBBPF_PERF_EVENT_CONT;
11756 struct perf_event_header *ehdr;
11759 while (data_head != data_tail) {
11760 ehdr = base + (data_tail & (mmap_size - 1));
11761 ehdr_size = ehdr->size;
11763 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11764 void *copy_start = ehdr;
11765 size_t len_first = base + mmap_size - copy_start;
11766 size_t len_secnd = ehdr_size - len_first;
11768 if (*copy_size < ehdr_size) {
11770 *copy_mem = malloc(ehdr_size);
11773 ret = LIBBPF_PERF_EVENT_ERROR;
11776 *copy_size = ehdr_size;
11779 memcpy(*copy_mem, copy_start, len_first);
11780 memcpy(*copy_mem + len_first, base, len_secnd);
11784 ret = fn(ehdr, private_data);
11785 data_tail += ehdr_size;
11786 if (ret != LIBBPF_PERF_EVENT_CONT)
11790 ring_buffer_write_tail(header, data_tail);
11791 return libbpf_err(ret);
11794 struct perf_buffer;
11796 struct perf_buffer_params {
11797 struct perf_event_attr *attr;
11798 /* if event_cb is specified, it takes precendence */
11799 perf_buffer_event_fn event_cb;
11800 /* sample_cb and lost_cb are higher-level common-case callbacks */
11801 perf_buffer_sample_fn sample_cb;
11802 perf_buffer_lost_fn lost_cb;
11809 struct perf_cpu_buf {
11810 struct perf_buffer *pb;
11811 void *base; /* mmap()'ed memory */
11812 void *buf; /* for reconstructing segmented data */
11819 struct perf_buffer {
11820 perf_buffer_event_fn event_cb;
11821 perf_buffer_sample_fn sample_cb;
11822 perf_buffer_lost_fn lost_cb;
11823 void *ctx; /* passed into callbacks */
11827 struct perf_cpu_buf **cpu_bufs;
11828 struct epoll_event *events;
11829 int cpu_cnt; /* number of allocated CPU buffers */
11830 int epoll_fd; /* perf event FD */
11831 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11834 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11835 struct perf_cpu_buf *cpu_buf)
11839 if (cpu_buf->base &&
11840 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11841 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11842 if (cpu_buf->fd >= 0) {
11843 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11844 close(cpu_buf->fd);
11846 free(cpu_buf->buf);
11850 void perf_buffer__free(struct perf_buffer *pb)
11854 if (IS_ERR_OR_NULL(pb))
11856 if (pb->cpu_bufs) {
11857 for (i = 0; i < pb->cpu_cnt; i++) {
11858 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11863 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11864 perf_buffer__free_cpu_buf(pb, cpu_buf);
11866 free(pb->cpu_bufs);
11868 if (pb->epoll_fd >= 0)
11869 close(pb->epoll_fd);
11874 static struct perf_cpu_buf *
11875 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11876 int cpu, int map_key)
11878 struct perf_cpu_buf *cpu_buf;
11879 char msg[STRERR_BUFSIZE];
11882 cpu_buf = calloc(1, sizeof(*cpu_buf));
11884 return ERR_PTR(-ENOMEM);
11887 cpu_buf->cpu = cpu;
11888 cpu_buf->map_key = map_key;
11890 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11891 -1, PERF_FLAG_FD_CLOEXEC);
11892 if (cpu_buf->fd < 0) {
11894 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11895 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11899 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11900 PROT_READ | PROT_WRITE, MAP_SHARED,
11902 if (cpu_buf->base == MAP_FAILED) {
11903 cpu_buf->base = NULL;
11905 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11906 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11910 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11912 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11913 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11920 perf_buffer__free_cpu_buf(pb, cpu_buf);
11921 return (struct perf_cpu_buf *)ERR_PTR(err);
11924 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11925 struct perf_buffer_params *p);
11927 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11928 perf_buffer_sample_fn sample_cb,
11929 perf_buffer_lost_fn lost_cb,
11931 const struct perf_buffer_opts *opts)
11933 const size_t attr_sz = sizeof(struct perf_event_attr);
11934 struct perf_buffer_params p = {};
11935 struct perf_event_attr attr;
11936 __u32 sample_period;
11938 if (!OPTS_VALID(opts, perf_buffer_opts))
11939 return libbpf_err_ptr(-EINVAL);
11941 sample_period = OPTS_GET(opts, sample_period, 1);
11942 if (!sample_period)
11945 memset(&attr, 0, attr_sz);
11946 attr.size = attr_sz;
11947 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11948 attr.type = PERF_TYPE_SOFTWARE;
11949 attr.sample_type = PERF_SAMPLE_RAW;
11950 attr.sample_period = sample_period;
11951 attr.wakeup_events = sample_period;
11954 p.sample_cb = sample_cb;
11955 p.lost_cb = lost_cb;
11958 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11961 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11962 struct perf_event_attr *attr,
11963 perf_buffer_event_fn event_cb, void *ctx,
11964 const struct perf_buffer_raw_opts *opts)
11966 struct perf_buffer_params p = {};
11969 return libbpf_err_ptr(-EINVAL);
11971 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11972 return libbpf_err_ptr(-EINVAL);
11975 p.event_cb = event_cb;
11977 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11978 p.cpus = OPTS_GET(opts, cpus, NULL);
11979 p.map_keys = OPTS_GET(opts, map_keys, NULL);
11981 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11984 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11985 struct perf_buffer_params *p)
11987 const char *online_cpus_file = "/sys/devices/system/cpu/online";
11988 struct bpf_map_info map;
11989 char msg[STRERR_BUFSIZE];
11990 struct perf_buffer *pb;
11991 bool *online = NULL;
11992 __u32 map_info_len;
11995 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
11996 pr_warn("page count should be power of two, but is %zu\n",
11998 return ERR_PTR(-EINVAL);
12001 /* best-effort sanity checks */
12002 memset(&map, 0, sizeof(map));
12003 map_info_len = sizeof(map);
12004 err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12007 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12008 * -EBADFD, -EFAULT, or -E2BIG on real error
12010 if (err != -EINVAL) {
12011 pr_warn("failed to get map info for map FD %d: %s\n",
12012 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12013 return ERR_PTR(err);
12015 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12018 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12019 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12021 return ERR_PTR(-EINVAL);
12025 pb = calloc(1, sizeof(*pb));
12027 return ERR_PTR(-ENOMEM);
12029 pb->event_cb = p->event_cb;
12030 pb->sample_cb = p->sample_cb;
12031 pb->lost_cb = p->lost_cb;
12034 pb->page_size = getpagesize();
12035 pb->mmap_size = pb->page_size * page_cnt;
12036 pb->map_fd = map_fd;
12038 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12039 if (pb->epoll_fd < 0) {
12041 pr_warn("failed to create epoll instance: %s\n",
12042 libbpf_strerror_r(err, msg, sizeof(msg)));
12046 if (p->cpu_cnt > 0) {
12047 pb->cpu_cnt = p->cpu_cnt;
12049 pb->cpu_cnt = libbpf_num_possible_cpus();
12050 if (pb->cpu_cnt < 0) {
12054 if (map.max_entries && map.max_entries < pb->cpu_cnt)
12055 pb->cpu_cnt = map.max_entries;
12058 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12061 pr_warn("failed to allocate events: out of memory\n");
12064 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12065 if (!pb->cpu_bufs) {
12067 pr_warn("failed to allocate buffers: out of memory\n");
12071 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12073 pr_warn("failed to get online CPU mask: %d\n", err);
12077 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12078 struct perf_cpu_buf *cpu_buf;
12081 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12082 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12084 /* in case user didn't explicitly requested particular CPUs to
12085 * be attached to, skip offline/not present CPUs
12087 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12090 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12091 if (IS_ERR(cpu_buf)) {
12092 err = PTR_ERR(cpu_buf);
12096 pb->cpu_bufs[j] = cpu_buf;
12098 err = bpf_map_update_elem(pb->map_fd, &map_key,
12102 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12103 cpu, map_key, cpu_buf->fd,
12104 libbpf_strerror_r(err, msg, sizeof(msg)));
12108 pb->events[j].events = EPOLLIN;
12109 pb->events[j].data.ptr = cpu_buf;
12110 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12111 &pb->events[j]) < 0) {
12113 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12115 libbpf_strerror_r(err, msg, sizeof(msg)));
12128 perf_buffer__free(pb);
12129 return ERR_PTR(err);
12132 struct perf_sample_raw {
12133 struct perf_event_header header;
12138 struct perf_sample_lost {
12139 struct perf_event_header header;
12142 uint64_t sample_id;
12145 static enum bpf_perf_event_ret
12146 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12148 struct perf_cpu_buf *cpu_buf = ctx;
12149 struct perf_buffer *pb = cpu_buf->pb;
12152 /* user wants full control over parsing perf event */
12154 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12157 case PERF_RECORD_SAMPLE: {
12158 struct perf_sample_raw *s = data;
12161 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12164 case PERF_RECORD_LOST: {
12165 struct perf_sample_lost *s = data;
12168 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12172 pr_warn("unknown perf sample type %d\n", e->type);
12173 return LIBBPF_PERF_EVENT_ERROR;
12175 return LIBBPF_PERF_EVENT_CONT;
12178 static int perf_buffer__process_records(struct perf_buffer *pb,
12179 struct perf_cpu_buf *cpu_buf)
12181 enum bpf_perf_event_ret ret;
12183 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12184 pb->page_size, &cpu_buf->buf,
12185 &cpu_buf->buf_size,
12186 perf_buffer__process_record, cpu_buf);
12187 if (ret != LIBBPF_PERF_EVENT_CONT)
12192 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12194 return pb->epoll_fd;
12197 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12201 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12205 for (i = 0; i < cnt; i++) {
12206 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12208 err = perf_buffer__process_records(pb, cpu_buf);
12210 pr_warn("error while processing records: %d\n", err);
12211 return libbpf_err(err);
12217 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12220 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12222 return pb->cpu_cnt;
12226 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12227 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12228 * select()/poll()/epoll() Linux syscalls.
12230 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12232 struct perf_cpu_buf *cpu_buf;
12234 if (buf_idx >= pb->cpu_cnt)
12235 return libbpf_err(-EINVAL);
12237 cpu_buf = pb->cpu_bufs[buf_idx];
12239 return libbpf_err(-ENOENT);
12241 return cpu_buf->fd;
12244 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12246 struct perf_cpu_buf *cpu_buf;
12248 if (buf_idx >= pb->cpu_cnt)
12249 return libbpf_err(-EINVAL);
12251 cpu_buf = pb->cpu_bufs[buf_idx];
12253 return libbpf_err(-ENOENT);
12255 *buf = cpu_buf->base;
12256 *buf_size = pb->mmap_size;
12261 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12262 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12263 * consume, do nothing and return success.
12268 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12270 struct perf_cpu_buf *cpu_buf;
12272 if (buf_idx >= pb->cpu_cnt)
12273 return libbpf_err(-EINVAL);
12275 cpu_buf = pb->cpu_bufs[buf_idx];
12277 return libbpf_err(-ENOENT);
12279 return perf_buffer__process_records(pb, cpu_buf);
12282 int perf_buffer__consume(struct perf_buffer *pb)
12286 for (i = 0; i < pb->cpu_cnt; i++) {
12287 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12292 err = perf_buffer__process_records(pb, cpu_buf);
12294 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12295 return libbpf_err(err);
12301 int bpf_program__set_attach_target(struct bpf_program *prog,
12302 int attach_prog_fd,
12303 const char *attach_func_name)
12305 int btf_obj_fd = 0, btf_id = 0, err;
12307 if (!prog || attach_prog_fd < 0)
12308 return libbpf_err(-EINVAL);
12310 if (prog->obj->loaded)
12311 return libbpf_err(-EINVAL);
12313 if (attach_prog_fd && !attach_func_name) {
12314 /* remember attach_prog_fd and let bpf_program__load() find
12315 * BTF ID during the program load
12317 prog->attach_prog_fd = attach_prog_fd;
12321 if (attach_prog_fd) {
12322 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12325 return libbpf_err(btf_id);
12327 if (!attach_func_name)
12328 return libbpf_err(-EINVAL);
12330 /* load btf_vmlinux, if not yet */
12331 err = bpf_object__load_vmlinux_btf(prog->obj, true);
12333 return libbpf_err(err);
12334 err = find_kernel_btf_id(prog->obj, attach_func_name,
12335 prog->expected_attach_type,
12336 &btf_obj_fd, &btf_id);
12338 return libbpf_err(err);
12341 prog->attach_btf_id = btf_id;
12342 prog->attach_btf_obj_fd = btf_obj_fd;
12343 prog->attach_prog_fd = attach_prog_fd;
12347 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12349 int err = 0, n, len, start, end = -1;
12355 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12357 if (*s == ',' || *s == '\n') {
12361 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12362 if (n <= 0 || n > 2) {
12363 pr_warn("Failed to get CPU range %s: %d\n", s, n);
12366 } else if (n == 1) {
12369 if (start < 0 || start > end) {
12370 pr_warn("Invalid CPU range [%d,%d] in %s\n",
12375 tmp = realloc(*mask, end + 1);
12381 memset(tmp + *mask_sz, 0, start - *mask_sz);
12382 memset(tmp + start, 1, end - start + 1);
12383 *mask_sz = end + 1;
12387 pr_warn("Empty CPU range\n");
12397 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12399 int fd, err = 0, len;
12402 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12405 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12408 len = read(fd, buf, sizeof(buf));
12411 err = len ? -errno : -EINVAL;
12412 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12415 if (len >= sizeof(buf)) {
12416 pr_warn("CPU mask is too big in file %s\n", fcpu);
12421 return parse_cpu_mask_str(buf, mask, mask_sz);
12424 int libbpf_num_possible_cpus(void)
12426 static const char *fcpu = "/sys/devices/system/cpu/possible";
12428 int err, n, i, tmp_cpus;
12431 tmp_cpus = READ_ONCE(cpus);
12435 err = parse_cpu_mask_file(fcpu, &mask, &n);
12437 return libbpf_err(err);
12440 for (i = 0; i < n; i++) {
12446 WRITE_ONCE(cpus, tmp_cpus);
12450 static int populate_skeleton_maps(const struct bpf_object *obj,
12451 struct bpf_map_skeleton *maps,
12456 for (i = 0; i < map_cnt; i++) {
12457 struct bpf_map **map = maps[i].map;
12458 const char *name = maps[i].name;
12459 void **mmaped = maps[i].mmaped;
12461 *map = bpf_object__find_map_by_name(obj, name);
12463 pr_warn("failed to find skeleton map '%s'\n", name);
12467 /* externs shouldn't be pre-setup from user code */
12468 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12469 *mmaped = (*map)->mmaped;
12474 static int populate_skeleton_progs(const struct bpf_object *obj,
12475 struct bpf_prog_skeleton *progs,
12480 for (i = 0; i < prog_cnt; i++) {
12481 struct bpf_program **prog = progs[i].prog;
12482 const char *name = progs[i].name;
12484 *prog = bpf_object__find_program_by_name(obj, name);
12486 pr_warn("failed to find skeleton program '%s'\n", name);
12493 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12494 const struct bpf_object_open_opts *opts)
12496 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12497 .object_name = s->name,
12499 struct bpf_object *obj;
12502 /* Attempt to preserve opts->object_name, unless overriden by user
12503 * explicitly. Overwriting object name for skeletons is discouraged,
12504 * as it breaks global data maps, because they contain object name
12505 * prefix as their own map name prefix. When skeleton is generated,
12506 * bpftool is making an assumption that this name will stay the same.
12509 memcpy(&skel_opts, opts, sizeof(*opts));
12510 if (!opts->object_name)
12511 skel_opts.object_name = s->name;
12514 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12515 err = libbpf_get_error(obj);
12517 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12519 return libbpf_err(err);
12523 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12525 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12526 return libbpf_err(err);
12529 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12531 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12532 return libbpf_err(err);
12538 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12540 int err, len, var_idx, i;
12541 const char *var_name;
12542 const struct bpf_map *map;
12545 const struct btf_type *map_type, *var_type;
12546 const struct bpf_var_skeleton *var_skel;
12547 struct btf_var_secinfo *var;
12550 return libbpf_err(-EINVAL);
12552 btf = bpf_object__btf(s->obj);
12554 pr_warn("subskeletons require BTF at runtime (object %s)\n",
12555 bpf_object__name(s->obj));
12556 return libbpf_err(-errno);
12559 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12561 pr_warn("failed to populate subskeleton maps: %d\n", err);
12562 return libbpf_err(err);
12565 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12567 pr_warn("failed to populate subskeleton maps: %d\n", err);
12568 return libbpf_err(err);
12571 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12572 var_skel = &s->vars[var_idx];
12573 map = *var_skel->map;
12574 map_type_id = bpf_map__btf_value_type_id(map);
12575 map_type = btf__type_by_id(btf, map_type_id);
12577 if (!btf_is_datasec(map_type)) {
12578 pr_warn("type for map '%1$s' is not a datasec: %2$s",
12579 bpf_map__name(map),
12580 __btf_kind_str(btf_kind(map_type)));
12581 return libbpf_err(-EINVAL);
12584 len = btf_vlen(map_type);
12585 var = btf_var_secinfos(map_type);
12586 for (i = 0; i < len; i++, var++) {
12587 var_type = btf__type_by_id(btf, var->type);
12588 var_name = btf__name_by_offset(btf, var_type->name_off);
12589 if (strcmp(var_name, var_skel->name) == 0) {
12590 *var_skel->addr = map->mmaped + var->offset;
12598 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12608 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12612 err = bpf_object__load(*s->obj);
12614 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12615 return libbpf_err(err);
12618 for (i = 0; i < s->map_cnt; i++) {
12619 struct bpf_map *map = *s->maps[i].map;
12620 size_t mmap_sz = bpf_map_mmap_sz(map);
12621 int prot, map_fd = bpf_map__fd(map);
12622 void **mmaped = s->maps[i].mmaped;
12627 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12632 if (map->def.map_flags & BPF_F_RDONLY_PROG)
12635 prot = PROT_READ | PROT_WRITE;
12637 /* Remap anonymous mmap()-ed "map initialization image" as
12638 * a BPF map-backed mmap()-ed memory, but preserving the same
12639 * memory address. This will cause kernel to change process'
12640 * page table to point to a different piece of kernel memory,
12641 * but from userspace point of view memory address (and its
12642 * contents, being identical at this point) will stay the
12643 * same. This mapping will be released by bpf_object__close()
12644 * as per normal clean up procedure, so we don't need to worry
12645 * about it from skeleton's clean up perspective.
12647 *mmaped = mmap(map->mmaped, mmap_sz, prot,
12648 MAP_SHARED | MAP_FIXED, map_fd, 0);
12649 if (*mmaped == MAP_FAILED) {
12652 pr_warn("failed to re-mmap() map '%s': %d\n",
12653 bpf_map__name(map), err);
12654 return libbpf_err(err);
12661 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12665 for (i = 0; i < s->prog_cnt; i++) {
12666 struct bpf_program *prog = *s->progs[i].prog;
12667 struct bpf_link **link = s->progs[i].link;
12669 if (!prog->autoload || !prog->autoattach)
12672 /* auto-attaching not supported for this program */
12673 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12676 /* if user already set the link manually, don't attempt auto-attach */
12680 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12682 pr_warn("prog '%s': failed to auto-attach: %d\n",
12683 bpf_program__name(prog), err);
12684 return libbpf_err(err);
12687 /* It's possible that for some SEC() definitions auto-attach
12688 * is supported in some cases (e.g., if definition completely
12689 * specifies target information), but is not in other cases.
12690 * SEC("uprobe") is one such case. If user specified target
12691 * binary and function name, such BPF program can be
12692 * auto-attached. But if not, it shouldn't trigger skeleton's
12693 * attach to fail. It should just be skipped.
12694 * attach_fn signals such case with returning 0 (no error) and
12695 * setting link to NULL.
12702 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12706 for (i = 0; i < s->prog_cnt; i++) {
12707 struct bpf_link **link = s->progs[i].link;
12709 bpf_link__destroy(*link);
12714 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12720 bpf_object__detach_skeleton(s);
12722 bpf_object__close(*s->obj);