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"
472 enum libbpf_map_type {
482 unsigned int key_size;
483 unsigned int value_size;
484 unsigned int max_entries;
485 unsigned int map_flags;
489 struct bpf_object *obj;
491 /* real_name is defined for special internal maps (.rodata*,
492 * .data*, .bss, .kconfig) and preserves their original ELF section
493 * name. This is important to be able to find corresponding BTF
494 * DATASEC information.
502 struct bpf_map_def def;
505 __u32 btf_key_type_id;
506 __u32 btf_value_type_id;
507 __u32 btf_vmlinux_value_type_id;
508 enum libbpf_map_type libbpf_type;
510 struct bpf_struct_ops *st_ops;
511 struct bpf_map *inner_map;
537 enum extern_type type;
553 unsigned long long addr;
555 /* target btf_id of the corresponding kernel var. */
556 int kernel_btf_obj_fd;
559 /* local btf_id of the ksym extern's type. */
561 /* BTF fd index to be patched in for insn->off, this is
562 * 0 for vmlinux BTF, index in obj->fd_array for module
586 struct elf_sec_desc {
587 enum sec_type sec_type;
599 Elf_Data *st_ops_data;
600 size_t shstrndx; /* section index for section name strings */
602 struct elf_sec_desc *secs;
605 __u32 btf_maps_sec_btf_id;
614 char name[BPF_OBJ_NAME_LEN];
618 struct bpf_program *programs;
620 struct bpf_map *maps;
625 struct extern_desc *externs;
633 struct bpf_gen *gen_loader;
635 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
636 struct elf_state efile;
639 struct btf_ext *btf_ext;
641 /* Parse and load BTF vmlinux if any of the programs in the object need
644 struct btf *btf_vmlinux;
645 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
646 * override for vmlinux BTF.
648 char *btf_custom_path;
649 /* vmlinux BTF override for CO-RE relocations */
650 struct btf *btf_vmlinux_override;
651 /* Lazily initialized kernel module BTFs */
652 struct module_btf *btf_modules;
653 bool btf_modules_loaded;
654 size_t btf_module_cnt;
655 size_t btf_module_cap;
657 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
666 struct usdt_manager *usdt_man;
671 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
672 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
673 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
674 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
675 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
676 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
677 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
678 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
679 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
681 void bpf_program__unload(struct bpf_program *prog)
688 zfree(&prog->func_info);
689 zfree(&prog->line_info);
692 static void bpf_program__exit(struct bpf_program *prog)
697 bpf_program__unload(prog);
699 zfree(&prog->sec_name);
701 zfree(&prog->reloc_desc);
708 static bool insn_is_subprog_call(const struct bpf_insn *insn)
710 return BPF_CLASS(insn->code) == BPF_JMP &&
711 BPF_OP(insn->code) == BPF_CALL &&
712 BPF_SRC(insn->code) == BPF_K &&
713 insn->src_reg == BPF_PSEUDO_CALL &&
714 insn->dst_reg == 0 &&
718 static bool is_call_insn(const struct bpf_insn *insn)
720 return insn->code == (BPF_JMP | BPF_CALL);
723 static bool insn_is_pseudo_func(struct bpf_insn *insn)
725 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
729 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
730 const char *name, size_t sec_idx, const char *sec_name,
731 size_t sec_off, void *insn_data, size_t insn_data_sz)
733 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
734 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
735 sec_name, name, sec_off, insn_data_sz);
739 memset(prog, 0, sizeof(*prog));
742 prog->sec_idx = sec_idx;
743 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
744 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
745 /* insns_cnt can later be increased by appending used subprograms */
746 prog->insns_cnt = prog->sec_insn_cnt;
748 prog->type = BPF_PROG_TYPE_UNSPEC;
751 /* libbpf's convention for SEC("?abc...") is that it's just like
752 * SEC("abc...") but the corresponding bpf_program starts out with
753 * autoload set to false.
755 if (sec_name[0] == '?') {
756 prog->autoload = false;
757 /* from now on forget there was ? in section name */
760 prog->autoload = true;
763 prog->autoattach = true;
765 /* inherit object's log_level */
766 prog->log_level = obj->log_level;
768 prog->sec_name = strdup(sec_name);
772 prog->name = strdup(name);
776 prog->insns = malloc(insn_data_sz);
779 memcpy(prog->insns, insn_data, insn_data_sz);
783 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
784 bpf_program__exit(prog);
789 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
790 const char *sec_name, int sec_idx)
792 Elf_Data *symbols = obj->efile.symbols;
793 struct bpf_program *prog, *progs;
794 void *data = sec_data->d_buf;
795 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
796 int nr_progs, err, i;
800 progs = obj->programs;
801 nr_progs = obj->nr_programs;
802 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
804 for (i = 0; i < nr_syms; i++) {
805 sym = elf_sym_by_idx(obj, i);
807 if (sym->st_shndx != sec_idx)
809 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
812 prog_sz = sym->st_size;
813 sec_off = sym->st_value;
815 name = elf_sym_str(obj, sym->st_name);
817 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
819 return -LIBBPF_ERRNO__FORMAT;
822 if (sec_off + prog_sz > sec_sz) {
823 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
825 return -LIBBPF_ERRNO__FORMAT;
828 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
829 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
833 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
834 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
836 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
839 * In this case the original obj->programs
840 * is still valid, so don't need special treat for
841 * bpf_close_object().
843 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
847 obj->programs = progs;
849 prog = &progs[nr_progs];
851 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
852 sec_off, data + sec_off, prog_sz);
856 /* if function is a global/weak symbol, but has restricted
857 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
858 * as static to enable more permissive BPF verification mode
859 * with more outside context available to BPF verifier
861 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
862 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
863 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
864 prog->mark_btf_static = true;
867 obj->nr_programs = nr_progs;
873 static const struct btf_member *
874 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
876 struct btf_member *m;
879 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
880 if (btf_member_bit_offset(t, i) == bit_offset)
887 static const struct btf_member *
888 find_member_by_name(const struct btf *btf, const struct btf_type *t,
891 struct btf_member *m;
894 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
895 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
902 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
903 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
904 const char *name, __u32 kind);
907 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
908 const struct btf_type **type, __u32 *type_id,
909 const struct btf_type **vtype, __u32 *vtype_id,
910 const struct btf_member **data_member)
912 const struct btf_type *kern_type, *kern_vtype;
913 const struct btf_member *kern_data_member;
914 __s32 kern_vtype_id, kern_type_id;
917 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
918 if (kern_type_id < 0) {
919 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
923 kern_type = btf__type_by_id(btf, kern_type_id);
925 /* Find the corresponding "map_value" type that will be used
926 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
927 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
930 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
931 tname, BTF_KIND_STRUCT);
932 if (kern_vtype_id < 0) {
933 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
934 STRUCT_OPS_VALUE_PREFIX, tname);
935 return kern_vtype_id;
937 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
939 /* Find "struct tcp_congestion_ops" from
940 * struct bpf_struct_ops_tcp_congestion_ops {
942 * struct tcp_congestion_ops data;
945 kern_data_member = btf_members(kern_vtype);
946 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
947 if (kern_data_member->type == kern_type_id)
950 if (i == btf_vlen(kern_vtype)) {
951 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
952 tname, STRUCT_OPS_VALUE_PREFIX, tname);
957 *type_id = kern_type_id;
959 *vtype_id = kern_vtype_id;
960 *data_member = kern_data_member;
965 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
967 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
970 /* Init the map's fields that depend on kern_btf */
971 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
972 const struct btf *btf,
973 const struct btf *kern_btf)
975 const struct btf_member *member, *kern_member, *kern_data_member;
976 const struct btf_type *type, *kern_type, *kern_vtype;
977 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
978 struct bpf_struct_ops *st_ops;
979 void *data, *kern_data;
983 st_ops = map->st_ops;
985 tname = st_ops->tname;
986 err = find_struct_ops_kern_types(kern_btf, tname,
987 &kern_type, &kern_type_id,
988 &kern_vtype, &kern_vtype_id,
993 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
994 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
996 map->def.value_size = kern_vtype->size;
997 map->btf_vmlinux_value_type_id = kern_vtype_id;
999 st_ops->kern_vdata = calloc(1, kern_vtype->size);
1000 if (!st_ops->kern_vdata)
1003 data = st_ops->data;
1004 kern_data_off = kern_data_member->offset / 8;
1005 kern_data = st_ops->kern_vdata + kern_data_off;
1007 member = btf_members(type);
1008 for (i = 0; i < btf_vlen(type); i++, member++) {
1009 const struct btf_type *mtype, *kern_mtype;
1010 __u32 mtype_id, kern_mtype_id;
1011 void *mdata, *kern_mdata;
1012 __s64 msize, kern_msize;
1013 __u32 moff, kern_moff;
1014 __u32 kern_member_idx;
1017 mname = btf__name_by_offset(btf, member->name_off);
1018 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1020 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1025 kern_member_idx = kern_member - btf_members(kern_type);
1026 if (btf_member_bitfield_size(type, i) ||
1027 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1028 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1033 moff = member->offset / 8;
1034 kern_moff = kern_member->offset / 8;
1036 mdata = data + moff;
1037 kern_mdata = kern_data + kern_moff;
1039 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1040 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1042 if (BTF_INFO_KIND(mtype->info) !=
1043 BTF_INFO_KIND(kern_mtype->info)) {
1044 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1045 map->name, mname, BTF_INFO_KIND(mtype->info),
1046 BTF_INFO_KIND(kern_mtype->info));
1050 if (btf_is_ptr(mtype)) {
1051 struct bpf_program *prog;
1053 prog = st_ops->progs[i];
1057 kern_mtype = skip_mods_and_typedefs(kern_btf,
1061 /* mtype->type must be a func_proto which was
1062 * guaranteed in bpf_object__collect_st_ops_relos(),
1063 * so only check kern_mtype for func_proto here.
1065 if (!btf_is_func_proto(kern_mtype)) {
1066 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1071 prog->attach_btf_id = kern_type_id;
1072 prog->expected_attach_type = kern_member_idx;
1074 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1076 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1077 map->name, mname, prog->name, moff,
1083 msize = btf__resolve_size(btf, mtype_id);
1084 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1085 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1086 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1087 map->name, mname, (ssize_t)msize,
1088 (ssize_t)kern_msize);
1092 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1093 map->name, mname, (unsigned int)msize,
1095 memcpy(kern_mdata, mdata, msize);
1101 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1103 struct bpf_map *map;
1107 for (i = 0; i < obj->nr_maps; i++) {
1108 map = &obj->maps[i];
1110 if (!bpf_map__is_struct_ops(map))
1113 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1122 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1124 const struct btf_type *type, *datasec;
1125 const struct btf_var_secinfo *vsi;
1126 struct bpf_struct_ops *st_ops;
1127 const char *tname, *var_name;
1128 __s32 type_id, datasec_id;
1129 const struct btf *btf;
1130 struct bpf_map *map;
1133 if (obj->efile.st_ops_shndx == -1)
1137 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1139 if (datasec_id < 0) {
1140 pr_warn("struct_ops init: DATASEC %s not found\n",
1145 datasec = btf__type_by_id(btf, datasec_id);
1146 vsi = btf_var_secinfos(datasec);
1147 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1148 type = btf__type_by_id(obj->btf, vsi->type);
1149 var_name = btf__name_by_offset(obj->btf, type->name_off);
1151 type_id = btf__resolve_type(obj->btf, vsi->type);
1153 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1154 vsi->type, STRUCT_OPS_SEC);
1158 type = btf__type_by_id(obj->btf, type_id);
1159 tname = btf__name_by_offset(obj->btf, type->name_off);
1161 pr_warn("struct_ops init: anonymous type is not supported\n");
1164 if (!btf_is_struct(type)) {
1165 pr_warn("struct_ops init: %s is not a struct\n", tname);
1169 map = bpf_object__add_map(obj);
1171 return PTR_ERR(map);
1173 map->sec_idx = obj->efile.st_ops_shndx;
1174 map->sec_offset = vsi->offset;
1175 map->name = strdup(var_name);
1179 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1180 map->def.key_size = sizeof(int);
1181 map->def.value_size = type->size;
1182 map->def.max_entries = 1;
1184 map->st_ops = calloc(1, sizeof(*map->st_ops));
1187 st_ops = map->st_ops;
1188 st_ops->data = malloc(type->size);
1189 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1190 st_ops->kern_func_off = malloc(btf_vlen(type) *
1191 sizeof(*st_ops->kern_func_off));
1192 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1195 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1196 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1197 var_name, STRUCT_OPS_SEC);
1201 memcpy(st_ops->data,
1202 obj->efile.st_ops_data->d_buf + vsi->offset,
1204 st_ops->tname = tname;
1205 st_ops->type = type;
1206 st_ops->type_id = type_id;
1208 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1209 tname, type_id, var_name, vsi->offset);
1215 static struct bpf_object *bpf_object__new(const char *path,
1216 const void *obj_buf,
1218 const char *obj_name)
1220 struct bpf_object *obj;
1223 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1225 pr_warn("alloc memory failed for %s\n", path);
1226 return ERR_PTR(-ENOMEM);
1229 strcpy(obj->path, path);
1231 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1233 /* Using basename() GNU version which doesn't modify arg. */
1234 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1235 end = strchr(obj->name, '.');
1242 * Caller of this function should also call
1243 * bpf_object__elf_finish() after data collection to return
1244 * obj_buf to user. If not, we should duplicate the buffer to
1245 * avoid user freeing them before elf finish.
1247 obj->efile.obj_buf = obj_buf;
1248 obj->efile.obj_buf_sz = obj_buf_sz;
1249 obj->efile.btf_maps_shndx = -1;
1250 obj->efile.st_ops_shndx = -1;
1251 obj->kconfig_map_idx = -1;
1253 obj->kern_version = get_kernel_version();
1254 obj->loaded = false;
1259 static void bpf_object__elf_finish(struct bpf_object *obj)
1261 if (!obj->efile.elf)
1264 elf_end(obj->efile.elf);
1265 obj->efile.elf = NULL;
1266 obj->efile.symbols = NULL;
1267 obj->efile.st_ops_data = NULL;
1269 zfree(&obj->efile.secs);
1270 obj->efile.sec_cnt = 0;
1271 zclose(obj->efile.fd);
1272 obj->efile.obj_buf = NULL;
1273 obj->efile.obj_buf_sz = 0;
1276 static int bpf_object__elf_init(struct bpf_object *obj)
1282 if (obj->efile.elf) {
1283 pr_warn("elf: init internal error\n");
1284 return -LIBBPF_ERRNO__LIBELF;
1287 if (obj->efile.obj_buf_sz > 0) {
1288 /* obj_buf should have been validated by bpf_object__open_mem(). */
1289 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1291 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1292 if (obj->efile.fd < 0) {
1293 char errmsg[STRERR_BUFSIZE], *cp;
1296 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1297 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1301 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1305 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1306 err = -LIBBPF_ERRNO__LIBELF;
1310 obj->efile.elf = elf;
1312 if (elf_kind(elf) != ELF_K_ELF) {
1313 err = -LIBBPF_ERRNO__FORMAT;
1314 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1318 if (gelf_getclass(elf) != ELFCLASS64) {
1319 err = -LIBBPF_ERRNO__FORMAT;
1320 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1324 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1325 if (!obj->efile.ehdr) {
1326 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1327 err = -LIBBPF_ERRNO__FORMAT;
1331 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1332 pr_warn("elf: failed to get section names section index for %s: %s\n",
1333 obj->path, elf_errmsg(-1));
1334 err = -LIBBPF_ERRNO__FORMAT;
1338 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1339 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1340 pr_warn("elf: failed to get section names strings from %s: %s\n",
1341 obj->path, elf_errmsg(-1));
1342 err = -LIBBPF_ERRNO__FORMAT;
1346 /* Old LLVM set e_machine to EM_NONE */
1347 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1348 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1349 err = -LIBBPF_ERRNO__FORMAT;
1355 bpf_object__elf_finish(obj);
1359 static int bpf_object__check_endianness(struct bpf_object *obj)
1361 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1362 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1364 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1365 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1368 # error "Unrecognized __BYTE_ORDER__"
1370 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1371 return -LIBBPF_ERRNO__ENDIAN;
1375 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1378 pr_warn("invalid license section in %s\n", obj->path);
1379 return -LIBBPF_ERRNO__FORMAT;
1381 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1382 * go over allowed ELF data section buffer
1384 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1385 pr_debug("license of %s is %s\n", obj->path, obj->license);
1390 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1394 if (!data || size != sizeof(kver)) {
1395 pr_warn("invalid kver section in %s\n", obj->path);
1396 return -LIBBPF_ERRNO__FORMAT;
1398 memcpy(&kver, data, sizeof(kver));
1399 obj->kern_version = kver;
1400 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1404 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1406 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1407 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1412 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1420 scn = elf_sec_by_name(obj, name);
1421 data = elf_sec_data(obj, scn);
1423 *size = data->d_size;
1424 return 0; /* found it */
1430 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1432 Elf_Data *symbols = obj->efile.symbols;
1436 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1437 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1439 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1442 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1443 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1446 sname = elf_sym_str(obj, sym->st_name);
1448 pr_warn("failed to get sym name string for var %s\n", name);
1449 return ERR_PTR(-EIO);
1451 if (strcmp(name, sname) == 0)
1455 return ERR_PTR(-ENOENT);
1458 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1460 struct bpf_map *map;
1463 err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1464 sizeof(*obj->maps), obj->nr_maps + 1);
1466 return ERR_PTR(err);
1468 map = &obj->maps[obj->nr_maps++];
1471 map->inner_map_fd = -1;
1472 map->autocreate = true;
1477 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1479 long page_sz = sysconf(_SC_PAGE_SIZE);
1482 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1483 map_sz = roundup(map_sz, page_sz);
1487 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1489 char map_name[BPF_OBJ_NAME_LEN], *p;
1490 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1492 /* This is one of the more confusing parts of libbpf for various
1493 * reasons, some of which are historical. The original idea for naming
1494 * internal names was to include as much of BPF object name prefix as
1495 * possible, so that it can be distinguished from similar internal
1496 * maps of a different BPF object.
1497 * As an example, let's say we have bpf_object named 'my_object_name'
1498 * and internal map corresponding to '.rodata' ELF section. The final
1499 * map name advertised to user and to the kernel will be
1500 * 'my_objec.rodata', taking first 8 characters of object name and
1501 * entire 7 characters of '.rodata'.
1502 * Somewhat confusingly, if internal map ELF section name is shorter
1503 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1504 * for the suffix, even though we only have 4 actual characters, and
1505 * resulting map will be called 'my_objec.bss', not even using all 15
1506 * characters allowed by the kernel. Oh well, at least the truncated
1507 * object name is somewhat consistent in this case. But if the map
1508 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1509 * (8 chars) and thus will be left with only first 7 characters of the
1510 * object name ('my_obje'). Happy guessing, user, that the final map
1511 * name will be "my_obje.kconfig".
1512 * Now, with libbpf starting to support arbitrarily named .rodata.*
1513 * and .data.* data sections, it's possible that ELF section name is
1514 * longer than allowed 15 chars, so we now need to be careful to take
1515 * only up to 15 first characters of ELF name, taking no BPF object
1516 * name characters at all. So '.rodata.abracadabra' will result in
1517 * '.rodata.abracad' kernel and user-visible name.
1518 * We need to keep this convoluted logic intact for .data, .bss and
1519 * .rodata maps, but for new custom .data.custom and .rodata.custom
1520 * maps we use their ELF names as is, not prepending bpf_object name
1521 * in front. We still need to truncate them to 15 characters for the
1522 * kernel. Full name can be recovered for such maps by using DATASEC
1523 * BTF type associated with such map's value type, though.
1525 if (sfx_len >= BPF_OBJ_NAME_LEN)
1526 sfx_len = BPF_OBJ_NAME_LEN - 1;
1528 /* if there are two or more dots in map name, it's a custom dot map */
1529 if (strchr(real_name + 1, '.') != NULL)
1532 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1534 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1535 sfx_len, real_name);
1537 /* sanitise map name to characters allowed by kernel */
1538 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1539 if (!isalnum(*p) && *p != '_' && *p != '.')
1542 return strdup(map_name);
1546 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1548 /* Internal BPF map is mmap()'able only if at least one of corresponding
1549 * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1550 * variable and it's not marked as __hidden (which turns it into, effectively,
1551 * a STATIC variable).
1553 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1555 const struct btf_type *t, *vt;
1556 struct btf_var_secinfo *vsi;
1559 if (!map->btf_value_type_id)
1562 t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1563 if (!btf_is_datasec(t))
1566 vsi = btf_var_secinfos(t);
1567 for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1568 vt = btf__type_by_id(obj->btf, vsi->type);
1569 if (!btf_is_var(vt))
1572 if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1580 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1581 const char *real_name, int sec_idx, void *data, size_t data_sz)
1583 struct bpf_map_def *def;
1584 struct bpf_map *map;
1587 map = bpf_object__add_map(obj);
1589 return PTR_ERR(map);
1591 map->libbpf_type = type;
1592 map->sec_idx = sec_idx;
1593 map->sec_offset = 0;
1594 map->real_name = strdup(real_name);
1595 map->name = internal_map_name(obj, real_name);
1596 if (!map->real_name || !map->name) {
1597 zfree(&map->real_name);
1603 def->type = BPF_MAP_TYPE_ARRAY;
1604 def->key_size = sizeof(int);
1605 def->value_size = data_sz;
1606 def->max_entries = 1;
1607 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1608 ? BPF_F_RDONLY_PROG : 0;
1610 /* failures are fine because of maps like .rodata.str1.1 */
1611 (void) map_fill_btf_type_info(obj, map);
1613 if (map_is_mmapable(obj, map))
1614 def->map_flags |= BPF_F_MMAPABLE;
1616 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1617 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1619 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1620 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1621 if (map->mmaped == MAP_FAILED) {
1624 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1626 zfree(&map->real_name);
1632 memcpy(map->mmaped, data, data_sz);
1634 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1638 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1640 struct elf_sec_desc *sec_desc;
1641 const char *sec_name;
1642 int err = 0, sec_idx;
1645 * Populate obj->maps with libbpf internal maps.
1647 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1648 sec_desc = &obj->efile.secs[sec_idx];
1650 /* Skip recognized sections with size 0. */
1651 if (!sec_desc->data || sec_desc->data->d_size == 0)
1654 switch (sec_desc->sec_type) {
1656 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1657 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1659 sec_desc->data->d_buf,
1660 sec_desc->data->d_size);
1663 obj->has_rodata = true;
1664 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1665 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1667 sec_desc->data->d_buf,
1668 sec_desc->data->d_size);
1671 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1672 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1675 sec_desc->data->d_size);
1688 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1693 for (i = 0; i < obj->nr_extern; i++) {
1694 if (strcmp(obj->externs[i].name, name) == 0)
1695 return &obj->externs[i];
1700 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1703 switch (ext->kcfg.type) {
1706 pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1710 *(bool *)ext_val = value == 'y' ? true : false;
1714 *(enum libbpf_tristate *)ext_val = TRI_YES;
1715 else if (value == 'm')
1716 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1717 else /* value == 'n' */
1718 *(enum libbpf_tristate *)ext_val = TRI_NO;
1721 *(char *)ext_val = value;
1727 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1735 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1740 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1741 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1746 len = strlen(value);
1747 if (value[len - 1] != '"') {
1748 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1755 if (len >= ext->kcfg.sz) {
1756 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1757 ext->name, value, len, ext->kcfg.sz - 1);
1758 len = ext->kcfg.sz - 1;
1760 memcpy(ext_val, value + 1, len);
1761 ext_val[len] = '\0';
1766 static int parse_u64(const char *value, __u64 *res)
1772 *res = strtoull(value, &value_end, 0);
1775 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1779 pr_warn("failed to parse '%s' as integer completely\n", value);
1785 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1787 int bit_sz = ext->kcfg.sz * 8;
1789 if (ext->kcfg.sz == 8)
1792 /* Validate that value stored in u64 fits in integer of `ext->sz`
1793 * bytes size without any loss of information. If the target integer
1794 * is signed, we rely on the following limits of integer type of
1795 * Y bits and subsequent transformation:
1797 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1798 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1799 * 0 <= X + 2^(Y-1) < 2^Y
1801 * For unsigned target integer, check that all the (64 - Y) bits are
1804 if (ext->kcfg.is_signed)
1805 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1807 return (v >> bit_sz) == 0;
1810 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1813 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1814 ext->kcfg.type != KCFG_BOOL) {
1815 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1816 ext->name, (unsigned long long)value);
1819 if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1820 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1821 ext->name, (unsigned long long)value);
1825 if (!is_kcfg_value_in_range(ext, value)) {
1826 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1827 ext->name, (unsigned long long)value, ext->kcfg.sz);
1830 switch (ext->kcfg.sz) {
1832 *(__u8 *)ext_val = value;
1835 *(__u16 *)ext_val = value;
1838 *(__u32 *)ext_val = value;
1841 *(__u64 *)ext_val = value;
1850 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1851 char *buf, void *data)
1853 struct extern_desc *ext;
1859 if (!str_has_pfx(buf, "CONFIG_"))
1862 sep = strchr(buf, '=');
1864 pr_warn("failed to parse '%s': no separator\n", buf);
1868 /* Trim ending '\n' */
1870 if (buf[len - 1] == '\n')
1871 buf[len - 1] = '\0';
1872 /* Split on '=' and ensure that a value is present. */
1876 pr_warn("failed to parse '%s': no value\n", buf);
1880 ext = find_extern_by_name(obj, buf);
1881 if (!ext || ext->is_set)
1884 ext_val = data + ext->kcfg.data_off;
1888 case 'y': case 'n': case 'm':
1889 err = set_kcfg_value_tri(ext, ext_val, *value);
1892 err = set_kcfg_value_str(ext, ext_val, value);
1895 /* assume integer */
1896 err = parse_u64(value, &num);
1898 pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1901 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1902 pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1905 err = set_kcfg_value_num(ext, ext_val, num);
1910 pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1914 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1922 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1925 else if (len >= PATH_MAX)
1926 return -ENAMETOOLONG;
1928 /* gzopen also accepts uncompressed files. */
1929 file = gzopen(buf, "r");
1931 file = gzopen("/proc/config.gz", "r");
1934 pr_warn("failed to open system Kconfig\n");
1938 while (gzgets(file, buf, sizeof(buf))) {
1939 err = bpf_object__process_kconfig_line(obj, buf, data);
1941 pr_warn("error parsing system Kconfig line '%s': %d\n",
1952 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1953 const char *config, void *data)
1959 file = fmemopen((void *)config, strlen(config), "r");
1962 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1966 while (fgets(buf, sizeof(buf), file)) {
1967 err = bpf_object__process_kconfig_line(obj, buf, data);
1969 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1979 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1981 struct extern_desc *last_ext = NULL, *ext;
1985 for (i = 0; i < obj->nr_extern; i++) {
1986 ext = &obj->externs[i];
1987 if (ext->type == EXT_KCFG)
1994 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1995 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1996 ".kconfig", obj->efile.symbols_shndx,
2001 obj->kconfig_map_idx = obj->nr_maps - 1;
2006 const struct btf_type *
2007 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2009 const struct btf_type *t = btf__type_by_id(btf, id);
2014 while (btf_is_mod(t) || btf_is_typedef(t)) {
2017 t = btf__type_by_id(btf, t->type);
2023 static const struct btf_type *
2024 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2026 const struct btf_type *t;
2028 t = skip_mods_and_typedefs(btf, id, NULL);
2032 t = skip_mods_and_typedefs(btf, t->type, res_id);
2034 return btf_is_func_proto(t) ? t : NULL;
2037 static const char *__btf_kind_str(__u16 kind)
2040 case BTF_KIND_UNKN: return "void";
2041 case BTF_KIND_INT: return "int";
2042 case BTF_KIND_PTR: return "ptr";
2043 case BTF_KIND_ARRAY: return "array";
2044 case BTF_KIND_STRUCT: return "struct";
2045 case BTF_KIND_UNION: return "union";
2046 case BTF_KIND_ENUM: return "enum";
2047 case BTF_KIND_FWD: return "fwd";
2048 case BTF_KIND_TYPEDEF: return "typedef";
2049 case BTF_KIND_VOLATILE: return "volatile";
2050 case BTF_KIND_CONST: return "const";
2051 case BTF_KIND_RESTRICT: return "restrict";
2052 case BTF_KIND_FUNC: return "func";
2053 case BTF_KIND_FUNC_PROTO: return "func_proto";
2054 case BTF_KIND_VAR: return "var";
2055 case BTF_KIND_DATASEC: return "datasec";
2056 case BTF_KIND_FLOAT: return "float";
2057 case BTF_KIND_DECL_TAG: return "decl_tag";
2058 case BTF_KIND_TYPE_TAG: return "type_tag";
2059 case BTF_KIND_ENUM64: return "enum64";
2060 default: return "unknown";
2064 const char *btf_kind_str(const struct btf_type *t)
2066 return __btf_kind_str(btf_kind(t));
2070 * Fetch integer attribute of BTF map definition. Such attributes are
2071 * represented using a pointer to an array, in which dimensionality of array
2072 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2073 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2074 * type definition, while using only sizeof(void *) space in ELF data section.
2076 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2077 const struct btf_member *m, __u32 *res)
2079 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2080 const char *name = btf__name_by_offset(btf, m->name_off);
2081 const struct btf_array *arr_info;
2082 const struct btf_type *arr_t;
2084 if (!btf_is_ptr(t)) {
2085 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2086 map_name, name, btf_kind_str(t));
2090 arr_t = btf__type_by_id(btf, t->type);
2092 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2093 map_name, name, t->type);
2096 if (!btf_is_array(arr_t)) {
2097 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2098 map_name, name, btf_kind_str(arr_t));
2101 arr_info = btf_array(arr_t);
2102 *res = arr_info->nelems;
2106 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2110 len = snprintf(buf, buf_sz, "%s/%s", path, name);
2114 return -ENAMETOOLONG;
2119 static int build_map_pin_path(struct bpf_map *map, const char *path)
2125 path = "/sys/fs/bpf";
2127 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2131 return bpf_map__set_pin_path(map, buf);
2134 /* should match definition in bpf_helpers.h */
2135 enum libbpf_pin_type {
2137 /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2141 int parse_btf_map_def(const char *map_name, struct btf *btf,
2142 const struct btf_type *def_t, bool strict,
2143 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2145 const struct btf_type *t;
2146 const struct btf_member *m;
2147 bool is_inner = inner_def == NULL;
2150 vlen = btf_vlen(def_t);
2151 m = btf_members(def_t);
2152 for (i = 0; i < vlen; i++, m++) {
2153 const char *name = btf__name_by_offset(btf, m->name_off);
2156 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2159 if (strcmp(name, "type") == 0) {
2160 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2162 map_def->parts |= MAP_DEF_MAP_TYPE;
2163 } else if (strcmp(name, "max_entries") == 0) {
2164 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2166 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2167 } else if (strcmp(name, "map_flags") == 0) {
2168 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2170 map_def->parts |= MAP_DEF_MAP_FLAGS;
2171 } else if (strcmp(name, "numa_node") == 0) {
2172 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2174 map_def->parts |= MAP_DEF_NUMA_NODE;
2175 } else if (strcmp(name, "key_size") == 0) {
2178 if (!get_map_field_int(map_name, btf, m, &sz))
2180 if (map_def->key_size && map_def->key_size != sz) {
2181 pr_warn("map '%s': conflicting key size %u != %u.\n",
2182 map_name, map_def->key_size, sz);
2185 map_def->key_size = sz;
2186 map_def->parts |= MAP_DEF_KEY_SIZE;
2187 } else if (strcmp(name, "key") == 0) {
2190 t = btf__type_by_id(btf, m->type);
2192 pr_warn("map '%s': key type [%d] not found.\n",
2196 if (!btf_is_ptr(t)) {
2197 pr_warn("map '%s': key spec is not PTR: %s.\n",
2198 map_name, btf_kind_str(t));
2201 sz = btf__resolve_size(btf, t->type);
2203 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2204 map_name, t->type, (ssize_t)sz);
2207 if (map_def->key_size && map_def->key_size != sz) {
2208 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2209 map_name, map_def->key_size, (ssize_t)sz);
2212 map_def->key_size = sz;
2213 map_def->key_type_id = t->type;
2214 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2215 } else if (strcmp(name, "value_size") == 0) {
2218 if (!get_map_field_int(map_name, btf, m, &sz))
2220 if (map_def->value_size && map_def->value_size != sz) {
2221 pr_warn("map '%s': conflicting value size %u != %u.\n",
2222 map_name, map_def->value_size, sz);
2225 map_def->value_size = sz;
2226 map_def->parts |= MAP_DEF_VALUE_SIZE;
2227 } else if (strcmp(name, "value") == 0) {
2230 t = btf__type_by_id(btf, m->type);
2232 pr_warn("map '%s': value type [%d] not found.\n",
2236 if (!btf_is_ptr(t)) {
2237 pr_warn("map '%s': value spec is not PTR: %s.\n",
2238 map_name, btf_kind_str(t));
2241 sz = btf__resolve_size(btf, t->type);
2243 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2244 map_name, t->type, (ssize_t)sz);
2247 if (map_def->value_size && map_def->value_size != sz) {
2248 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2249 map_name, map_def->value_size, (ssize_t)sz);
2252 map_def->value_size = sz;
2253 map_def->value_type_id = t->type;
2254 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2256 else if (strcmp(name, "values") == 0) {
2257 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2258 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2259 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2260 char inner_map_name[128];
2264 pr_warn("map '%s': multi-level inner maps not supported.\n",
2268 if (i != vlen - 1) {
2269 pr_warn("map '%s': '%s' member should be last.\n",
2273 if (!is_map_in_map && !is_prog_array) {
2274 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2278 if (map_def->value_size && map_def->value_size != 4) {
2279 pr_warn("map '%s': conflicting value size %u != 4.\n",
2280 map_name, map_def->value_size);
2283 map_def->value_size = 4;
2284 t = btf__type_by_id(btf, m->type);
2286 pr_warn("map '%s': %s type [%d] not found.\n",
2287 map_name, desc, m->type);
2290 if (!btf_is_array(t) || btf_array(t)->nelems) {
2291 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2295 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2296 if (!btf_is_ptr(t)) {
2297 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2298 map_name, desc, btf_kind_str(t));
2301 t = skip_mods_and_typedefs(btf, t->type, NULL);
2302 if (is_prog_array) {
2303 if (!btf_is_func_proto(t)) {
2304 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2305 map_name, btf_kind_str(t));
2310 if (!btf_is_struct(t)) {
2311 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2312 map_name, btf_kind_str(t));
2316 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2317 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2321 map_def->parts |= MAP_DEF_INNER_MAP;
2322 } else if (strcmp(name, "pinning") == 0) {
2326 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2329 if (!get_map_field_int(map_name, btf, m, &val))
2331 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2332 pr_warn("map '%s': invalid pinning value %u.\n",
2336 map_def->pinning = val;
2337 map_def->parts |= MAP_DEF_PINNING;
2338 } else if (strcmp(name, "map_extra") == 0) {
2341 if (!get_map_field_int(map_name, btf, m, &map_extra))
2343 map_def->map_extra = map_extra;
2344 map_def->parts |= MAP_DEF_MAP_EXTRA;
2347 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2350 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2354 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2355 pr_warn("map '%s': map type isn't specified.\n", map_name);
2362 static size_t adjust_ringbuf_sz(size_t sz)
2364 __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2367 /* if user forgot to set any size, make sure they see error */
2370 /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2371 * a power-of-2 multiple of kernel's page size. If user diligently
2372 * satisified these conditions, pass the size through.
2374 if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2377 /* Otherwise find closest (page_sz * power_of_2) product bigger than
2378 * user-set size to satisfy both user size request and kernel
2379 * requirements and substitute correct max_entries for map creation.
2381 for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2382 if (mul * page_sz > sz)
2383 return mul * page_sz;
2386 /* if it's impossible to satisfy the conditions (i.e., user size is
2387 * very close to UINT_MAX but is not a power-of-2 multiple of
2388 * page_size) then just return original size and let kernel reject it
2393 static bool map_is_ringbuf(const struct bpf_map *map)
2395 return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2396 map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2399 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2401 map->def.type = def->map_type;
2402 map->def.key_size = def->key_size;
2403 map->def.value_size = def->value_size;
2404 map->def.max_entries = def->max_entries;
2405 map->def.map_flags = def->map_flags;
2406 map->map_extra = def->map_extra;
2408 map->numa_node = def->numa_node;
2409 map->btf_key_type_id = def->key_type_id;
2410 map->btf_value_type_id = def->value_type_id;
2412 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2413 if (map_is_ringbuf(map))
2414 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2416 if (def->parts & MAP_DEF_MAP_TYPE)
2417 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2419 if (def->parts & MAP_DEF_KEY_TYPE)
2420 pr_debug("map '%s': found key [%u], sz = %u.\n",
2421 map->name, def->key_type_id, def->key_size);
2422 else if (def->parts & MAP_DEF_KEY_SIZE)
2423 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2425 if (def->parts & MAP_DEF_VALUE_TYPE)
2426 pr_debug("map '%s': found value [%u], sz = %u.\n",
2427 map->name, def->value_type_id, def->value_size);
2428 else if (def->parts & MAP_DEF_VALUE_SIZE)
2429 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2431 if (def->parts & MAP_DEF_MAX_ENTRIES)
2432 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2433 if (def->parts & MAP_DEF_MAP_FLAGS)
2434 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2435 if (def->parts & MAP_DEF_MAP_EXTRA)
2436 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2437 (unsigned long long)def->map_extra);
2438 if (def->parts & MAP_DEF_PINNING)
2439 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2440 if (def->parts & MAP_DEF_NUMA_NODE)
2441 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2443 if (def->parts & MAP_DEF_INNER_MAP)
2444 pr_debug("map '%s': found inner map definition.\n", map->name);
2447 static const char *btf_var_linkage_str(__u32 linkage)
2450 case BTF_VAR_STATIC: return "static";
2451 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2452 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2453 default: return "unknown";
2457 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2458 const struct btf_type *sec,
2459 int var_idx, int sec_idx,
2460 const Elf_Data *data, bool strict,
2461 const char *pin_root_path)
2463 struct btf_map_def map_def = {}, inner_def = {};
2464 const struct btf_type *var, *def;
2465 const struct btf_var_secinfo *vi;
2466 const struct btf_var *var_extra;
2467 const char *map_name;
2468 struct bpf_map *map;
2471 vi = btf_var_secinfos(sec) + var_idx;
2472 var = btf__type_by_id(obj->btf, vi->type);
2473 var_extra = btf_var(var);
2474 map_name = btf__name_by_offset(obj->btf, var->name_off);
2476 if (map_name == NULL || map_name[0] == '\0') {
2477 pr_warn("map #%d: empty name.\n", var_idx);
2480 if ((__u64)vi->offset + vi->size > data->d_size) {
2481 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2484 if (!btf_is_var(var)) {
2485 pr_warn("map '%s': unexpected var kind %s.\n",
2486 map_name, btf_kind_str(var));
2489 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2490 pr_warn("map '%s': unsupported map linkage %s.\n",
2491 map_name, btf_var_linkage_str(var_extra->linkage));
2495 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2496 if (!btf_is_struct(def)) {
2497 pr_warn("map '%s': unexpected def kind %s.\n",
2498 map_name, btf_kind_str(var));
2501 if (def->size > vi->size) {
2502 pr_warn("map '%s': invalid def size.\n", map_name);
2506 map = bpf_object__add_map(obj);
2508 return PTR_ERR(map);
2509 map->name = strdup(map_name);
2511 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2514 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2515 map->def.type = BPF_MAP_TYPE_UNSPEC;
2516 map->sec_idx = sec_idx;
2517 map->sec_offset = vi->offset;
2518 map->btf_var_idx = var_idx;
2519 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2520 map_name, map->sec_idx, map->sec_offset);
2522 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2526 fill_map_from_def(map, &map_def);
2528 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2529 err = build_map_pin_path(map, pin_root_path);
2531 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2536 if (map_def.parts & MAP_DEF_INNER_MAP) {
2537 map->inner_map = calloc(1, sizeof(*map->inner_map));
2538 if (!map->inner_map)
2540 map->inner_map->fd = -1;
2541 map->inner_map->sec_idx = sec_idx;
2542 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2543 if (!map->inner_map->name)
2545 sprintf(map->inner_map->name, "%s.inner", map_name);
2547 fill_map_from_def(map->inner_map, &inner_def);
2550 err = map_fill_btf_type_info(obj, map);
2557 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2558 const char *pin_root_path)
2560 const struct btf_type *sec = NULL;
2561 int nr_types, i, vlen, err;
2562 const struct btf_type *t;
2567 if (obj->efile.btf_maps_shndx < 0)
2570 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2571 data = elf_sec_data(obj, scn);
2572 if (!scn || !data) {
2573 pr_warn("elf: failed to get %s map definitions for %s\n",
2574 MAPS_ELF_SEC, obj->path);
2578 nr_types = btf__type_cnt(obj->btf);
2579 for (i = 1; i < nr_types; i++) {
2580 t = btf__type_by_id(obj->btf, i);
2581 if (!btf_is_datasec(t))
2583 name = btf__name_by_offset(obj->btf, t->name_off);
2584 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2586 obj->efile.btf_maps_sec_btf_id = i;
2592 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2596 vlen = btf_vlen(sec);
2597 for (i = 0; i < vlen; i++) {
2598 err = bpf_object__init_user_btf_map(obj, sec, i,
2599 obj->efile.btf_maps_shndx,
2609 static int bpf_object__init_maps(struct bpf_object *obj,
2610 const struct bpf_object_open_opts *opts)
2612 const char *pin_root_path;
2616 strict = !OPTS_GET(opts, relaxed_maps, false);
2617 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2619 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2620 err = err ?: bpf_object__init_global_data_maps(obj);
2621 err = err ?: bpf_object__init_kconfig_map(obj);
2622 err = err ?: bpf_object__init_struct_ops_maps(obj);
2627 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2631 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2635 return sh->sh_flags & SHF_EXECINSTR;
2638 static bool btf_needs_sanitization(struct bpf_object *obj)
2640 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2641 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2642 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2643 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2644 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2645 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2646 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2648 return !has_func || !has_datasec || !has_func_global || !has_float ||
2649 !has_decl_tag || !has_type_tag || !has_enum64;
2652 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2654 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2655 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2656 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2657 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2658 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2659 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2660 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2661 int enum64_placeholder_id = 0;
2665 for (i = 1; i < btf__type_cnt(btf); i++) {
2666 t = (struct btf_type *)btf__type_by_id(btf, i);
2668 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2669 /* replace VAR/DECL_TAG with INT */
2670 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2672 * using size = 1 is the safest choice, 4 will be too
2673 * big and cause kernel BTF validation failure if
2674 * original variable took less than 4 bytes
2677 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2678 } else if (!has_datasec && btf_is_datasec(t)) {
2679 /* replace DATASEC with STRUCT */
2680 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2681 struct btf_member *m = btf_members(t);
2682 struct btf_type *vt;
2685 name = (char *)btf__name_by_offset(btf, t->name_off);
2693 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2694 for (j = 0; j < vlen; j++, v++, m++) {
2695 /* order of field assignments is important */
2696 m->offset = v->offset * 8;
2698 /* preserve variable name as member name */
2699 vt = (void *)btf__type_by_id(btf, v->type);
2700 m->name_off = vt->name_off;
2702 } else if (!has_func && btf_is_func_proto(t)) {
2703 /* replace FUNC_PROTO with ENUM */
2705 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2706 t->size = sizeof(__u32); /* kernel enforced */
2707 } else if (!has_func && btf_is_func(t)) {
2708 /* replace FUNC with TYPEDEF */
2709 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2710 } else if (!has_func_global && btf_is_func(t)) {
2711 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2712 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2713 } else if (!has_float && btf_is_float(t)) {
2714 /* replace FLOAT with an equally-sized empty STRUCT;
2715 * since C compilers do not accept e.g. "float" as a
2716 * valid struct name, make it anonymous
2719 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2720 } else if (!has_type_tag && btf_is_type_tag(t)) {
2721 /* replace TYPE_TAG with a CONST */
2723 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2724 } else if (!has_enum64 && btf_is_enum(t)) {
2725 /* clear the kflag */
2726 t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2727 } else if (!has_enum64 && btf_is_enum64(t)) {
2728 /* replace ENUM64 with a union */
2729 struct btf_member *m;
2731 if (enum64_placeholder_id == 0) {
2732 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2733 if (enum64_placeholder_id < 0)
2734 return enum64_placeholder_id;
2736 t = (struct btf_type *)btf__type_by_id(btf, i);
2741 t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2742 for (j = 0; j < vlen; j++, m++) {
2743 m->type = enum64_placeholder_id;
2752 static bool libbpf_needs_btf(const struct bpf_object *obj)
2754 return obj->efile.btf_maps_shndx >= 0 ||
2755 obj->efile.st_ops_shndx >= 0 ||
2759 static bool kernel_needs_btf(const struct bpf_object *obj)
2761 return obj->efile.st_ops_shndx >= 0;
2764 static int bpf_object__init_btf(struct bpf_object *obj,
2766 Elf_Data *btf_ext_data)
2771 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2772 err = libbpf_get_error(obj->btf);
2775 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2778 /* enforce 8-byte pointers for BPF-targeted BTFs */
2779 btf__set_pointer_size(obj->btf, 8);
2782 struct btf_ext_info *ext_segs[3];
2783 int seg_num, sec_num;
2786 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2787 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2790 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2791 err = libbpf_get_error(obj->btf_ext);
2793 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2794 BTF_EXT_ELF_SEC, err);
2795 obj->btf_ext = NULL;
2799 /* setup .BTF.ext to ELF section mapping */
2800 ext_segs[0] = &obj->btf_ext->func_info;
2801 ext_segs[1] = &obj->btf_ext->line_info;
2802 ext_segs[2] = &obj->btf_ext->core_relo_info;
2803 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2804 struct btf_ext_info *seg = ext_segs[seg_num];
2805 const struct btf_ext_info_sec *sec;
2806 const char *sec_name;
2809 if (seg->sec_cnt == 0)
2812 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2813 if (!seg->sec_idxs) {
2819 for_each_btf_ext_sec(seg, sec) {
2820 /* preventively increment index to avoid doing
2821 * this before every continue below
2825 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2826 if (str_is_empty(sec_name))
2828 scn = elf_sec_by_name(obj, sec_name);
2832 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2837 if (err && libbpf_needs_btf(obj)) {
2838 pr_warn("BTF is required, but is missing or corrupted.\n");
2844 static int compare_vsi_off(const void *_a, const void *_b)
2846 const struct btf_var_secinfo *a = _a;
2847 const struct btf_var_secinfo *b = _b;
2849 return a->offset - b->offset;
2852 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2855 __u32 size = 0, i, vars = btf_vlen(t);
2856 const char *sec_name = btf__name_by_offset(btf, t->name_off);
2857 struct btf_var_secinfo *vsi;
2858 bool fixup_offsets = false;
2862 pr_debug("No name found in string section for DATASEC kind.\n");
2866 /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2867 * variable offsets set at the previous step. Further, not every
2868 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2869 * all fixups altogether for such sections and go straight to sorting
2870 * VARs within their DATASEC.
2872 if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2875 /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2876 * fix this up. But BPF static linker already fixes this up and fills
2877 * all the sizes and offsets during static linking. So this step has
2878 * to be optional. But the STV_HIDDEN handling is non-optional for any
2879 * non-extern DATASEC, so the variable fixup loop below handles both
2880 * functions at the same time, paying the cost of BTF VAR <-> ELF
2881 * symbol matching just once.
2884 err = find_elf_sec_sz(obj, sec_name, &size);
2886 pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2887 sec_name, size, err);
2892 fixup_offsets = true;
2895 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2896 const struct btf_type *t_var;
2897 struct btf_var *var;
2898 const char *var_name;
2901 t_var = btf__type_by_id(btf, vsi->type);
2902 if (!t_var || !btf_is_var(t_var)) {
2903 pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2907 var = btf_var(t_var);
2908 if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2911 var_name = btf__name_by_offset(btf, t_var->name_off);
2913 pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2918 sym = find_elf_var_sym(obj, var_name);
2920 pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2921 sec_name, var_name);
2926 vsi->offset = sym->st_value;
2928 /* if variable is a global/weak symbol, but has restricted
2929 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2930 * as static. This follows similar logic for functions (BPF
2931 * subprogs) and influences libbpf's further decisions about
2932 * whether to make global data BPF array maps as
2935 if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2936 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2937 var->linkage = BTF_VAR_STATIC;
2941 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2945 static int bpf_object_fixup_btf(struct bpf_object *obj)
2952 n = btf__type_cnt(obj->btf);
2953 for (i = 1; i < n; i++) {
2954 struct btf_type *t = btf_type_by_id(obj->btf, i);
2956 /* Loader needs to fix up some of the things compiler
2957 * couldn't get its hands on while emitting BTF. This
2958 * is section size and global variable offset. We use
2959 * the info from the ELF itself for this purpose.
2961 if (btf_is_datasec(t)) {
2962 err = btf_fixup_datasec(obj, obj->btf, t);
2971 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2973 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2974 prog->type == BPF_PROG_TYPE_LSM)
2977 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2978 * also need vmlinux BTF
2980 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2986 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2988 struct bpf_program *prog;
2991 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2994 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2997 /* Support for typed ksyms needs kernel BTF */
2998 for (i = 0; i < obj->nr_extern; i++) {
2999 const struct extern_desc *ext;
3001 ext = &obj->externs[i];
3002 if (ext->type == EXT_KSYM && ext->ksym.type_id)
3006 bpf_object__for_each_program(prog, obj) {
3007 if (!prog->autoload)
3009 if (prog_needs_vmlinux_btf(prog))
3016 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3020 /* btf_vmlinux could be loaded earlier */
3021 if (obj->btf_vmlinux || obj->gen_loader)
3024 if (!force && !obj_needs_vmlinux_btf(obj))
3027 obj->btf_vmlinux = btf__load_vmlinux_btf();
3028 err = libbpf_get_error(obj->btf_vmlinux);
3030 pr_warn("Error loading vmlinux BTF: %d\n", err);
3031 obj->btf_vmlinux = NULL;
3037 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3039 struct btf *kern_btf = obj->btf;
3040 bool btf_mandatory, sanitize;
3046 if (!kernel_supports(obj, FEAT_BTF)) {
3047 if (kernel_needs_btf(obj)) {
3051 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3055 /* Even though some subprogs are global/weak, user might prefer more
3056 * permissive BPF verification process that BPF verifier performs for
3057 * static functions, taking into account more context from the caller
3058 * functions. In such case, they need to mark such subprogs with
3059 * __attribute__((visibility("hidden"))) and libbpf will adjust
3060 * corresponding FUNC BTF type to be marked as static and trigger more
3061 * involved BPF verification process.
3063 for (i = 0; i < obj->nr_programs; i++) {
3064 struct bpf_program *prog = &obj->programs[i];
3069 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3072 n = btf__type_cnt(obj->btf);
3073 for (j = 1; j < n; j++) {
3074 t = btf_type_by_id(obj->btf, j);
3075 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3078 name = btf__str_by_offset(obj->btf, t->name_off);
3079 if (strcmp(name, prog->name) != 0)
3082 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3087 sanitize = btf_needs_sanitization(obj);
3089 const void *raw_data;
3092 /* clone BTF to sanitize a copy and leave the original intact */
3093 raw_data = btf__raw_data(obj->btf, &sz);
3094 kern_btf = btf__new(raw_data, sz);
3095 err = libbpf_get_error(kern_btf);
3099 /* enforce 8-byte pointers for BPF-targeted BTFs */
3100 btf__set_pointer_size(obj->btf, 8);
3101 err = bpf_object__sanitize_btf(obj, kern_btf);
3106 if (obj->gen_loader) {
3108 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3112 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3113 /* Pretend to have valid FD to pass various fd >= 0 checks.
3114 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3116 btf__set_fd(kern_btf, 0);
3118 /* currently BPF_BTF_LOAD only supports log_level 1 */
3119 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3120 obj->log_level ? 1 : 0);
3124 /* move fd to libbpf's BTF */
3125 btf__set_fd(obj->btf, btf__fd(kern_btf));
3126 btf__set_fd(kern_btf, -1);
3128 btf__free(kern_btf);
3132 btf_mandatory = kernel_needs_btf(obj);
3133 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3134 btf_mandatory ? "BTF is mandatory, can't proceed."
3135 : "BTF is optional, ignoring.");
3142 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3146 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3148 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3149 off, obj->path, elf_errmsg(-1));
3156 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3160 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3162 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3163 off, obj->path, elf_errmsg(-1));
3170 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3174 scn = elf_getscn(obj->efile.elf, idx);
3176 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3177 idx, obj->path, elf_errmsg(-1));
3183 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3185 Elf_Scn *scn = NULL;
3186 Elf *elf = obj->efile.elf;
3187 const char *sec_name;
3189 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3190 sec_name = elf_sec_name(obj, scn);
3194 if (strcmp(sec_name, name) != 0)
3202 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3209 shdr = elf64_getshdr(scn);
3211 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3212 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3219 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3227 sh = elf_sec_hdr(obj, scn);
3231 name = elf_sec_str(obj, sh->sh_name);
3233 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3234 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3241 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3248 data = elf_getdata(scn, 0);
3250 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3251 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3252 obj->path, elf_errmsg(-1));
3259 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3261 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3264 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3267 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3269 if (idx >= data->d_size / sizeof(Elf64_Rel))
3272 return (Elf64_Rel *)data->d_buf + idx;
3275 static bool is_sec_name_dwarf(const char *name)
3277 /* approximation, but the actual list is too long */
3278 return str_has_pfx(name, ".debug_");
3281 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3283 /* no special handling of .strtab */
3284 if (hdr->sh_type == SHT_STRTAB)
3287 /* ignore .llvm_addrsig section as well */
3288 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3291 /* no subprograms will lead to an empty .text section, ignore it */
3292 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3293 strcmp(name, ".text") == 0)
3296 /* DWARF sections */
3297 if (is_sec_name_dwarf(name))
3300 if (str_has_pfx(name, ".rel")) {
3301 name += sizeof(".rel") - 1;
3302 /* DWARF section relocations */
3303 if (is_sec_name_dwarf(name))
3306 /* .BTF and .BTF.ext don't need relocations */
3307 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3308 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3315 static int cmp_progs(const void *_a, const void *_b)
3317 const struct bpf_program *a = _a;
3318 const struct bpf_program *b = _b;
3320 if (a->sec_idx != b->sec_idx)
3321 return a->sec_idx < b->sec_idx ? -1 : 1;
3323 /* sec_insn_off can't be the same within the section */
3324 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3327 static int bpf_object__elf_collect(struct bpf_object *obj)
3329 struct elf_sec_desc *sec_desc;
3330 Elf *elf = obj->efile.elf;
3331 Elf_Data *btf_ext_data = NULL;
3332 Elf_Data *btf_data = NULL;
3333 int idx = 0, err = 0;
3339 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3340 * section. Since section count retrieved by elf_getshdrnum() does
3341 * include sec #0, it is already the necessary size of an array to keep
3344 if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3345 pr_warn("elf: failed to get the number of sections for %s: %s\n",
3346 obj->path, elf_errmsg(-1));
3347 return -LIBBPF_ERRNO__FORMAT;
3349 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3350 if (!obj->efile.secs)
3353 /* a bunch of ELF parsing functionality depends on processing symbols,
3354 * so do the first pass and find the symbol table
3357 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3358 sh = elf_sec_hdr(obj, scn);
3360 return -LIBBPF_ERRNO__FORMAT;
3362 if (sh->sh_type == SHT_SYMTAB) {
3363 if (obj->efile.symbols) {
3364 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3365 return -LIBBPF_ERRNO__FORMAT;
3368 data = elf_sec_data(obj, scn);
3370 return -LIBBPF_ERRNO__FORMAT;
3372 idx = elf_ndxscn(scn);
3374 obj->efile.symbols = data;
3375 obj->efile.symbols_shndx = idx;
3376 obj->efile.strtabidx = sh->sh_link;
3380 if (!obj->efile.symbols) {
3381 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3387 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3388 idx = elf_ndxscn(scn);
3389 sec_desc = &obj->efile.secs[idx];
3391 sh = elf_sec_hdr(obj, scn);
3393 return -LIBBPF_ERRNO__FORMAT;
3395 name = elf_sec_str(obj, sh->sh_name);
3397 return -LIBBPF_ERRNO__FORMAT;
3399 if (ignore_elf_section(sh, name))
3402 data = elf_sec_data(obj, scn);
3404 return -LIBBPF_ERRNO__FORMAT;
3406 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3407 idx, name, (unsigned long)data->d_size,
3408 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3411 if (strcmp(name, "license") == 0) {
3412 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3415 } else if (strcmp(name, "version") == 0) {
3416 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3419 } else if (strcmp(name, "maps") == 0) {
3420 pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3422 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3423 obj->efile.btf_maps_shndx = idx;
3424 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3425 if (sh->sh_type != SHT_PROGBITS)
3426 return -LIBBPF_ERRNO__FORMAT;
3428 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3429 if (sh->sh_type != SHT_PROGBITS)
3430 return -LIBBPF_ERRNO__FORMAT;
3431 btf_ext_data = data;
3432 } else if (sh->sh_type == SHT_SYMTAB) {
3433 /* already processed during the first pass above */
3434 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3435 if (sh->sh_flags & SHF_EXECINSTR) {
3436 if (strcmp(name, ".text") == 0)
3437 obj->efile.text_shndx = idx;
3438 err = bpf_object__add_programs(obj, data, name, idx);
3441 } else if (strcmp(name, DATA_SEC) == 0 ||
3442 str_has_pfx(name, DATA_SEC ".")) {
3443 sec_desc->sec_type = SEC_DATA;
3444 sec_desc->shdr = sh;
3445 sec_desc->data = data;
3446 } else if (strcmp(name, RODATA_SEC) == 0 ||
3447 str_has_pfx(name, RODATA_SEC ".")) {
3448 sec_desc->sec_type = SEC_RODATA;
3449 sec_desc->shdr = sh;
3450 sec_desc->data = data;
3451 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3452 obj->efile.st_ops_data = data;
3453 obj->efile.st_ops_shndx = idx;
3455 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3458 } else if (sh->sh_type == SHT_REL) {
3459 int targ_sec_idx = sh->sh_info; /* points to other section */
3461 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3462 targ_sec_idx >= obj->efile.sec_cnt)
3463 return -LIBBPF_ERRNO__FORMAT;
3465 /* Only do relo for section with exec instructions */
3466 if (!section_have_execinstr(obj, targ_sec_idx) &&
3467 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3468 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3469 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3470 idx, name, targ_sec_idx,
3471 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3475 sec_desc->sec_type = SEC_RELO;
3476 sec_desc->shdr = sh;
3477 sec_desc->data = data;
3478 } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3479 str_has_pfx(name, BSS_SEC "."))) {
3480 sec_desc->sec_type = SEC_BSS;
3481 sec_desc->shdr = sh;
3482 sec_desc->data = data;
3484 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3485 (size_t)sh->sh_size);
3489 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3490 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3491 return -LIBBPF_ERRNO__FORMAT;
3494 /* sort BPF programs by section name and in-section instruction offset
3497 if (obj->nr_programs)
3498 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3500 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3503 static bool sym_is_extern(const Elf64_Sym *sym)
3505 int bind = ELF64_ST_BIND(sym->st_info);
3506 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3507 return sym->st_shndx == SHN_UNDEF &&
3508 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3509 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3512 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3514 int bind = ELF64_ST_BIND(sym->st_info);
3515 int type = ELF64_ST_TYPE(sym->st_info);
3517 /* in .text section */
3518 if (sym->st_shndx != text_shndx)
3521 /* local function */
3522 if (bind == STB_LOCAL && type == STT_SECTION)
3525 /* global function */
3526 return bind == STB_GLOBAL && type == STT_FUNC;
3529 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3531 const struct btf_type *t;
3538 n = btf__type_cnt(btf);
3539 for (i = 1; i < n; i++) {
3540 t = btf__type_by_id(btf, i);
3542 if (!btf_is_var(t) && !btf_is_func(t))
3545 tname = btf__name_by_offset(btf, t->name_off);
3546 if (strcmp(tname, ext_name))
3549 if (btf_is_var(t) &&
3550 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3553 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3562 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3563 const struct btf_var_secinfo *vs;
3564 const struct btf_type *t;
3570 n = btf__type_cnt(btf);
3571 for (i = 1; i < n; i++) {
3572 t = btf__type_by_id(btf, i);
3574 if (!btf_is_datasec(t))
3577 vs = btf_var_secinfos(t);
3578 for (j = 0; j < btf_vlen(t); j++, vs++) {
3579 if (vs->type == ext_btf_id)
3587 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3590 const struct btf_type *t;
3593 t = skip_mods_and_typedefs(btf, id, NULL);
3594 name = btf__name_by_offset(btf, t->name_off);
3598 switch (btf_kind(t)) {
3599 case BTF_KIND_INT: {
3600 int enc = btf_int_encoding(t);
3602 if (enc & BTF_INT_BOOL)
3603 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3605 *is_signed = enc & BTF_INT_SIGNED;
3608 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3609 return KCFG_UNKNOWN;
3614 return KCFG_UNKNOWN;
3615 if (strcmp(name, "libbpf_tristate"))
3616 return KCFG_UNKNOWN;
3617 return KCFG_TRISTATE;
3618 case BTF_KIND_ENUM64:
3619 if (strcmp(name, "libbpf_tristate"))
3620 return KCFG_UNKNOWN;
3621 return KCFG_TRISTATE;
3622 case BTF_KIND_ARRAY:
3623 if (btf_array(t)->nelems == 0)
3624 return KCFG_UNKNOWN;
3625 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3626 return KCFG_UNKNOWN;
3627 return KCFG_CHAR_ARR;
3629 return KCFG_UNKNOWN;
3633 static int cmp_externs(const void *_a, const void *_b)
3635 const struct extern_desc *a = _a;
3636 const struct extern_desc *b = _b;
3638 if (a->type != b->type)
3639 return a->type < b->type ? -1 : 1;
3641 if (a->type == EXT_KCFG) {
3642 /* descending order by alignment requirements */
3643 if (a->kcfg.align != b->kcfg.align)
3644 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3645 /* ascending order by size, within same alignment class */
3646 if (a->kcfg.sz != b->kcfg.sz)
3647 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3650 /* resolve ties by name */
3651 return strcmp(a->name, b->name);
3654 static int find_int_btf_id(const struct btf *btf)
3656 const struct btf_type *t;
3659 n = btf__type_cnt(btf);
3660 for (i = 1; i < n; i++) {
3661 t = btf__type_by_id(btf, i);
3663 if (btf_is_int(t) && btf_int_bits(t) == 32)
3670 static int add_dummy_ksym_var(struct btf *btf)
3672 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3673 const struct btf_var_secinfo *vs;
3674 const struct btf_type *sec;
3679 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3684 sec = btf__type_by_id(btf, sec_btf_id);
3685 vs = btf_var_secinfos(sec);
3686 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3687 const struct btf_type *vt;
3689 vt = btf__type_by_id(btf, vs->type);
3690 if (btf_is_func(vt))
3694 /* No func in ksyms sec. No need to add dummy var. */
3695 if (i == btf_vlen(sec))
3698 int_btf_id = find_int_btf_id(btf);
3699 dummy_var_btf_id = btf__add_var(btf,
3701 BTF_VAR_GLOBAL_ALLOCATED,
3703 if (dummy_var_btf_id < 0)
3704 pr_warn("cannot create a dummy_ksym var\n");
3706 return dummy_var_btf_id;
3709 static int bpf_object__collect_externs(struct bpf_object *obj)
3711 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3712 const struct btf_type *t;
3713 struct extern_desc *ext;
3714 int i, n, off, dummy_var_btf_id;
3715 const char *ext_name, *sec_name;
3719 if (!obj->efile.symbols)
3722 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3723 sh = elf_sec_hdr(obj, scn);
3724 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3725 return -LIBBPF_ERRNO__FORMAT;
3727 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3728 if (dummy_var_btf_id < 0)
3729 return dummy_var_btf_id;
3731 n = sh->sh_size / sh->sh_entsize;
3732 pr_debug("looking for externs among %d symbols...\n", n);
3734 for (i = 0; i < n; i++) {
3735 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3738 return -LIBBPF_ERRNO__FORMAT;
3739 if (!sym_is_extern(sym))
3741 ext_name = elf_sym_str(obj, sym->st_name);
3742 if (!ext_name || !ext_name[0])
3746 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3750 ext = &ext[obj->nr_extern];
3751 memset(ext, 0, sizeof(*ext));
3754 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3755 if (ext->btf_id <= 0) {
3756 pr_warn("failed to find BTF for extern '%s': %d\n",
3757 ext_name, ext->btf_id);
3760 t = btf__type_by_id(obj->btf, ext->btf_id);
3761 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3763 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3765 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3766 if (ext->sec_btf_id <= 0) {
3767 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3768 ext_name, ext->btf_id, ext->sec_btf_id);
3769 return ext->sec_btf_id;
3771 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3772 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3774 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3775 if (btf_is_func(t)) {
3776 pr_warn("extern function %s is unsupported under %s section\n",
3777 ext->name, KCONFIG_SEC);
3781 ext->type = EXT_KCFG;
3782 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3783 if (ext->kcfg.sz <= 0) {
3784 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3785 ext_name, ext->kcfg.sz);
3786 return ext->kcfg.sz;
3788 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3789 if (ext->kcfg.align <= 0) {
3790 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3791 ext_name, ext->kcfg.align);
3794 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3795 &ext->kcfg.is_signed);
3796 if (ext->kcfg.type == KCFG_UNKNOWN) {
3797 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3800 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3802 ext->type = EXT_KSYM;
3803 skip_mods_and_typedefs(obj->btf, t->type,
3804 &ext->ksym.type_id);
3806 pr_warn("unrecognized extern section '%s'\n", sec_name);
3810 pr_debug("collected %d externs total\n", obj->nr_extern);
3812 if (!obj->nr_extern)
3815 /* sort externs by type, for kcfg ones also by (align, size, name) */
3816 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3818 /* for .ksyms section, we need to turn all externs into allocated
3819 * variables in BTF to pass kernel verification; we do this by
3820 * pretending that each extern is a 8-byte variable
3823 /* find existing 4-byte integer type in BTF to use for fake
3824 * extern variables in DATASEC
3826 int int_btf_id = find_int_btf_id(obj->btf);
3827 /* For extern function, a dummy_var added earlier
3828 * will be used to replace the vs->type and
3829 * its name string will be used to refill
3830 * the missing param's name.
3832 const struct btf_type *dummy_var;
3834 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3835 for (i = 0; i < obj->nr_extern; i++) {
3836 ext = &obj->externs[i];
3837 if (ext->type != EXT_KSYM)
3839 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3840 i, ext->sym_idx, ext->name);
3845 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3846 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3847 struct btf_type *vt;
3849 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3850 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3851 ext = find_extern_by_name(obj, ext_name);
3853 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3854 btf_kind_str(vt), ext_name);
3857 if (btf_is_func(vt)) {
3858 const struct btf_type *func_proto;
3859 struct btf_param *param;
3862 func_proto = btf__type_by_id(obj->btf,
3864 param = btf_params(func_proto);
3865 /* Reuse the dummy_var string if the
3866 * func proto does not have param name.
3868 for (j = 0; j < btf_vlen(func_proto); j++)
3869 if (param[j].type && !param[j].name_off)
3871 dummy_var->name_off;
3872 vs->type = dummy_var_btf_id;
3873 vt->info &= ~0xffff;
3874 vt->info |= BTF_FUNC_GLOBAL;
3876 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3877 vt->type = int_btf_id;
3880 vs->size = sizeof(int);
3887 /* for kcfg externs calculate their offsets within a .kconfig map */
3889 for (i = 0; i < obj->nr_extern; i++) {
3890 ext = &obj->externs[i];
3891 if (ext->type != EXT_KCFG)
3894 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3895 off = ext->kcfg.data_off + ext->kcfg.sz;
3896 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3897 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3901 for (i = 0; i < n; i++) {
3902 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3904 t = btf__type_by_id(obj->btf, vs->type);
3905 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3906 ext = find_extern_by_name(obj, ext_name);
3908 pr_warn("failed to find extern definition for BTF var '%s'\n",
3912 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3913 vs->offset = ext->kcfg.data_off;
3919 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3921 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3924 struct bpf_program *
3925 bpf_object__find_program_by_name(const struct bpf_object *obj,
3928 struct bpf_program *prog;
3930 bpf_object__for_each_program(prog, obj) {
3931 if (prog_is_subprog(obj, prog))
3933 if (!strcmp(prog->name, name))
3936 return errno = ENOENT, NULL;
3939 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3942 switch (obj->efile.secs[shndx].sec_type) {
3952 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3955 return shndx == obj->efile.btf_maps_shndx;
3958 static enum libbpf_map_type
3959 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3961 if (shndx == obj->efile.symbols_shndx)
3962 return LIBBPF_MAP_KCONFIG;
3964 switch (obj->efile.secs[shndx].sec_type) {
3966 return LIBBPF_MAP_BSS;
3968 return LIBBPF_MAP_DATA;
3970 return LIBBPF_MAP_RODATA;
3972 return LIBBPF_MAP_UNSPEC;
3976 static int bpf_program__record_reloc(struct bpf_program *prog,
3977 struct reloc_desc *reloc_desc,
3978 __u32 insn_idx, const char *sym_name,
3979 const Elf64_Sym *sym, const Elf64_Rel *rel)
3981 struct bpf_insn *insn = &prog->insns[insn_idx];
3982 size_t map_idx, nr_maps = prog->obj->nr_maps;
3983 struct bpf_object *obj = prog->obj;
3984 __u32 shdr_idx = sym->st_shndx;
3985 enum libbpf_map_type type;
3986 const char *sym_sec_name;
3987 struct bpf_map *map;
3989 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3990 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3991 prog->name, sym_name, insn_idx, insn->code);
3992 return -LIBBPF_ERRNO__RELOC;
3995 if (sym_is_extern(sym)) {
3996 int sym_idx = ELF64_R_SYM(rel->r_info);
3997 int i, n = obj->nr_extern;
3998 struct extern_desc *ext;
4000 for (i = 0; i < n; i++) {
4001 ext = &obj->externs[i];
4002 if (ext->sym_idx == sym_idx)
4006 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4007 prog->name, sym_name, sym_idx);
4008 return -LIBBPF_ERRNO__RELOC;
4010 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4011 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4012 if (insn->code == (BPF_JMP | BPF_CALL))
4013 reloc_desc->type = RELO_EXTERN_CALL;
4015 reloc_desc->type = RELO_EXTERN_LD64;
4016 reloc_desc->insn_idx = insn_idx;
4017 reloc_desc->sym_off = i; /* sym_off stores extern index */
4021 /* sub-program call relocation */
4022 if (is_call_insn(insn)) {
4023 if (insn->src_reg != BPF_PSEUDO_CALL) {
4024 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4025 return -LIBBPF_ERRNO__RELOC;
4027 /* text_shndx can be 0, if no default "main" program exists */
4028 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4029 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4030 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4031 prog->name, sym_name, sym_sec_name);
4032 return -LIBBPF_ERRNO__RELOC;
4034 if (sym->st_value % BPF_INSN_SZ) {
4035 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4036 prog->name, sym_name, (size_t)sym->st_value);
4037 return -LIBBPF_ERRNO__RELOC;
4039 reloc_desc->type = RELO_CALL;
4040 reloc_desc->insn_idx = insn_idx;
4041 reloc_desc->sym_off = sym->st_value;
4045 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4046 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4047 prog->name, sym_name, shdr_idx);
4048 return -LIBBPF_ERRNO__RELOC;
4051 /* loading subprog addresses */
4052 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4053 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4054 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4056 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4057 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4058 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4059 return -LIBBPF_ERRNO__RELOC;
4062 reloc_desc->type = RELO_SUBPROG_ADDR;
4063 reloc_desc->insn_idx = insn_idx;
4064 reloc_desc->sym_off = sym->st_value;
4068 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4069 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4071 /* generic map reference relocation */
4072 if (type == LIBBPF_MAP_UNSPEC) {
4073 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4074 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4075 prog->name, sym_name, sym_sec_name);
4076 return -LIBBPF_ERRNO__RELOC;
4078 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4079 map = &obj->maps[map_idx];
4080 if (map->libbpf_type != type ||
4081 map->sec_idx != sym->st_shndx ||
4082 map->sec_offset != sym->st_value)
4084 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4085 prog->name, map_idx, map->name, map->sec_idx,
4086 map->sec_offset, insn_idx);
4089 if (map_idx >= nr_maps) {
4090 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4091 prog->name, sym_sec_name, (size_t)sym->st_value);
4092 return -LIBBPF_ERRNO__RELOC;
4094 reloc_desc->type = RELO_LD64;
4095 reloc_desc->insn_idx = insn_idx;
4096 reloc_desc->map_idx = map_idx;
4097 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4101 /* global data map relocation */
4102 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4103 pr_warn("prog '%s': bad data relo against section '%s'\n",
4104 prog->name, sym_sec_name);
4105 return -LIBBPF_ERRNO__RELOC;
4107 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4108 map = &obj->maps[map_idx];
4109 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4111 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4112 prog->name, map_idx, map->name, map->sec_idx,
4113 map->sec_offset, insn_idx);
4116 if (map_idx >= nr_maps) {
4117 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4118 prog->name, sym_sec_name);
4119 return -LIBBPF_ERRNO__RELOC;
4122 reloc_desc->type = RELO_DATA;
4123 reloc_desc->insn_idx = insn_idx;
4124 reloc_desc->map_idx = map_idx;
4125 reloc_desc->sym_off = sym->st_value;
4129 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4131 return insn_idx >= prog->sec_insn_off &&
4132 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4135 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4136 size_t sec_idx, size_t insn_idx)
4138 int l = 0, r = obj->nr_programs - 1, m;
4139 struct bpf_program *prog;
4141 if (!obj->nr_programs)
4145 m = l + (r - l + 1) / 2;
4146 prog = &obj->programs[m];
4148 if (prog->sec_idx < sec_idx ||
4149 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4154 /* matching program could be at index l, but it still might be the
4155 * wrong one, so we need to double check conditions for the last time
4157 prog = &obj->programs[l];
4158 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4164 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4166 const char *relo_sec_name, *sec_name;
4167 size_t sec_idx = shdr->sh_info, sym_idx;
4168 struct bpf_program *prog;
4169 struct reloc_desc *relos;
4171 const char *sym_name;
4178 if (sec_idx >= obj->efile.sec_cnt)
4181 scn = elf_sec_by_idx(obj, sec_idx);
4182 scn_data = elf_sec_data(obj, scn);
4184 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4185 sec_name = elf_sec_name(obj, scn);
4186 if (!relo_sec_name || !sec_name)
4189 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4190 relo_sec_name, sec_idx, sec_name);
4191 nrels = shdr->sh_size / shdr->sh_entsize;
4193 for (i = 0; i < nrels; i++) {
4194 rel = elf_rel_by_idx(data, i);
4196 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4197 return -LIBBPF_ERRNO__FORMAT;
4200 sym_idx = ELF64_R_SYM(rel->r_info);
4201 sym = elf_sym_by_idx(obj, sym_idx);
4203 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4204 relo_sec_name, sym_idx, i);
4205 return -LIBBPF_ERRNO__FORMAT;
4208 if (sym->st_shndx >= obj->efile.sec_cnt) {
4209 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4210 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4211 return -LIBBPF_ERRNO__FORMAT;
4214 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4215 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4216 relo_sec_name, (size_t)rel->r_offset, i);
4217 return -LIBBPF_ERRNO__FORMAT;
4220 insn_idx = rel->r_offset / BPF_INSN_SZ;
4221 /* relocations against static functions are recorded as
4222 * relocations against the section that contains a function;
4223 * in such case, symbol will be STT_SECTION and sym.st_name
4224 * will point to empty string (0), so fetch section name
4227 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4228 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4230 sym_name = elf_sym_str(obj, sym->st_name);
4231 sym_name = sym_name ?: "<?";
4233 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4234 relo_sec_name, i, insn_idx, sym_name);
4236 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4238 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4239 relo_sec_name, i, sec_name, insn_idx);
4243 relos = libbpf_reallocarray(prog->reloc_desc,
4244 prog->nr_reloc + 1, sizeof(*relos));
4247 prog->reloc_desc = relos;
4249 /* adjust insn_idx to local BPF program frame of reference */
4250 insn_idx -= prog->sec_insn_off;
4251 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4252 insn_idx, sym_name, sym, rel);
4261 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4268 /* if it's BTF-defined map, we don't need to search for type IDs.
4269 * For struct_ops map, it does not need btf_key_type_id and
4270 * btf_value_type_id.
4272 if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4276 * LLVM annotates global data differently in BTF, that is,
4277 * only as '.data', '.bss' or '.rodata'.
4279 if (!bpf_map__is_internal(map))
4282 id = btf__find_by_name(obj->btf, map->real_name);
4286 map->btf_key_type_id = 0;
4287 map->btf_value_type_id = id;
4291 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4293 char file[PATH_MAX], buff[4096];
4298 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4299 memset(info, 0, sizeof(*info));
4301 fp = fopen(file, "r");
4304 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4309 while (fgets(buff, sizeof(buff), fp)) {
4310 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4312 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4313 info->key_size = val;
4314 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4315 info->value_size = val;
4316 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4317 info->max_entries = val;
4318 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4319 info->map_flags = val;
4327 bool bpf_map__autocreate(const struct bpf_map *map)
4329 return map->autocreate;
4332 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4334 if (map->obj->loaded)
4335 return libbpf_err(-EBUSY);
4337 map->autocreate = autocreate;
4341 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4343 struct bpf_map_info info;
4344 __u32 len = sizeof(info), name_len;
4348 memset(&info, 0, len);
4349 err = bpf_map_get_info_by_fd(fd, &info, &len);
4350 if (err && errno == EINVAL)
4351 err = bpf_get_map_info_from_fdinfo(fd, &info);
4353 return libbpf_err(err);
4355 name_len = strlen(info.name);
4356 if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4357 new_name = strdup(map->name);
4359 new_name = strdup(info.name);
4362 return libbpf_err(-errno);
4364 new_fd = open("/", O_RDONLY | O_CLOEXEC);
4367 goto err_free_new_name;
4370 new_fd = dup3(fd, new_fd, O_CLOEXEC);
4373 goto err_close_new_fd;
4376 err = zclose(map->fd);
4379 goto err_close_new_fd;
4384 map->name = new_name;
4385 map->def.type = info.type;
4386 map->def.key_size = info.key_size;
4387 map->def.value_size = info.value_size;
4388 map->def.max_entries = info.max_entries;
4389 map->def.map_flags = info.map_flags;
4390 map->btf_key_type_id = info.btf_key_type_id;
4391 map->btf_value_type_id = info.btf_value_type_id;
4393 map->map_extra = info.map_extra;
4401 return libbpf_err(err);
4404 __u32 bpf_map__max_entries(const struct bpf_map *map)
4406 return map->def.max_entries;
4409 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4411 if (!bpf_map_type__is_map_in_map(map->def.type))
4412 return errno = EINVAL, NULL;
4414 return map->inner_map;
4417 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4419 if (map->obj->loaded)
4420 return libbpf_err(-EBUSY);
4422 map->def.max_entries = max_entries;
4424 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4425 if (map_is_ringbuf(map))
4426 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4432 bpf_object__probe_loading(struct bpf_object *obj)
4434 char *cp, errmsg[STRERR_BUFSIZE];
4435 struct bpf_insn insns[] = {
4436 BPF_MOV64_IMM(BPF_REG_0, 0),
4439 int ret, insn_cnt = ARRAY_SIZE(insns);
4441 if (obj->gen_loader)
4444 ret = bump_rlimit_memlock();
4446 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4448 /* make sure basic loading works */
4449 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4451 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4454 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4455 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4456 "program. Make sure your kernel supports BPF "
4457 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4458 "set to big enough value.\n", __func__, cp, ret);
4466 static int probe_fd(int fd)
4473 static int probe_kern_prog_name(void)
4475 const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4476 struct bpf_insn insns[] = {
4477 BPF_MOV64_IMM(BPF_REG_0, 0),
4480 union bpf_attr attr;
4483 memset(&attr, 0, attr_sz);
4484 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4485 attr.license = ptr_to_u64("GPL");
4486 attr.insns = ptr_to_u64(insns);
4487 attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4488 libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4490 /* make sure loading with name works */
4491 ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4492 return probe_fd(ret);
4495 static int probe_kern_global_data(void)
4497 char *cp, errmsg[STRERR_BUFSIZE];
4498 struct bpf_insn insns[] = {
4499 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4500 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4501 BPF_MOV64_IMM(BPF_REG_0, 0),
4504 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4506 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4509 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4510 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4511 __func__, cp, -ret);
4517 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4519 return probe_fd(ret);
4522 static int probe_kern_btf(void)
4524 static const char strs[] = "\0int";
4527 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4530 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4531 strs, sizeof(strs)));
4534 static int probe_kern_btf_func(void)
4536 static const char strs[] = "\0int\0x\0a";
4537 /* void x(int a) {} */
4540 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4541 /* FUNC_PROTO */ /* [2] */
4542 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4543 BTF_PARAM_ENC(7, 1),
4544 /* FUNC x */ /* [3] */
4545 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4548 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4549 strs, sizeof(strs)));
4552 static int probe_kern_btf_func_global(void)
4554 static const char strs[] = "\0int\0x\0a";
4555 /* static void x(int a) {} */
4558 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4559 /* FUNC_PROTO */ /* [2] */
4560 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4561 BTF_PARAM_ENC(7, 1),
4562 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4563 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4566 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4567 strs, sizeof(strs)));
4570 static int probe_kern_btf_datasec(void)
4572 static const char strs[] = "\0x\0.data";
4576 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4577 /* VAR x */ /* [2] */
4578 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4580 /* DATASEC val */ /* [3] */
4581 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4582 BTF_VAR_SECINFO_ENC(2, 0, 4),
4585 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4586 strs, sizeof(strs)));
4589 static int probe_kern_btf_float(void)
4591 static const char strs[] = "\0float";
4594 BTF_TYPE_FLOAT_ENC(1, 4),
4597 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4598 strs, sizeof(strs)));
4601 static int probe_kern_btf_decl_tag(void)
4603 static const char strs[] = "\0tag";
4606 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4607 /* VAR x */ /* [2] */
4608 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4611 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4614 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4615 strs, sizeof(strs)));
4618 static int probe_kern_btf_type_tag(void)
4620 static const char strs[] = "\0tag";
4623 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4625 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4627 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4630 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4631 strs, sizeof(strs)));
4634 static int probe_kern_array_mmap(void)
4636 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4639 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4640 return probe_fd(fd);
4643 static int probe_kern_exp_attach_type(void)
4645 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4646 struct bpf_insn insns[] = {
4647 BPF_MOV64_IMM(BPF_REG_0, 0),
4650 int fd, insn_cnt = ARRAY_SIZE(insns);
4652 /* use any valid combination of program type and (optional)
4653 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4654 * to see if kernel supports expected_attach_type field for
4655 * BPF_PROG_LOAD command
4657 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4658 return probe_fd(fd);
4661 static int probe_kern_probe_read_kernel(void)
4663 struct bpf_insn insns[] = {
4664 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4665 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4666 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4667 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4668 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4671 int fd, insn_cnt = ARRAY_SIZE(insns);
4673 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4674 return probe_fd(fd);
4677 static int probe_prog_bind_map(void)
4679 char *cp, errmsg[STRERR_BUFSIZE];
4680 struct bpf_insn insns[] = {
4681 BPF_MOV64_IMM(BPF_REG_0, 0),
4684 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4686 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4689 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4690 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4691 __func__, cp, -ret);
4695 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4701 ret = bpf_prog_bind_map(prog, map, NULL);
4709 static int probe_module_btf(void)
4711 static const char strs[] = "\0int";
4714 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4716 struct bpf_btf_info info;
4717 __u32 len = sizeof(info);
4721 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4723 return 0; /* BTF not supported at all */
4725 memset(&info, 0, sizeof(info));
4726 info.name = ptr_to_u64(name);
4727 info.name_len = sizeof(name);
4729 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4730 * kernel's module BTF support coincides with support for
4731 * name/name_len fields in struct bpf_btf_info.
4733 err = bpf_btf_get_info_by_fd(fd, &info, &len);
4738 static int probe_perf_link(void)
4740 struct bpf_insn insns[] = {
4741 BPF_MOV64_IMM(BPF_REG_0, 0),
4744 int prog_fd, link_fd, err;
4746 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4747 insns, ARRAY_SIZE(insns), NULL);
4751 /* use invalid perf_event FD to get EBADF, if link is supported;
4752 * otherwise EINVAL should be returned
4754 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4755 err = -errno; /* close() can clobber errno */
4761 return link_fd < 0 && err == -EBADF;
4764 static int probe_kern_bpf_cookie(void)
4766 struct bpf_insn insns[] = {
4767 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4770 int ret, insn_cnt = ARRAY_SIZE(insns);
4772 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4773 return probe_fd(ret);
4776 static int probe_kern_btf_enum64(void)
4778 static const char strs[] = "\0enum64";
4780 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4783 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4784 strs, sizeof(strs)));
4787 static int probe_kern_syscall_wrapper(void);
4789 enum kern_feature_result {
4795 typedef int (*feature_probe_fn)(void);
4797 static struct kern_feature_desc {
4799 feature_probe_fn probe;
4800 enum kern_feature_result res;
4801 } feature_probes[__FEAT_CNT] = {
4802 [FEAT_PROG_NAME] = {
4803 "BPF program name", probe_kern_prog_name,
4805 [FEAT_GLOBAL_DATA] = {
4806 "global variables", probe_kern_global_data,
4809 "minimal BTF", probe_kern_btf,
4812 "BTF functions", probe_kern_btf_func,
4814 [FEAT_BTF_GLOBAL_FUNC] = {
4815 "BTF global function", probe_kern_btf_func_global,
4817 [FEAT_BTF_DATASEC] = {
4818 "BTF data section and variable", probe_kern_btf_datasec,
4820 [FEAT_ARRAY_MMAP] = {
4821 "ARRAY map mmap()", probe_kern_array_mmap,
4823 [FEAT_EXP_ATTACH_TYPE] = {
4824 "BPF_PROG_LOAD expected_attach_type attribute",
4825 probe_kern_exp_attach_type,
4827 [FEAT_PROBE_READ_KERN] = {
4828 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4830 [FEAT_PROG_BIND_MAP] = {
4831 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4833 [FEAT_MODULE_BTF] = {
4834 "module BTF support", probe_module_btf,
4836 [FEAT_BTF_FLOAT] = {
4837 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4839 [FEAT_PERF_LINK] = {
4840 "BPF perf link support", probe_perf_link,
4842 [FEAT_BTF_DECL_TAG] = {
4843 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4845 [FEAT_BTF_TYPE_TAG] = {
4846 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4848 [FEAT_MEMCG_ACCOUNT] = {
4849 "memcg-based memory accounting", probe_memcg_account,
4851 [FEAT_BPF_COOKIE] = {
4852 "BPF cookie support", probe_kern_bpf_cookie,
4854 [FEAT_BTF_ENUM64] = {
4855 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4857 [FEAT_SYSCALL_WRAPPER] = {
4858 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4862 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4864 struct kern_feature_desc *feat = &feature_probes[feat_id];
4867 if (obj && obj->gen_loader)
4868 /* To generate loader program assume the latest kernel
4869 * to avoid doing extra prog_load, map_create syscalls.
4873 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4874 ret = feat->probe();
4876 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4877 } else if (ret == 0) {
4878 WRITE_ONCE(feat->res, FEAT_MISSING);
4880 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4881 WRITE_ONCE(feat->res, FEAT_MISSING);
4885 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4888 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4890 struct bpf_map_info map_info;
4891 char msg[STRERR_BUFSIZE];
4892 __u32 map_info_len = sizeof(map_info);
4895 memset(&map_info, 0, map_info_len);
4896 err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4897 if (err && errno == EINVAL)
4898 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4900 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4901 libbpf_strerror_r(errno, msg, sizeof(msg)));
4905 return (map_info.type == map->def.type &&
4906 map_info.key_size == map->def.key_size &&
4907 map_info.value_size == map->def.value_size &&
4908 map_info.max_entries == map->def.max_entries &&
4909 map_info.map_flags == map->def.map_flags &&
4910 map_info.map_extra == map->map_extra);
4914 bpf_object__reuse_map(struct bpf_map *map)
4916 char *cp, errmsg[STRERR_BUFSIZE];
4919 pin_fd = bpf_obj_get(map->pin_path);
4922 if (err == -ENOENT) {
4923 pr_debug("found no pinned map to reuse at '%s'\n",
4928 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4929 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4934 if (!map_is_reuse_compat(map, pin_fd)) {
4935 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4941 err = bpf_map__reuse_fd(map, pin_fd);
4947 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4953 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4955 enum libbpf_map_type map_type = map->libbpf_type;
4956 char *cp, errmsg[STRERR_BUFSIZE];
4959 if (obj->gen_loader) {
4960 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4961 map->mmaped, map->def.value_size);
4962 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4963 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4966 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4969 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4970 pr_warn("Error setting initial map(%s) contents: %s\n",
4975 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4976 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4977 err = bpf_map_freeze(map->fd);
4980 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4981 pr_warn("Error freezing map(%s) as read-only: %s\n",
4989 static void bpf_map__destroy(struct bpf_map *map);
4991 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4993 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4994 struct bpf_map_def *def = &map->def;
4995 const char *map_name = NULL;
4998 if (kernel_supports(obj, FEAT_PROG_NAME))
4999 map_name = map->name;
5000 create_attr.map_ifindex = map->map_ifindex;
5001 create_attr.map_flags = def->map_flags;
5002 create_attr.numa_node = map->numa_node;
5003 create_attr.map_extra = map->map_extra;
5005 if (bpf_map__is_struct_ops(map))
5006 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5008 if (obj->btf && btf__fd(obj->btf) >= 0) {
5009 create_attr.btf_fd = btf__fd(obj->btf);
5010 create_attr.btf_key_type_id = map->btf_key_type_id;
5011 create_attr.btf_value_type_id = map->btf_value_type_id;
5014 if (bpf_map_type__is_map_in_map(def->type)) {
5015 if (map->inner_map) {
5016 err = bpf_object__create_map(obj, map->inner_map, true);
5018 pr_warn("map '%s': failed to create inner map: %d\n",
5022 map->inner_map_fd = bpf_map__fd(map->inner_map);
5024 if (map->inner_map_fd >= 0)
5025 create_attr.inner_map_fd = map->inner_map_fd;
5028 switch (def->type) {
5029 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5030 case BPF_MAP_TYPE_CGROUP_ARRAY:
5031 case BPF_MAP_TYPE_STACK_TRACE:
5032 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5033 case BPF_MAP_TYPE_HASH_OF_MAPS:
5034 case BPF_MAP_TYPE_DEVMAP:
5035 case BPF_MAP_TYPE_DEVMAP_HASH:
5036 case BPF_MAP_TYPE_CPUMAP:
5037 case BPF_MAP_TYPE_XSKMAP:
5038 case BPF_MAP_TYPE_SOCKMAP:
5039 case BPF_MAP_TYPE_SOCKHASH:
5040 case BPF_MAP_TYPE_QUEUE:
5041 case BPF_MAP_TYPE_STACK:
5042 create_attr.btf_fd = 0;
5043 create_attr.btf_key_type_id = 0;
5044 create_attr.btf_value_type_id = 0;
5045 map->btf_key_type_id = 0;
5046 map->btf_value_type_id = 0;
5051 if (obj->gen_loader) {
5052 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5053 def->key_size, def->value_size, def->max_entries,
5054 &create_attr, is_inner ? -1 : map - obj->maps);
5055 /* Pretend to have valid FD to pass various fd >= 0 checks.
5056 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5060 map->fd = bpf_map_create(def->type, map_name,
5061 def->key_size, def->value_size,
5062 def->max_entries, &create_attr);
5064 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5065 create_attr.btf_value_type_id)) {
5066 char *cp, errmsg[STRERR_BUFSIZE];
5069 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5070 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5071 map->name, cp, err);
5072 create_attr.btf_fd = 0;
5073 create_attr.btf_key_type_id = 0;
5074 create_attr.btf_value_type_id = 0;
5075 map->btf_key_type_id = 0;
5076 map->btf_value_type_id = 0;
5077 map->fd = bpf_map_create(def->type, map_name,
5078 def->key_size, def->value_size,
5079 def->max_entries, &create_attr);
5082 err = map->fd < 0 ? -errno : 0;
5084 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5085 if (obj->gen_loader)
5086 map->inner_map->fd = -1;
5087 bpf_map__destroy(map->inner_map);
5088 zfree(&map->inner_map);
5094 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5096 const struct bpf_map *targ_map;
5100 for (i = 0; i < map->init_slots_sz; i++) {
5101 if (!map->init_slots[i])
5104 targ_map = map->init_slots[i];
5105 fd = bpf_map__fd(targ_map);
5107 if (obj->gen_loader) {
5108 bpf_gen__populate_outer_map(obj->gen_loader,
5110 targ_map - obj->maps);
5112 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5116 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5117 map->name, i, targ_map->name, fd, err);
5120 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5121 map->name, i, targ_map->name, fd);
5124 zfree(&map->init_slots);
5125 map->init_slots_sz = 0;
5130 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5132 const struct bpf_program *targ_prog;
5136 if (obj->gen_loader)
5139 for (i = 0; i < map->init_slots_sz; i++) {
5140 if (!map->init_slots[i])
5143 targ_prog = map->init_slots[i];
5144 fd = bpf_program__fd(targ_prog);
5146 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5149 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5150 map->name, i, targ_prog->name, fd, err);
5153 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5154 map->name, i, targ_prog->name, fd);
5157 zfree(&map->init_slots);
5158 map->init_slots_sz = 0;
5163 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5165 struct bpf_map *map;
5168 for (i = 0; i < obj->nr_maps; i++) {
5169 map = &obj->maps[i];
5171 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5174 err = init_prog_array_slots(obj, map);
5183 static int map_set_def_max_entries(struct bpf_map *map)
5185 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5188 nr_cpus = libbpf_num_possible_cpus();
5190 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5191 map->name, nr_cpus);
5194 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5195 map->def.max_entries = nr_cpus;
5202 bpf_object__create_maps(struct bpf_object *obj)
5204 struct bpf_map *map;
5205 char *cp, errmsg[STRERR_BUFSIZE];
5210 for (i = 0; i < obj->nr_maps; i++) {
5211 map = &obj->maps[i];
5213 /* To support old kernels, we skip creating global data maps
5214 * (.rodata, .data, .kconfig, etc); later on, during program
5215 * loading, if we detect that at least one of the to-be-loaded
5216 * programs is referencing any global data map, we'll error
5217 * out with program name and relocation index logged.
5218 * This approach allows to accommodate Clang emitting
5219 * unnecessary .rodata.str1.1 sections for string literals,
5220 * but also it allows to have CO-RE applications that use
5221 * global variables in some of BPF programs, but not others.
5222 * If those global variable-using programs are not loaded at
5223 * runtime due to bpf_program__set_autoload(prog, false),
5224 * bpf_object loading will succeed just fine even on old
5227 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5228 map->autocreate = false;
5230 if (!map->autocreate) {
5231 pr_debug("map '%s': skipped auto-creating...\n", map->name);
5235 err = map_set_def_max_entries(map);
5241 if (map->pin_path) {
5242 err = bpf_object__reuse_map(map);
5244 pr_warn("map '%s': error reusing pinned map\n",
5248 if (retried && map->fd < 0) {
5249 pr_warn("map '%s': cannot find pinned map\n",
5257 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5258 map->name, map->fd);
5260 err = bpf_object__create_map(obj, map, false);
5264 pr_debug("map '%s': created successfully, fd=%d\n",
5265 map->name, map->fd);
5267 if (bpf_map__is_internal(map)) {
5268 err = bpf_object__populate_internal_map(obj, map);
5275 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5276 err = init_map_in_map_slots(obj, map);
5284 if (map->pin_path && !map->pinned) {
5285 err = bpf_map__pin(map, NULL);
5288 if (!retried && err == -EEXIST) {
5292 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5293 map->name, map->pin_path, err);
5302 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5303 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5305 for (j = 0; j < i; j++)
5306 zclose(obj->maps[j].fd);
5310 static bool bpf_core_is_flavor_sep(const char *s)
5312 /* check X___Y name pattern, where X and Y are not underscores */
5313 return s[0] != '_' && /* X */
5314 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5315 s[4] != '_'; /* Y */
5318 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5319 * before last triple underscore. Struct name part after last triple
5320 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5322 size_t bpf_core_essential_name_len(const char *name)
5324 size_t n = strlen(name);
5327 for (i = n - 5; i >= 0; i--) {
5328 if (bpf_core_is_flavor_sep(name + i))
5334 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5343 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5344 size_t local_essent_len,
5345 const struct btf *targ_btf,
5346 const char *targ_btf_name,
5348 struct bpf_core_cand_list *cands)
5350 struct bpf_core_cand *new_cands, *cand;
5351 const struct btf_type *t, *local_t;
5352 const char *targ_name, *local_name;
5353 size_t targ_essent_len;
5356 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5357 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5359 n = btf__type_cnt(targ_btf);
5360 for (i = targ_start_id; i < n; i++) {
5361 t = btf__type_by_id(targ_btf, i);
5362 if (!btf_kind_core_compat(t, local_t))
5365 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5366 if (str_is_empty(targ_name))
5369 targ_essent_len = bpf_core_essential_name_len(targ_name);
5370 if (targ_essent_len != local_essent_len)
5373 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5376 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5377 local_cand->id, btf_kind_str(local_t),
5378 local_name, i, btf_kind_str(t), targ_name,
5380 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5381 sizeof(*cands->cands));
5385 cand = &new_cands[cands->len];
5386 cand->btf = targ_btf;
5389 cands->cands = new_cands;
5395 static int load_module_btfs(struct bpf_object *obj)
5397 struct bpf_btf_info info;
5398 struct module_btf *mod_btf;
5404 if (obj->btf_modules_loaded)
5407 if (obj->gen_loader)
5410 /* don't do this again, even if we find no module BTFs */
5411 obj->btf_modules_loaded = true;
5413 /* kernel too old to support module BTFs */
5414 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5418 err = bpf_btf_get_next_id(id, &id);
5419 if (err && errno == ENOENT)
5423 pr_warn("failed to iterate BTF objects: %d\n", err);
5427 fd = bpf_btf_get_fd_by_id(id);
5429 if (errno == ENOENT)
5430 continue; /* expected race: BTF was unloaded */
5432 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5437 memset(&info, 0, sizeof(info));
5438 info.name = ptr_to_u64(name);
5439 info.name_len = sizeof(name);
5441 err = bpf_btf_get_info_by_fd(fd, &info, &len);
5444 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5448 /* ignore non-module BTFs */
5449 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5454 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5455 err = libbpf_get_error(btf);
5457 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5462 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5463 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5467 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5472 mod_btf->name = strdup(name);
5473 if (!mod_btf->name) {
5487 static struct bpf_core_cand_list *
5488 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5490 struct bpf_core_cand local_cand = {};
5491 struct bpf_core_cand_list *cands;
5492 const struct btf *main_btf;
5493 const struct btf_type *local_t;
5494 const char *local_name;
5495 size_t local_essent_len;
5498 local_cand.btf = local_btf;
5499 local_cand.id = local_type_id;
5500 local_t = btf__type_by_id(local_btf, local_type_id);
5502 return ERR_PTR(-EINVAL);
5504 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5505 if (str_is_empty(local_name))
5506 return ERR_PTR(-EINVAL);
5507 local_essent_len = bpf_core_essential_name_len(local_name);
5509 cands = calloc(1, sizeof(*cands));
5511 return ERR_PTR(-ENOMEM);
5513 /* Attempt to find target candidates in vmlinux BTF first */
5514 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5515 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5519 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5523 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5524 if (obj->btf_vmlinux_override)
5527 /* now look through module BTFs, trying to still find candidates */
5528 err = load_module_btfs(obj);
5532 for (i = 0; i < obj->btf_module_cnt; i++) {
5533 err = bpf_core_add_cands(&local_cand, local_essent_len,
5534 obj->btf_modules[i].btf,
5535 obj->btf_modules[i].name,
5536 btf__type_cnt(obj->btf_vmlinux),
5544 bpf_core_free_cands(cands);
5545 return ERR_PTR(err);
5548 /* Check local and target types for compatibility. This check is used for
5549 * type-based CO-RE relocations and follow slightly different rules than
5550 * field-based relocations. This function assumes that root types were already
5551 * checked for name match. Beyond that initial root-level name check, names
5552 * are completely ignored. Compatibility rules are as follows:
5553 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5554 * kind should match for local and target types (i.e., STRUCT is not
5555 * compatible with UNION);
5556 * - for ENUMs, the size is ignored;
5557 * - for INT, size and signedness are ignored;
5558 * - for ARRAY, dimensionality is ignored, element types are checked for
5559 * compatibility recursively;
5560 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5561 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5562 * - FUNC_PROTOs are compatible if they have compatible signature: same
5563 * number of input args and compatible return and argument types.
5564 * These rules are not set in stone and probably will be adjusted as we get
5565 * more experience with using BPF CO-RE relocations.
5567 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5568 const struct btf *targ_btf, __u32 targ_id)
5570 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5573 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5574 const struct btf *targ_btf, __u32 targ_id)
5576 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5579 static size_t bpf_core_hash_fn(const long key, void *ctx)
5584 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5589 static int record_relo_core(struct bpf_program *prog,
5590 const struct bpf_core_relo *core_relo, int insn_idx)
5592 struct reloc_desc *relos, *relo;
5594 relos = libbpf_reallocarray(prog->reloc_desc,
5595 prog->nr_reloc + 1, sizeof(*relos));
5598 relo = &relos[prog->nr_reloc];
5599 relo->type = RELO_CORE;
5600 relo->insn_idx = insn_idx;
5601 relo->core_relo = core_relo;
5602 prog->reloc_desc = relos;
5607 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5609 struct reloc_desc *relo;
5612 for (i = 0; i < prog->nr_reloc; i++) {
5613 relo = &prog->reloc_desc[i];
5614 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5617 return relo->core_relo;
5623 static int bpf_core_resolve_relo(struct bpf_program *prog,
5624 const struct bpf_core_relo *relo,
5626 const struct btf *local_btf,
5627 struct hashmap *cand_cache,
5628 struct bpf_core_relo_res *targ_res)
5630 struct bpf_core_spec specs_scratch[3] = {};
5631 struct bpf_core_cand_list *cands = NULL;
5632 const char *prog_name = prog->name;
5633 const struct btf_type *local_type;
5634 const char *local_name;
5635 __u32 local_id = relo->type_id;
5638 local_type = btf__type_by_id(local_btf, local_id);
5642 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5646 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5647 !hashmap__find(cand_cache, local_id, &cands)) {
5648 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5649 if (IS_ERR(cands)) {
5650 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5651 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5652 local_name, PTR_ERR(cands));
5653 return PTR_ERR(cands);
5655 err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5657 bpf_core_free_cands(cands);
5662 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5667 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5669 const struct btf_ext_info_sec *sec;
5670 struct bpf_core_relo_res targ_res;
5671 const struct bpf_core_relo *rec;
5672 const struct btf_ext_info *seg;
5673 struct hashmap_entry *entry;
5674 struct hashmap *cand_cache = NULL;
5675 struct bpf_program *prog;
5676 struct bpf_insn *insn;
5677 const char *sec_name;
5678 int i, err = 0, insn_idx, sec_idx, sec_num;
5680 if (obj->btf_ext->core_relo_info.len == 0)
5683 if (targ_btf_path) {
5684 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5685 err = libbpf_get_error(obj->btf_vmlinux_override);
5687 pr_warn("failed to parse target BTF: %d\n", err);
5692 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5693 if (IS_ERR(cand_cache)) {
5694 err = PTR_ERR(cand_cache);
5698 seg = &obj->btf_ext->core_relo_info;
5700 for_each_btf_ext_sec(seg, sec) {
5701 sec_idx = seg->sec_idxs[sec_num];
5704 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5705 if (str_is_empty(sec_name)) {
5710 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5712 for_each_btf_ext_rec(seg, sec, i, rec) {
5713 if (rec->insn_off % BPF_INSN_SZ)
5715 insn_idx = rec->insn_off / BPF_INSN_SZ;
5716 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5718 /* When __weak subprog is "overridden" by another instance
5719 * of the subprog from a different object file, linker still
5720 * appends all the .BTF.ext info that used to belong to that
5721 * eliminated subprogram.
5722 * This is similar to what x86-64 linker does for relocations.
5723 * So just ignore such relocations just like we ignore
5724 * subprog instructions when discovering subprograms.
5726 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5727 sec_name, i, insn_idx);
5730 /* no need to apply CO-RE relocation if the program is
5731 * not going to be loaded
5733 if (!prog->autoload)
5736 /* adjust insn_idx from section frame of reference to the local
5737 * program's frame of reference; (sub-)program code is not yet
5738 * relocated, so it's enough to just subtract in-section offset
5740 insn_idx = insn_idx - prog->sec_insn_off;
5741 if (insn_idx >= prog->insns_cnt)
5743 insn = &prog->insns[insn_idx];
5745 err = record_relo_core(prog, rec, insn_idx);
5747 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5748 prog->name, i, err);
5752 if (prog->obj->gen_loader)
5755 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5757 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5758 prog->name, i, err);
5762 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5764 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5765 prog->name, i, insn_idx, err);
5772 /* obj->btf_vmlinux and module BTFs are freed after object load */
5773 btf__free(obj->btf_vmlinux_override);
5774 obj->btf_vmlinux_override = NULL;
5776 if (!IS_ERR_OR_NULL(cand_cache)) {
5777 hashmap__for_each_entry(cand_cache, entry, i) {
5778 bpf_core_free_cands(entry->pvalue);
5780 hashmap__free(cand_cache);
5785 /* base map load ldimm64 special constant, used also for log fixup logic */
5786 #define MAP_LDIMM64_POISON_BASE 2001000000
5787 #define MAP_LDIMM64_POISON_PFX "200100"
5789 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5790 int insn_idx, struct bpf_insn *insn,
5791 int map_idx, const struct bpf_map *map)
5795 pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5796 prog->name, relo_idx, insn_idx, map_idx, map->name);
5798 /* we turn single ldimm64 into two identical invalid calls */
5799 for (i = 0; i < 2; i++) {
5800 insn->code = BPF_JMP | BPF_CALL;
5804 /* if this instruction is reachable (not a dead code),
5805 * verifier will complain with something like:
5806 * invalid func unknown#2001000123
5807 * where lower 123 is map index into obj->maps[] array
5809 insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5815 /* Relocate data references within program code:
5817 * - global variable references;
5818 * - extern references.
5821 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5825 for (i = 0; i < prog->nr_reloc; i++) {
5826 struct reloc_desc *relo = &prog->reloc_desc[i];
5827 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5828 const struct bpf_map *map;
5829 struct extern_desc *ext;
5831 switch (relo->type) {
5833 map = &obj->maps[relo->map_idx];
5834 if (obj->gen_loader) {
5835 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5836 insn[0].imm = relo->map_idx;
5837 } else if (map->autocreate) {
5838 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5839 insn[0].imm = map->fd;
5841 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5842 relo->map_idx, map);
5846 map = &obj->maps[relo->map_idx];
5847 insn[1].imm = insn[0].imm + relo->sym_off;
5848 if (obj->gen_loader) {
5849 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5850 insn[0].imm = relo->map_idx;
5851 } else if (map->autocreate) {
5852 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5853 insn[0].imm = map->fd;
5855 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5856 relo->map_idx, map);
5859 case RELO_EXTERN_LD64:
5860 ext = &obj->externs[relo->sym_off];
5861 if (ext->type == EXT_KCFG) {
5862 if (obj->gen_loader) {
5863 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5864 insn[0].imm = obj->kconfig_map_idx;
5866 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5867 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5869 insn[1].imm = ext->kcfg.data_off;
5870 } else /* EXT_KSYM */ {
5871 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5872 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5873 insn[0].imm = ext->ksym.kernel_btf_id;
5874 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5875 } else { /* typeless ksyms or unresolved typed ksyms */
5876 insn[0].imm = (__u32)ext->ksym.addr;
5877 insn[1].imm = ext->ksym.addr >> 32;
5881 case RELO_EXTERN_CALL:
5882 ext = &obj->externs[relo->sym_off];
5883 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5885 insn[0].imm = ext->ksym.kernel_btf_id;
5886 insn[0].off = ext->ksym.btf_fd_idx;
5887 } else { /* unresolved weak kfunc */
5892 case RELO_SUBPROG_ADDR:
5893 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5894 pr_warn("prog '%s': relo #%d: bad insn\n",
5898 /* handled already */
5901 /* handled already */
5904 /* will be handled by bpf_program_record_relos() */
5907 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5908 prog->name, i, relo->type);
5916 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5917 const struct bpf_program *prog,
5918 const struct btf_ext_info *ext_info,
5919 void **prog_info, __u32 *prog_rec_cnt,
5922 void *copy_start = NULL, *copy_end = NULL;
5923 void *rec, *rec_end, *new_prog_info;
5924 const struct btf_ext_info_sec *sec;
5925 size_t old_sz, new_sz;
5926 int i, sec_num, sec_idx, off_adj;
5929 for_each_btf_ext_sec(ext_info, sec) {
5930 sec_idx = ext_info->sec_idxs[sec_num];
5932 if (prog->sec_idx != sec_idx)
5935 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5936 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5938 if (insn_off < prog->sec_insn_off)
5940 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5945 copy_end = rec + ext_info->rec_size;
5951 /* append func/line info of a given (sub-)program to the main
5952 * program func/line info
5954 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5955 new_sz = old_sz + (copy_end - copy_start);
5956 new_prog_info = realloc(*prog_info, new_sz);
5959 *prog_info = new_prog_info;
5960 *prog_rec_cnt = new_sz / ext_info->rec_size;
5961 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5963 /* Kernel instruction offsets are in units of 8-byte
5964 * instructions, while .BTF.ext instruction offsets generated
5965 * by Clang are in units of bytes. So convert Clang offsets
5966 * into kernel offsets and adjust offset according to program
5967 * relocated position.
5969 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5970 rec = new_prog_info + old_sz;
5971 rec_end = new_prog_info + new_sz;
5972 for (; rec < rec_end; rec += ext_info->rec_size) {
5973 __u32 *insn_off = rec;
5975 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5977 *prog_rec_sz = ext_info->rec_size;
5985 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5986 struct bpf_program *main_prog,
5987 const struct bpf_program *prog)
5991 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5992 * supprot func/line info
5994 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5997 /* only attempt func info relocation if main program's func_info
5998 * relocation was successful
6000 if (main_prog != prog && !main_prog->func_info)
6003 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6004 &main_prog->func_info,
6005 &main_prog->func_info_cnt,
6006 &main_prog->func_info_rec_size);
6008 if (err != -ENOENT) {
6009 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6013 if (main_prog->func_info) {
6015 * Some info has already been found but has problem
6016 * in the last btf_ext reloc. Must have to error out.
6018 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6021 /* Have problem loading the very first info. Ignore the rest. */
6022 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6027 /* don't relocate line info if main program's relocation failed */
6028 if (main_prog != prog && !main_prog->line_info)
6031 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6032 &main_prog->line_info,
6033 &main_prog->line_info_cnt,
6034 &main_prog->line_info_rec_size);
6036 if (err != -ENOENT) {
6037 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6041 if (main_prog->line_info) {
6043 * Some info has already been found but has problem
6044 * in the last btf_ext reloc. Must have to error out.
6046 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6049 /* Have problem loading the very first info. Ignore the rest. */
6050 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6056 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6058 size_t insn_idx = *(const size_t *)key;
6059 const struct reloc_desc *relo = elem;
6061 if (insn_idx == relo->insn_idx)
6063 return insn_idx < relo->insn_idx ? -1 : 1;
6066 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6068 if (!prog->nr_reloc)
6070 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6071 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6074 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6076 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6077 struct reloc_desc *relos;
6080 if (main_prog == subprog)
6082 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6085 if (subprog->nr_reloc)
6086 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6087 sizeof(*relos) * subprog->nr_reloc);
6089 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6090 relos[i].insn_idx += subprog->sub_insn_off;
6091 /* After insn_idx adjustment the 'relos' array is still sorted
6092 * by insn_idx and doesn't break bsearch.
6094 main_prog->reloc_desc = relos;
6095 main_prog->nr_reloc = new_cnt;
6100 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6101 struct bpf_program *prog)
6103 size_t sub_insn_idx, insn_idx, new_cnt;
6104 struct bpf_program *subprog;
6105 struct bpf_insn *insns, *insn;
6106 struct reloc_desc *relo;
6109 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6113 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6114 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6115 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6118 relo = find_prog_insn_relo(prog, insn_idx);
6119 if (relo && relo->type == RELO_EXTERN_CALL)
6120 /* kfunc relocations will be handled later
6121 * in bpf_object__relocate_data()
6124 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6125 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6126 prog->name, insn_idx, relo->type);
6127 return -LIBBPF_ERRNO__RELOC;
6130 /* sub-program instruction index is a combination of
6131 * an offset of a symbol pointed to by relocation and
6132 * call instruction's imm field; for global functions,
6133 * call always has imm = -1, but for static functions
6134 * relocation is against STT_SECTION and insn->imm
6135 * points to a start of a static function
6137 * for subprog addr relocation, the relo->sym_off + insn->imm is
6138 * the byte offset in the corresponding section.
6140 if (relo->type == RELO_CALL)
6141 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6143 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6144 } else if (insn_is_pseudo_func(insn)) {
6146 * RELO_SUBPROG_ADDR relo is always emitted even if both
6147 * functions are in the same section, so it shouldn't reach here.
6149 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6150 prog->name, insn_idx);
6151 return -LIBBPF_ERRNO__RELOC;
6153 /* if subprogram call is to a static function within
6154 * the same ELF section, there won't be any relocation
6155 * emitted, but it also means there is no additional
6156 * offset necessary, insns->imm is relative to
6157 * instruction's original position within the section
6159 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6162 /* we enforce that sub-programs should be in .text section */
6163 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6165 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6167 return -LIBBPF_ERRNO__RELOC;
6170 /* if it's the first call instruction calling into this
6171 * subprogram (meaning this subprog hasn't been processed
6172 * yet) within the context of current main program:
6173 * - append it at the end of main program's instructions blog;
6174 * - process is recursively, while current program is put on hold;
6175 * - if that subprogram calls some other not yet processes
6176 * subprogram, same thing will happen recursively until
6177 * there are no more unprocesses subprograms left to append
6180 if (subprog->sub_insn_off == 0) {
6181 subprog->sub_insn_off = main_prog->insns_cnt;
6183 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6184 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6186 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6189 main_prog->insns = insns;
6190 main_prog->insns_cnt = new_cnt;
6192 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6193 subprog->insns_cnt * sizeof(*insns));
6195 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6196 main_prog->name, subprog->insns_cnt, subprog->name);
6198 /* The subprog insns are now appended. Append its relos too. */
6199 err = append_subprog_relos(main_prog, subprog);
6202 err = bpf_object__reloc_code(obj, main_prog, subprog);
6207 /* main_prog->insns memory could have been re-allocated, so
6208 * calculate pointer again
6210 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6211 /* calculate correct instruction position within current main
6212 * prog; each main prog can have a different set of
6213 * subprograms appended (potentially in different order as
6214 * well), so position of any subprog can be different for
6215 * different main programs
6217 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6219 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6220 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6227 * Relocate sub-program calls.
6229 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6230 * main prog) is processed separately. For each subprog (non-entry functions,
6231 * that can be called from either entry progs or other subprogs) gets their
6232 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6233 * hasn't been yet appended and relocated within current main prog. Once its
6234 * relocated, sub_insn_off will point at the position within current main prog
6235 * where given subprog was appended. This will further be used to relocate all
6236 * the call instructions jumping into this subprog.
6238 * We start with main program and process all call instructions. If the call
6239 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6240 * is zero), subprog instructions are appended at the end of main program's
6241 * instruction array. Then main program is "put on hold" while we recursively
6242 * process newly appended subprogram. If that subprogram calls into another
6243 * subprogram that hasn't been appended, new subprogram is appended again to
6244 * the *main* prog's instructions (subprog's instructions are always left
6245 * untouched, as they need to be in unmodified state for subsequent main progs
6246 * and subprog instructions are always sent only as part of a main prog) and
6247 * the process continues recursively. Once all the subprogs called from a main
6248 * prog or any of its subprogs are appended (and relocated), all their
6249 * positions within finalized instructions array are known, so it's easy to
6250 * rewrite call instructions with correct relative offsets, corresponding to
6251 * desired target subprog.
6253 * Its important to realize that some subprogs might not be called from some
6254 * main prog and any of its called/used subprogs. Those will keep their
6255 * subprog->sub_insn_off as zero at all times and won't be appended to current
6256 * main prog and won't be relocated within the context of current main prog.
6257 * They might still be used from other main progs later.
6259 * Visually this process can be shown as below. Suppose we have two main
6260 * programs mainA and mainB and BPF object contains three subprogs: subA,
6261 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6262 * subC both call subB:
6264 * +--------+ +-------+
6266 * +--+---+ +--+-+-+ +---+--+
6267 * | subA | | subB | | subC |
6268 * +--+---+ +------+ +---+--+
6271 * +---+-------+ +------+----+
6272 * | mainA | | mainB |
6273 * +-----------+ +-----------+
6275 * We'll start relocating mainA, will find subA, append it and start
6276 * processing sub A recursively:
6278 * +-----------+------+
6280 * +-----------+------+
6282 * At this point we notice that subB is used from subA, so we append it and
6283 * relocate (there are no further subcalls from subB):
6285 * +-----------+------+------+
6286 * | mainA | subA | subB |
6287 * +-----------+------+------+
6289 * At this point, we relocate subA calls, then go one level up and finish with
6290 * relocatin mainA calls. mainA is done.
6292 * For mainB process is similar but results in different order. We start with
6293 * mainB and skip subA and subB, as mainB never calls them (at least
6294 * directly), but we see subC is needed, so we append and start processing it:
6296 * +-----------+------+
6298 * +-----------+------+
6299 * Now we see subC needs subB, so we go back to it, append and relocate it:
6301 * +-----------+------+------+
6302 * | mainB | subC | subB |
6303 * +-----------+------+------+
6305 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6308 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6310 struct bpf_program *subprog;
6313 /* mark all subprogs as not relocated (yet) within the context of
6314 * current main program
6316 for (i = 0; i < obj->nr_programs; i++) {
6317 subprog = &obj->programs[i];
6318 if (!prog_is_subprog(obj, subprog))
6321 subprog->sub_insn_off = 0;
6324 err = bpf_object__reloc_code(obj, prog, prog);
6332 bpf_object__free_relocs(struct bpf_object *obj)
6334 struct bpf_program *prog;
6337 /* free up relocation descriptors */
6338 for (i = 0; i < obj->nr_programs; i++) {
6339 prog = &obj->programs[i];
6340 zfree(&prog->reloc_desc);
6345 static int cmp_relocs(const void *_a, const void *_b)
6347 const struct reloc_desc *a = _a;
6348 const struct reloc_desc *b = _b;
6350 if (a->insn_idx != b->insn_idx)
6351 return a->insn_idx < b->insn_idx ? -1 : 1;
6353 /* no two relocations should have the same insn_idx, but ... */
6354 if (a->type != b->type)
6355 return a->type < b->type ? -1 : 1;
6360 static void bpf_object__sort_relos(struct bpf_object *obj)
6364 for (i = 0; i < obj->nr_programs; i++) {
6365 struct bpf_program *p = &obj->programs[i];
6370 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6375 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6377 struct bpf_program *prog;
6382 err = bpf_object__relocate_core(obj, targ_btf_path);
6384 pr_warn("failed to perform CO-RE relocations: %d\n",
6388 bpf_object__sort_relos(obj);
6391 /* Before relocating calls pre-process relocations and mark
6392 * few ld_imm64 instructions that points to subprogs.
6393 * Otherwise bpf_object__reloc_code() later would have to consider
6394 * all ld_imm64 insns as relocation candidates. That would
6395 * reduce relocation speed, since amount of find_prog_insn_relo()
6396 * would increase and most of them will fail to find a relo.
6398 for (i = 0; i < obj->nr_programs; i++) {
6399 prog = &obj->programs[i];
6400 for (j = 0; j < prog->nr_reloc; j++) {
6401 struct reloc_desc *relo = &prog->reloc_desc[j];
6402 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6404 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6405 if (relo->type == RELO_SUBPROG_ADDR)
6406 insn[0].src_reg = BPF_PSEUDO_FUNC;
6410 /* relocate subprogram calls and append used subprograms to main
6411 * programs; each copy of subprogram code needs to be relocated
6412 * differently for each main program, because its code location might
6414 * Append subprog relos to main programs to allow data relos to be
6415 * processed after text is completely relocated.
6417 for (i = 0; i < obj->nr_programs; i++) {
6418 prog = &obj->programs[i];
6419 /* sub-program's sub-calls are relocated within the context of
6420 * its main program only
6422 if (prog_is_subprog(obj, prog))
6424 if (!prog->autoload)
6427 err = bpf_object__relocate_calls(obj, prog);
6429 pr_warn("prog '%s': failed to relocate calls: %d\n",
6434 /* Process data relos for main programs */
6435 for (i = 0; i < obj->nr_programs; i++) {
6436 prog = &obj->programs[i];
6437 if (prog_is_subprog(obj, prog))
6439 if (!prog->autoload)
6441 err = bpf_object__relocate_data(obj, prog);
6443 pr_warn("prog '%s': failed to relocate data references: %d\n",
6452 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6453 Elf64_Shdr *shdr, Elf_Data *data);
6455 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6456 Elf64_Shdr *shdr, Elf_Data *data)
6458 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6459 int i, j, nrels, new_sz;
6460 const struct btf_var_secinfo *vi = NULL;
6461 const struct btf_type *sec, *var, *def;
6462 struct bpf_map *map = NULL, *targ_map = NULL;
6463 struct bpf_program *targ_prog = NULL;
6464 bool is_prog_array, is_map_in_map;
6465 const struct btf_member *member;
6466 const char *name, *mname, *type;
6472 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6474 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6478 nrels = shdr->sh_size / shdr->sh_entsize;
6479 for (i = 0; i < nrels; i++) {
6480 rel = elf_rel_by_idx(data, i);
6482 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6483 return -LIBBPF_ERRNO__FORMAT;
6486 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6488 pr_warn(".maps relo #%d: symbol %zx not found\n",
6489 i, (size_t)ELF64_R_SYM(rel->r_info));
6490 return -LIBBPF_ERRNO__FORMAT;
6492 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6494 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6495 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6496 (size_t)rel->r_offset, sym->st_name, name);
6498 for (j = 0; j < obj->nr_maps; j++) {
6499 map = &obj->maps[j];
6500 if (map->sec_idx != obj->efile.btf_maps_shndx)
6503 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6504 if (vi->offset <= rel->r_offset &&
6505 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6508 if (j == obj->nr_maps) {
6509 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6510 i, name, (size_t)rel->r_offset);
6514 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6515 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6516 type = is_map_in_map ? "map" : "prog";
6517 if (is_map_in_map) {
6518 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6519 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6521 return -LIBBPF_ERRNO__RELOC;
6523 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6524 map->def.key_size != sizeof(int)) {
6525 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6526 i, map->name, sizeof(int));
6529 targ_map = bpf_object__find_map_by_name(obj, name);
6531 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6535 } else if (is_prog_array) {
6536 targ_prog = bpf_object__find_program_by_name(obj, name);
6538 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6542 if (targ_prog->sec_idx != sym->st_shndx ||
6543 targ_prog->sec_insn_off * 8 != sym->st_value ||
6544 prog_is_subprog(obj, targ_prog)) {
6545 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6547 return -LIBBPF_ERRNO__RELOC;
6553 var = btf__type_by_id(obj->btf, vi->type);
6554 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6555 if (btf_vlen(def) == 0)
6557 member = btf_members(def) + btf_vlen(def) - 1;
6558 mname = btf__name_by_offset(obj->btf, member->name_off);
6559 if (strcmp(mname, "values"))
6562 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6563 if (rel->r_offset - vi->offset < moff)
6566 moff = rel->r_offset - vi->offset - moff;
6567 /* here we use BPF pointer size, which is always 64 bit, as we
6568 * are parsing ELF that was built for BPF target
6570 if (moff % bpf_ptr_sz)
6573 if (moff >= map->init_slots_sz) {
6575 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6578 map->init_slots = tmp;
6579 memset(map->init_slots + map->init_slots_sz, 0,
6580 (new_sz - map->init_slots_sz) * host_ptr_sz);
6581 map->init_slots_sz = new_sz;
6583 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6585 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6586 i, map->name, moff, type, name);
6592 static int bpf_object__collect_relos(struct bpf_object *obj)
6596 for (i = 0; i < obj->efile.sec_cnt; i++) {
6597 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6602 if (sec_desc->sec_type != SEC_RELO)
6605 shdr = sec_desc->shdr;
6606 data = sec_desc->data;
6607 idx = shdr->sh_info;
6609 if (shdr->sh_type != SHT_REL) {
6610 pr_warn("internal error at %d\n", __LINE__);
6611 return -LIBBPF_ERRNO__INTERNAL;
6614 if (idx == obj->efile.st_ops_shndx)
6615 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6616 else if (idx == obj->efile.btf_maps_shndx)
6617 err = bpf_object__collect_map_relos(obj, shdr, data);
6619 err = bpf_object__collect_prog_relos(obj, shdr, data);
6624 bpf_object__sort_relos(obj);
6628 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6630 if (BPF_CLASS(insn->code) == BPF_JMP &&
6631 BPF_OP(insn->code) == BPF_CALL &&
6632 BPF_SRC(insn->code) == BPF_K &&
6633 insn->src_reg == 0 &&
6634 insn->dst_reg == 0) {
6635 *func_id = insn->imm;
6641 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6643 struct bpf_insn *insn = prog->insns;
6644 enum bpf_func_id func_id;
6647 if (obj->gen_loader)
6650 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6651 if (!insn_is_helper_call(insn, &func_id))
6654 /* on kernels that don't yet support
6655 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6656 * to bpf_probe_read() which works well for old kernels
6659 case BPF_FUNC_probe_read_kernel:
6660 case BPF_FUNC_probe_read_user:
6661 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6662 insn->imm = BPF_FUNC_probe_read;
6664 case BPF_FUNC_probe_read_kernel_str:
6665 case BPF_FUNC_probe_read_user_str:
6666 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6667 insn->imm = BPF_FUNC_probe_read_str;
6676 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6677 int *btf_obj_fd, int *btf_type_id);
6679 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6680 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6681 struct bpf_prog_load_opts *opts, long cookie)
6683 enum sec_def_flags def = cookie;
6685 /* old kernels might not support specifying expected_attach_type */
6686 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6687 opts->expected_attach_type = 0;
6689 if (def & SEC_SLEEPABLE)
6690 opts->prog_flags |= BPF_F_SLEEPABLE;
6692 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6693 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6695 if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6696 int btf_obj_fd = 0, btf_type_id = 0, err;
6697 const char *attach_name;
6699 attach_name = strchr(prog->sec_name, '/');
6701 /* if BPF program is annotated with just SEC("fentry")
6702 * (or similar) without declaratively specifying
6703 * target, then it is expected that target will be
6704 * specified with bpf_program__set_attach_target() at
6705 * runtime before BPF object load step. If not, then
6706 * there is nothing to load into the kernel as BPF
6707 * verifier won't be able to validate BPF program
6708 * correctness anyways.
6710 pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6714 attach_name++; /* skip over / */
6716 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6720 /* cache resolved BTF FD and BTF type ID in the prog */
6721 prog->attach_btf_obj_fd = btf_obj_fd;
6722 prog->attach_btf_id = btf_type_id;
6724 /* but by now libbpf common logic is not utilizing
6725 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6726 * this callback is called after opts were populated by
6727 * libbpf, so this callback has to update opts explicitly here
6729 opts->attach_btf_obj_fd = btf_obj_fd;
6730 opts->attach_btf_id = btf_type_id;
6735 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6737 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6738 struct bpf_insn *insns, int insns_cnt,
6739 const char *license, __u32 kern_version, int *prog_fd)
6741 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6742 const char *prog_name = NULL;
6743 char *cp, errmsg[STRERR_BUFSIZE];
6744 size_t log_buf_size = 0;
6745 char *log_buf = NULL, *tmp;
6746 int btf_fd, ret, err;
6747 bool own_log_buf = true;
6748 __u32 log_level = prog->log_level;
6750 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6752 * The program type must be set. Most likely we couldn't find a proper
6753 * section definition at load time, and thus we didn't infer the type.
6755 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6756 prog->name, prog->sec_name);
6760 if (!insns || !insns_cnt)
6763 load_attr.expected_attach_type = prog->expected_attach_type;
6764 if (kernel_supports(obj, FEAT_PROG_NAME))
6765 prog_name = prog->name;
6766 load_attr.attach_prog_fd = prog->attach_prog_fd;
6767 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6768 load_attr.attach_btf_id = prog->attach_btf_id;
6769 load_attr.kern_version = kern_version;
6770 load_attr.prog_ifindex = prog->prog_ifindex;
6772 /* specify func_info/line_info only if kernel supports them */
6773 btf_fd = bpf_object__btf_fd(obj);
6774 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6775 load_attr.prog_btf_fd = btf_fd;
6776 load_attr.func_info = prog->func_info;
6777 load_attr.func_info_rec_size = prog->func_info_rec_size;
6778 load_attr.func_info_cnt = prog->func_info_cnt;
6779 load_attr.line_info = prog->line_info;
6780 load_attr.line_info_rec_size = prog->line_info_rec_size;
6781 load_attr.line_info_cnt = prog->line_info_cnt;
6783 load_attr.log_level = log_level;
6784 load_attr.prog_flags = prog->prog_flags;
6785 load_attr.fd_array = obj->fd_array;
6787 /* adjust load_attr if sec_def provides custom preload callback */
6788 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6789 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6791 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6795 insns = prog->insns;
6796 insns_cnt = prog->insns_cnt;
6799 if (obj->gen_loader) {
6800 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6801 license, insns, insns_cnt, &load_attr,
6802 prog - obj->programs);
6808 /* if log_level is zero, we don't request logs initially even if
6809 * custom log_buf is specified; if the program load fails, then we'll
6810 * bump log_level to 1 and use either custom log_buf or we'll allocate
6811 * our own and retry the load to get details on what failed
6814 if (prog->log_buf) {
6815 log_buf = prog->log_buf;
6816 log_buf_size = prog->log_size;
6817 own_log_buf = false;
6818 } else if (obj->log_buf) {
6819 log_buf = obj->log_buf;
6820 log_buf_size = obj->log_size;
6821 own_log_buf = false;
6823 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6824 tmp = realloc(log_buf, log_buf_size);
6835 load_attr.log_buf = log_buf;
6836 load_attr.log_size = log_buf_size;
6837 load_attr.log_level = log_level;
6839 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6841 if (log_level && own_log_buf) {
6842 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6843 prog->name, log_buf);
6846 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6847 struct bpf_map *map;
6850 for (i = 0; i < obj->nr_maps; i++) {
6851 map = &prog->obj->maps[i];
6852 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6855 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6856 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6857 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6858 prog->name, map->real_name, cp);
6859 /* Don't fail hard if can't bind rodata. */
6869 if (log_level == 0) {
6873 /* On ENOSPC, increase log buffer size and retry, unless custom
6874 * log_buf is specified.
6875 * Be careful to not overflow u32, though. Kernel's log buf size limit
6876 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6877 * multiply by 2 unless we are sure we'll fit within 32 bits.
6878 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6880 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6885 /* post-process verifier log to improve error descriptions */
6886 fixup_verifier_log(prog, log_buf, log_buf_size);
6888 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6889 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6892 if (own_log_buf && log_buf && log_buf[0] != '\0') {
6893 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6894 prog->name, log_buf);
6903 static char *find_prev_line(char *buf, char *cur)
6907 if (cur == buf) /* end of a log buf */
6911 while (p - 1 >= buf && *(p - 1) != '\n')
6917 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6918 char *orig, size_t orig_sz, const char *patch)
6920 /* size of the remaining log content to the right from the to-be-replaced part */
6921 size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6922 size_t patch_sz = strlen(patch);
6924 if (patch_sz != orig_sz) {
6925 /* If patch line(s) are longer than original piece of verifier log,
6926 * shift log contents by (patch_sz - orig_sz) bytes to the right
6927 * starting from after to-be-replaced part of the log.
6929 * If patch line(s) are shorter than original piece of verifier log,
6930 * shift log contents by (orig_sz - patch_sz) bytes to the left
6931 * starting from after to-be-replaced part of the log
6933 * We need to be careful about not overflowing available
6934 * buf_sz capacity. If that's the case, we'll truncate the end
6935 * of the original log, as necessary.
6937 if (patch_sz > orig_sz) {
6938 if (orig + patch_sz >= buf + buf_sz) {
6939 /* patch is big enough to cover remaining space completely */
6940 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6942 } else if (patch_sz - orig_sz > buf_sz - log_sz) {
6943 /* patch causes part of remaining log to be truncated */
6944 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6947 /* shift remaining log to the right by calculated amount */
6948 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6951 memcpy(orig, patch, patch_sz);
6954 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6955 char *buf, size_t buf_sz, size_t log_sz,
6956 char *line1, char *line2, char *line3)
6958 /* Expected log for failed and not properly guarded CO-RE relocation:
6959 * line1 -> 123: (85) call unknown#195896080
6960 * line2 -> invalid func unknown#195896080
6961 * line3 -> <anything else or end of buffer>
6963 * "123" is the index of the instruction that was poisoned. We extract
6964 * instruction index to find corresponding CO-RE relocation and
6965 * replace this part of the log with more relevant information about
6966 * failed CO-RE relocation.
6968 const struct bpf_core_relo *relo;
6969 struct bpf_core_spec spec;
6970 char patch[512], spec_buf[256];
6971 int insn_idx, err, spec_len;
6973 if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
6976 relo = find_relo_core(prog, insn_idx);
6980 err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
6984 spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
6985 snprintf(patch, sizeof(patch),
6986 "%d: <invalid CO-RE relocation>\n"
6987 "failed to resolve CO-RE relocation %s%s\n",
6988 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
6990 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
6993 static void fixup_log_missing_map_load(struct bpf_program *prog,
6994 char *buf, size_t buf_sz, size_t log_sz,
6995 char *line1, char *line2, char *line3)
6997 /* Expected log for failed and not properly guarded CO-RE relocation:
6998 * line1 -> 123: (85) call unknown#2001000345
6999 * line2 -> invalid func unknown#2001000345
7000 * line3 -> <anything else or end of buffer>
7002 * "123" is the index of the instruction that was poisoned.
7003 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7005 struct bpf_object *obj = prog->obj;
7006 const struct bpf_map *map;
7007 int insn_idx, map_idx;
7010 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7013 map_idx -= MAP_LDIMM64_POISON_BASE;
7014 if (map_idx < 0 || map_idx >= obj->nr_maps)
7016 map = &obj->maps[map_idx];
7018 snprintf(patch, sizeof(patch),
7019 "%d: <invalid BPF map reference>\n"
7020 "BPF map '%s' is referenced but wasn't created\n",
7021 insn_idx, map->name);
7023 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7026 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7028 /* look for familiar error patterns in last N lines of the log */
7029 const size_t max_last_line_cnt = 10;
7030 char *prev_line, *cur_line, *next_line;
7037 log_sz = strlen(buf) + 1;
7038 next_line = buf + log_sz - 1;
7040 for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7041 cur_line = find_prev_line(buf, next_line);
7045 /* failed CO-RE relocation case */
7046 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7047 prev_line = find_prev_line(buf, cur_line);
7051 fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7052 prev_line, cur_line, next_line);
7054 } else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7055 prev_line = find_prev_line(buf, cur_line);
7059 fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7060 prev_line, cur_line, next_line);
7066 static int bpf_program_record_relos(struct bpf_program *prog)
7068 struct bpf_object *obj = prog->obj;
7071 for (i = 0; i < prog->nr_reloc; i++) {
7072 struct reloc_desc *relo = &prog->reloc_desc[i];
7073 struct extern_desc *ext = &obj->externs[relo->sym_off];
7076 switch (relo->type) {
7077 case RELO_EXTERN_LD64:
7078 if (ext->type != EXT_KSYM)
7080 kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7081 BTF_KIND_VAR : BTF_KIND_FUNC;
7082 bpf_gen__record_extern(obj->gen_loader, ext->name,
7083 ext->is_weak, !ext->ksym.type_id,
7084 true, kind, relo->insn_idx);
7086 case RELO_EXTERN_CALL:
7087 bpf_gen__record_extern(obj->gen_loader, ext->name,
7088 ext->is_weak, false, false, BTF_KIND_FUNC,
7092 struct bpf_core_relo cr = {
7093 .insn_off = relo->insn_idx * 8,
7094 .type_id = relo->core_relo->type_id,
7095 .access_str_off = relo->core_relo->access_str_off,
7096 .kind = relo->core_relo->kind,
7099 bpf_gen__record_relo_core(obj->gen_loader, &cr);
7110 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7112 struct bpf_program *prog;
7116 for (i = 0; i < obj->nr_programs; i++) {
7117 prog = &obj->programs[i];
7118 err = bpf_object__sanitize_prog(obj, prog);
7123 for (i = 0; i < obj->nr_programs; i++) {
7124 prog = &obj->programs[i];
7125 if (prog_is_subprog(obj, prog))
7127 if (!prog->autoload) {
7128 pr_debug("prog '%s': skipped loading\n", prog->name);
7131 prog->log_level |= log_level;
7133 if (obj->gen_loader)
7134 bpf_program_record_relos(prog);
7136 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7137 obj->license, obj->kern_version, &prog->fd);
7139 pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7144 bpf_object__free_relocs(obj);
7148 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7150 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7152 struct bpf_program *prog;
7155 bpf_object__for_each_program(prog, obj) {
7156 prog->sec_def = find_sec_def(prog->sec_name);
7157 if (!prog->sec_def) {
7158 /* couldn't guess, but user might manually specify */
7159 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7160 prog->name, prog->sec_name);
7164 prog->type = prog->sec_def->prog_type;
7165 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7167 /* sec_def can have custom callback which should be called
7168 * after bpf_program is initialized to adjust its properties
7170 if (prog->sec_def->prog_setup_fn) {
7171 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7173 pr_warn("prog '%s': failed to initialize: %d\n",
7183 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7184 const struct bpf_object_open_opts *opts)
7186 const char *obj_name, *kconfig, *btf_tmp_path;
7187 struct bpf_object *obj;
7194 if (elf_version(EV_CURRENT) == EV_NONE) {
7195 pr_warn("failed to init libelf for %s\n",
7196 path ? : "(mem buf)");
7197 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7200 if (!OPTS_VALID(opts, bpf_object_open_opts))
7201 return ERR_PTR(-EINVAL);
7203 obj_name = OPTS_GET(opts, object_name, NULL);
7206 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7207 (unsigned long)obj_buf,
7208 (unsigned long)obj_buf_sz);
7209 obj_name = tmp_name;
7212 pr_debug("loading object '%s' from buffer\n", obj_name);
7215 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7216 log_size = OPTS_GET(opts, kernel_log_size, 0);
7217 log_level = OPTS_GET(opts, kernel_log_level, 0);
7218 if (log_size > UINT_MAX)
7219 return ERR_PTR(-EINVAL);
7220 if (log_size && !log_buf)
7221 return ERR_PTR(-EINVAL);
7223 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7227 obj->log_buf = log_buf;
7228 obj->log_size = log_size;
7229 obj->log_level = log_level;
7231 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7233 if (strlen(btf_tmp_path) >= PATH_MAX) {
7234 err = -ENAMETOOLONG;
7237 obj->btf_custom_path = strdup(btf_tmp_path);
7238 if (!obj->btf_custom_path) {
7244 kconfig = OPTS_GET(opts, kconfig, NULL);
7246 obj->kconfig = strdup(kconfig);
7247 if (!obj->kconfig) {
7253 err = bpf_object__elf_init(obj);
7254 err = err ? : bpf_object__check_endianness(obj);
7255 err = err ? : bpf_object__elf_collect(obj);
7256 err = err ? : bpf_object__collect_externs(obj);
7257 err = err ? : bpf_object_fixup_btf(obj);
7258 err = err ? : bpf_object__init_maps(obj, opts);
7259 err = err ? : bpf_object_init_progs(obj, opts);
7260 err = err ? : bpf_object__collect_relos(obj);
7264 bpf_object__elf_finish(obj);
7268 bpf_object__close(obj);
7269 return ERR_PTR(err);
7273 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7276 return libbpf_err_ptr(-EINVAL);
7278 pr_debug("loading %s\n", path);
7280 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7283 struct bpf_object *bpf_object__open(const char *path)
7285 return bpf_object__open_file(path, NULL);
7289 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7290 const struct bpf_object_open_opts *opts)
7292 if (!obj_buf || obj_buf_sz == 0)
7293 return libbpf_err_ptr(-EINVAL);
7295 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7298 static int bpf_object_unload(struct bpf_object *obj)
7303 return libbpf_err(-EINVAL);
7305 for (i = 0; i < obj->nr_maps; i++) {
7306 zclose(obj->maps[i].fd);
7307 if (obj->maps[i].st_ops)
7308 zfree(&obj->maps[i].st_ops->kern_vdata);
7311 for (i = 0; i < obj->nr_programs; i++)
7312 bpf_program__unload(&obj->programs[i]);
7317 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7321 bpf_object__for_each_map(m, obj) {
7322 if (!bpf_map__is_internal(m))
7324 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7325 m->def.map_flags &= ~BPF_F_MMAPABLE;
7331 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7333 char sym_type, sym_name[500];
7334 unsigned long long sym_addr;
7338 f = fopen("/proc/kallsyms", "r");
7341 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7346 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7347 &sym_addr, &sym_type, sym_name);
7348 if (ret == EOF && feof(f))
7351 pr_warn("failed to read kallsyms entry: %d\n", ret);
7356 err = cb(sym_addr, sym_type, sym_name, ctx);
7365 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7366 const char *sym_name, void *ctx)
7368 struct bpf_object *obj = ctx;
7369 const struct btf_type *t;
7370 struct extern_desc *ext;
7372 ext = find_extern_by_name(obj, sym_name);
7373 if (!ext || ext->type != EXT_KSYM)
7376 t = btf__type_by_id(obj->btf, ext->btf_id);
7380 if (ext->is_set && ext->ksym.addr != sym_addr) {
7381 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7382 sym_name, ext->ksym.addr, sym_addr);
7387 ext->ksym.addr = sym_addr;
7388 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7393 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7395 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7398 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7399 __u16 kind, struct btf **res_btf,
7400 struct module_btf **res_mod_btf)
7402 struct module_btf *mod_btf;
7406 btf = obj->btf_vmlinux;
7408 id = btf__find_by_name_kind(btf, ksym_name, kind);
7410 if (id == -ENOENT) {
7411 err = load_module_btfs(obj);
7415 for (i = 0; i < obj->btf_module_cnt; i++) {
7416 /* we assume module_btf's BTF FD is always >0 */
7417 mod_btf = &obj->btf_modules[i];
7419 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7428 *res_mod_btf = mod_btf;
7432 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7433 struct extern_desc *ext)
7435 const struct btf_type *targ_var, *targ_type;
7436 __u32 targ_type_id, local_type_id;
7437 struct module_btf *mod_btf = NULL;
7438 const char *targ_var_name;
7439 struct btf *btf = NULL;
7442 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7444 if (id == -ESRCH && ext->is_weak)
7446 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7451 /* find local type_id */
7452 local_type_id = ext->ksym.type_id;
7454 /* find target type_id */
7455 targ_var = btf__type_by_id(btf, id);
7456 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7457 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7459 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7462 const struct btf_type *local_type;
7463 const char *targ_name, *local_name;
7465 local_type = btf__type_by_id(obj->btf, local_type_id);
7466 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7467 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7469 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7470 ext->name, local_type_id,
7471 btf_kind_str(local_type), local_name, targ_type_id,
7472 btf_kind_str(targ_type), targ_name);
7477 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7478 ext->ksym.kernel_btf_id = id;
7479 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7480 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7485 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7486 struct extern_desc *ext)
7488 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7489 struct module_btf *mod_btf = NULL;
7490 const struct btf_type *kern_func;
7491 struct btf *kern_btf = NULL;
7494 local_func_proto_id = ext->ksym.type_id;
7496 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7498 if (kfunc_id == -ESRCH && ext->is_weak)
7500 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7505 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7506 kfunc_proto_id = kern_func->type;
7508 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7509 kern_btf, kfunc_proto_id);
7511 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7512 ext->name, local_func_proto_id, kfunc_proto_id);
7516 /* set index for module BTF fd in fd_array, if unset */
7517 if (mod_btf && !mod_btf->fd_array_idx) {
7518 /* insn->off is s16 */
7519 if (obj->fd_array_cnt == INT16_MAX) {
7520 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7521 ext->name, mod_btf->fd_array_idx);
7524 /* Cannot use index 0 for module BTF fd */
7525 if (!obj->fd_array_cnt)
7526 obj->fd_array_cnt = 1;
7528 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7529 obj->fd_array_cnt + 1);
7532 mod_btf->fd_array_idx = obj->fd_array_cnt;
7533 /* we assume module BTF FD is always >0 */
7534 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7538 ext->ksym.kernel_btf_id = kfunc_id;
7539 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7540 /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7541 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7542 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7543 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7545 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7546 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7547 ext->name, kfunc_id);
7552 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7554 const struct btf_type *t;
7555 struct extern_desc *ext;
7558 for (i = 0; i < obj->nr_extern; i++) {
7559 ext = &obj->externs[i];
7560 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7563 if (obj->gen_loader) {
7565 ext->ksym.kernel_btf_obj_fd = 0;
7566 ext->ksym.kernel_btf_id = 0;
7569 t = btf__type_by_id(obj->btf, ext->btf_id);
7571 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7573 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7580 static int bpf_object__resolve_externs(struct bpf_object *obj,
7581 const char *extra_kconfig)
7583 bool need_config = false, need_kallsyms = false;
7584 bool need_vmlinux_btf = false;
7585 struct extern_desc *ext;
7586 void *kcfg_data = NULL;
7589 if (obj->nr_extern == 0)
7592 if (obj->kconfig_map_idx >= 0)
7593 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7595 for (i = 0; i < obj->nr_extern; i++) {
7596 ext = &obj->externs[i];
7598 if (ext->type == EXT_KSYM) {
7599 if (ext->ksym.type_id)
7600 need_vmlinux_btf = true;
7602 need_kallsyms = true;
7604 } else if (ext->type == EXT_KCFG) {
7605 void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7608 /* Kconfig externs need actual /proc/config.gz */
7609 if (str_has_pfx(ext->name, "CONFIG_")) {
7614 /* Virtual kcfg externs are customly handled by libbpf */
7615 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7616 value = get_kernel_version();
7618 pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7621 } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7622 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7623 } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7624 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7625 } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7626 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7627 * __kconfig externs, where LINUX_ ones are virtual and filled out
7628 * customly by libbpf (their values don't come from Kconfig).
7629 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7630 * __weak, it defaults to zero value, just like for CONFIG_xxx
7633 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7637 err = set_kcfg_value_num(ext, ext_ptr, value);
7640 pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7641 ext->name, (long long)value);
7643 pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7647 if (need_config && extra_kconfig) {
7648 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7651 need_config = false;
7652 for (i = 0; i < obj->nr_extern; i++) {
7653 ext = &obj->externs[i];
7654 if (ext->type == EXT_KCFG && !ext->is_set) {
7661 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7665 if (need_kallsyms) {
7666 err = bpf_object__read_kallsyms_file(obj);
7670 if (need_vmlinux_btf) {
7671 err = bpf_object__resolve_ksyms_btf_id(obj);
7675 for (i = 0; i < obj->nr_extern; i++) {
7676 ext = &obj->externs[i];
7678 if (!ext->is_set && !ext->is_weak) {
7679 pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7681 } else if (!ext->is_set) {
7682 pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7690 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7692 struct bpf_struct_ops *st_ops;
7695 st_ops = map->st_ops;
7696 for (i = 0; i < btf_vlen(st_ops->type); i++) {
7697 struct bpf_program *prog = st_ops->progs[i];
7704 prog_fd = bpf_program__fd(prog);
7705 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7706 *(unsigned long *)kern_data = prog_fd;
7710 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7714 for (i = 0; i < obj->nr_maps; i++)
7715 if (bpf_map__is_struct_ops(&obj->maps[i]))
7716 bpf_map_prepare_vdata(&obj->maps[i]);
7721 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7726 return libbpf_err(-EINVAL);
7729 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7730 return libbpf_err(-EINVAL);
7733 if (obj->gen_loader)
7734 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7736 err = bpf_object__probe_loading(obj);
7737 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7738 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7739 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7740 err = err ? : bpf_object__sanitize_maps(obj);
7741 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7742 err = err ? : bpf_object__create_maps(obj);
7743 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7744 err = err ? : bpf_object__load_progs(obj, extra_log_level);
7745 err = err ? : bpf_object_init_prog_arrays(obj);
7746 err = err ? : bpf_object_prepare_struct_ops(obj);
7748 if (obj->gen_loader) {
7751 btf__set_fd(obj->btf, -1);
7752 for (i = 0; i < obj->nr_maps; i++)
7753 obj->maps[i].fd = -1;
7755 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7758 /* clean up fd_array */
7759 zfree(&obj->fd_array);
7761 /* clean up module BTFs */
7762 for (i = 0; i < obj->btf_module_cnt; i++) {
7763 close(obj->btf_modules[i].fd);
7764 btf__free(obj->btf_modules[i].btf);
7765 free(obj->btf_modules[i].name);
7767 free(obj->btf_modules);
7769 /* clean up vmlinux BTF */
7770 btf__free(obj->btf_vmlinux);
7771 obj->btf_vmlinux = NULL;
7773 obj->loaded = true; /* doesn't matter if successfully or not */
7780 /* unpin any maps that were auto-pinned during load */
7781 for (i = 0; i < obj->nr_maps; i++)
7782 if (obj->maps[i].pinned && !obj->maps[i].reused)
7783 bpf_map__unpin(&obj->maps[i], NULL);
7785 bpf_object_unload(obj);
7786 pr_warn("failed to load object '%s'\n", obj->path);
7787 return libbpf_err(err);
7790 int bpf_object__load(struct bpf_object *obj)
7792 return bpf_object_load(obj, 0, NULL);
7795 static int make_parent_dir(const char *path)
7797 char *cp, errmsg[STRERR_BUFSIZE];
7801 dname = strdup(path);
7805 dir = dirname(dname);
7806 if (mkdir(dir, 0700) && errno != EEXIST)
7811 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7812 pr_warn("failed to mkdir %s: %s\n", path, cp);
7817 static int check_path(const char *path)
7819 char *cp, errmsg[STRERR_BUFSIZE];
7820 struct statfs st_fs;
7827 dname = strdup(path);
7831 dir = dirname(dname);
7832 if (statfs(dir, &st_fs)) {
7833 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7834 pr_warn("failed to statfs %s: %s\n", dir, cp);
7839 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7840 pr_warn("specified path %s is not on BPF FS\n", path);
7847 int bpf_program__pin(struct bpf_program *prog, const char *path)
7849 char *cp, errmsg[STRERR_BUFSIZE];
7853 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7854 return libbpf_err(-EINVAL);
7857 err = make_parent_dir(path);
7859 return libbpf_err(err);
7861 err = check_path(path);
7863 return libbpf_err(err);
7865 if (bpf_obj_pin(prog->fd, path)) {
7867 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7868 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7869 return libbpf_err(err);
7872 pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7876 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7881 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7882 return libbpf_err(-EINVAL);
7885 err = check_path(path);
7887 return libbpf_err(err);
7891 return libbpf_err(-errno);
7893 pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7897 int bpf_map__pin(struct bpf_map *map, const char *path)
7899 char *cp, errmsg[STRERR_BUFSIZE];
7903 pr_warn("invalid map pointer\n");
7904 return libbpf_err(-EINVAL);
7907 if (map->pin_path) {
7908 if (path && strcmp(path, map->pin_path)) {
7909 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7910 bpf_map__name(map), map->pin_path, path);
7911 return libbpf_err(-EINVAL);
7912 } else if (map->pinned) {
7913 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7914 bpf_map__name(map), map->pin_path);
7919 pr_warn("missing a path to pin map '%s' at\n",
7920 bpf_map__name(map));
7921 return libbpf_err(-EINVAL);
7922 } else if (map->pinned) {
7923 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7924 return libbpf_err(-EEXIST);
7927 map->pin_path = strdup(path);
7928 if (!map->pin_path) {
7934 err = make_parent_dir(map->pin_path);
7936 return libbpf_err(err);
7938 err = check_path(map->pin_path);
7940 return libbpf_err(err);
7942 if (bpf_obj_pin(map->fd, map->pin_path)) {
7948 pr_debug("pinned map '%s'\n", map->pin_path);
7953 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7954 pr_warn("failed to pin map: %s\n", cp);
7955 return libbpf_err(err);
7958 int bpf_map__unpin(struct bpf_map *map, const char *path)
7963 pr_warn("invalid map pointer\n");
7964 return libbpf_err(-EINVAL);
7967 if (map->pin_path) {
7968 if (path && strcmp(path, map->pin_path)) {
7969 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7970 bpf_map__name(map), map->pin_path, path);
7971 return libbpf_err(-EINVAL);
7973 path = map->pin_path;
7975 pr_warn("no path to unpin map '%s' from\n",
7976 bpf_map__name(map));
7977 return libbpf_err(-EINVAL);
7980 err = check_path(path);
7982 return libbpf_err(err);
7986 return libbpf_err(-errno);
7988 map->pinned = false;
7989 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7994 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8001 return libbpf_err(-errno);
8004 free(map->pin_path);
8005 map->pin_path = new;
8009 __alias(bpf_map__pin_path)
8010 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8012 const char *bpf_map__pin_path(const struct bpf_map *map)
8014 return map->pin_path;
8017 bool bpf_map__is_pinned(const struct bpf_map *map)
8022 static void sanitize_pin_path(char *s)
8024 /* bpffs disallows periods in path names */
8032 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8034 struct bpf_map *map;
8038 return libbpf_err(-ENOENT);
8041 pr_warn("object not yet loaded; load it first\n");
8042 return libbpf_err(-ENOENT);
8045 bpf_object__for_each_map(map, obj) {
8046 char *pin_path = NULL;
8049 if (!map->autocreate)
8053 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8055 goto err_unpin_maps;
8056 sanitize_pin_path(buf);
8058 } else if (!map->pin_path) {
8062 err = bpf_map__pin(map, pin_path);
8064 goto err_unpin_maps;
8070 while ((map = bpf_object__prev_map(obj, map))) {
8074 bpf_map__unpin(map, NULL);
8077 return libbpf_err(err);
8080 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8082 struct bpf_map *map;
8086 return libbpf_err(-ENOENT);
8088 bpf_object__for_each_map(map, obj) {
8089 char *pin_path = NULL;
8093 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8095 return libbpf_err(err);
8096 sanitize_pin_path(buf);
8098 } else if (!map->pin_path) {
8102 err = bpf_map__unpin(map, pin_path);
8104 return libbpf_err(err);
8110 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8112 struct bpf_program *prog;
8117 return libbpf_err(-ENOENT);
8120 pr_warn("object not yet loaded; load it first\n");
8121 return libbpf_err(-ENOENT);
8124 bpf_object__for_each_program(prog, obj) {
8125 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8127 goto err_unpin_programs;
8129 err = bpf_program__pin(prog, buf);
8131 goto err_unpin_programs;
8137 while ((prog = bpf_object__prev_program(obj, prog))) {
8138 if (pathname_concat(buf, sizeof(buf), path, prog->name))
8141 bpf_program__unpin(prog, buf);
8144 return libbpf_err(err);
8147 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8149 struct bpf_program *prog;
8153 return libbpf_err(-ENOENT);
8155 bpf_object__for_each_program(prog, obj) {
8158 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8160 return libbpf_err(err);
8162 err = bpf_program__unpin(prog, buf);
8164 return libbpf_err(err);
8170 int bpf_object__pin(struct bpf_object *obj, const char *path)
8174 err = bpf_object__pin_maps(obj, path);
8176 return libbpf_err(err);
8178 err = bpf_object__pin_programs(obj, path);
8180 bpf_object__unpin_maps(obj, path);
8181 return libbpf_err(err);
8187 static void bpf_map__destroy(struct bpf_map *map)
8189 if (map->inner_map) {
8190 bpf_map__destroy(map->inner_map);
8191 zfree(&map->inner_map);
8194 zfree(&map->init_slots);
8195 map->init_slots_sz = 0;
8198 munmap(map->mmaped, bpf_map_mmap_sz(map));
8203 zfree(&map->st_ops->data);
8204 zfree(&map->st_ops->progs);
8205 zfree(&map->st_ops->kern_func_off);
8206 zfree(&map->st_ops);
8210 zfree(&map->real_name);
8211 zfree(&map->pin_path);
8217 void bpf_object__close(struct bpf_object *obj)
8221 if (IS_ERR_OR_NULL(obj))
8224 usdt_manager_free(obj->usdt_man);
8225 obj->usdt_man = NULL;
8227 bpf_gen__free(obj->gen_loader);
8228 bpf_object__elf_finish(obj);
8229 bpf_object_unload(obj);
8230 btf__free(obj->btf);
8231 btf_ext__free(obj->btf_ext);
8233 for (i = 0; i < obj->nr_maps; i++)
8234 bpf_map__destroy(&obj->maps[i]);
8236 zfree(&obj->btf_custom_path);
8237 zfree(&obj->kconfig);
8238 zfree(&obj->externs);
8244 if (obj->programs && obj->nr_programs) {
8245 for (i = 0; i < obj->nr_programs; i++)
8246 bpf_program__exit(&obj->programs[i]);
8248 zfree(&obj->programs);
8253 const char *bpf_object__name(const struct bpf_object *obj)
8255 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8258 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8260 return obj ? obj->kern_version : 0;
8263 struct btf *bpf_object__btf(const struct bpf_object *obj)
8265 return obj ? obj->btf : NULL;
8268 int bpf_object__btf_fd(const struct bpf_object *obj)
8270 return obj->btf ? btf__fd(obj->btf) : -1;
8273 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8276 return libbpf_err(-EINVAL);
8278 obj->kern_version = kern_version;
8283 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8285 struct bpf_gen *gen;
8289 if (!OPTS_VALID(opts, gen_loader_opts))
8291 gen = calloc(sizeof(*gen), 1);
8295 obj->gen_loader = gen;
8299 static struct bpf_program *
8300 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8303 size_t nr_programs = obj->nr_programs;
8310 /* Iter from the beginning */
8311 return forward ? &obj->programs[0] :
8312 &obj->programs[nr_programs - 1];
8314 if (p->obj != obj) {
8315 pr_warn("error: program handler doesn't match object\n");
8316 return errno = EINVAL, NULL;
8319 idx = (p - obj->programs) + (forward ? 1 : -1);
8320 if (idx >= obj->nr_programs || idx < 0)
8322 return &obj->programs[idx];
8325 struct bpf_program *
8326 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8328 struct bpf_program *prog = prev;
8331 prog = __bpf_program__iter(prog, obj, true);
8332 } while (prog && prog_is_subprog(obj, prog));
8337 struct bpf_program *
8338 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8340 struct bpf_program *prog = next;
8343 prog = __bpf_program__iter(prog, obj, false);
8344 } while (prog && prog_is_subprog(obj, prog));
8349 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8351 prog->prog_ifindex = ifindex;
8354 const char *bpf_program__name(const struct bpf_program *prog)
8359 const char *bpf_program__section_name(const struct bpf_program *prog)
8361 return prog->sec_name;
8364 bool bpf_program__autoload(const struct bpf_program *prog)
8366 return prog->autoload;
8369 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8371 if (prog->obj->loaded)
8372 return libbpf_err(-EINVAL);
8374 prog->autoload = autoload;
8378 bool bpf_program__autoattach(const struct bpf_program *prog)
8380 return prog->autoattach;
8383 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8385 prog->autoattach = autoattach;
8388 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8393 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8395 return prog->insns_cnt;
8398 int bpf_program__set_insns(struct bpf_program *prog,
8399 struct bpf_insn *new_insns, size_t new_insn_cnt)
8401 struct bpf_insn *insns;
8403 if (prog->obj->loaded)
8406 insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8408 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8411 memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8413 prog->insns = insns;
8414 prog->insns_cnt = new_insn_cnt;
8418 int bpf_program__fd(const struct bpf_program *prog)
8421 return libbpf_err(-EINVAL);
8424 return libbpf_err(-ENOENT);
8429 __alias(bpf_program__type)
8430 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8432 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8437 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8439 if (prog->obj->loaded)
8440 return libbpf_err(-EBUSY);
8446 __alias(bpf_program__expected_attach_type)
8447 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8449 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8451 return prog->expected_attach_type;
8454 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8455 enum bpf_attach_type type)
8457 if (prog->obj->loaded)
8458 return libbpf_err(-EBUSY);
8460 prog->expected_attach_type = type;
8464 __u32 bpf_program__flags(const struct bpf_program *prog)
8466 return prog->prog_flags;
8469 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8471 if (prog->obj->loaded)
8472 return libbpf_err(-EBUSY);
8474 prog->prog_flags = flags;
8478 __u32 bpf_program__log_level(const struct bpf_program *prog)
8480 return prog->log_level;
8483 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8485 if (prog->obj->loaded)
8486 return libbpf_err(-EBUSY);
8488 prog->log_level = log_level;
8492 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8494 *log_size = prog->log_size;
8495 return prog->log_buf;
8498 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8500 if (log_size && !log_buf)
8502 if (prog->log_size > UINT_MAX)
8504 if (prog->obj->loaded)
8507 prog->log_buf = log_buf;
8508 prog->log_size = log_size;
8512 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8513 .sec = (char *)sec_pfx, \
8514 .prog_type = BPF_PROG_TYPE_##ptype, \
8515 .expected_attach_type = atype, \
8516 .cookie = (long)(flags), \
8517 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
8521 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8522 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8523 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8524 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8525 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8526 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8527 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8528 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8529 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8530 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8532 static const struct bpf_sec_def section_defs[] = {
8533 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8534 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8535 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8536 SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8537 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8538 SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8539 SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8540 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8541 SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8542 SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8543 SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8544 SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8545 SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8546 SEC_DEF("usdt+", KPROBE, 0, SEC_NONE, attach_usdt),
8547 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
8548 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE),
8549 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE),
8550 SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8551 SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8552 SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8553 SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8554 SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8555 SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8556 SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8557 SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8558 SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8559 SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8560 SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8561 SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8562 SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8563 SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8564 SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8565 SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8566 SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8567 SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8568 SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8569 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8570 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8571 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8572 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8573 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8574 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
8575 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8576 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8577 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8578 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8579 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8580 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8581 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8582 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8583 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8584 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8585 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8586 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8587 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8588 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8589 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8590 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8591 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8592 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8593 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8594 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8595 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8596 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8597 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8598 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8599 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8600 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8601 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8602 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8603 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8604 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8605 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8606 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8607 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8608 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8609 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8610 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8611 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8612 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8613 SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
8614 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8617 static size_t custom_sec_def_cnt;
8618 static struct bpf_sec_def *custom_sec_defs;
8619 static struct bpf_sec_def custom_fallback_def;
8620 static bool has_custom_fallback_def;
8622 static int last_custom_sec_def_handler_id;
8624 int libbpf_register_prog_handler(const char *sec,
8625 enum bpf_prog_type prog_type,
8626 enum bpf_attach_type exp_attach_type,
8627 const struct libbpf_prog_handler_opts *opts)
8629 struct bpf_sec_def *sec_def;
8631 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8632 return libbpf_err(-EINVAL);
8634 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8635 return libbpf_err(-E2BIG);
8638 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8641 return libbpf_err(-ENOMEM);
8643 custom_sec_defs = sec_def;
8644 sec_def = &custom_sec_defs[custom_sec_def_cnt];
8646 if (has_custom_fallback_def)
8647 return libbpf_err(-EBUSY);
8649 sec_def = &custom_fallback_def;
8652 sec_def->sec = sec ? strdup(sec) : NULL;
8653 if (sec && !sec_def->sec)
8654 return libbpf_err(-ENOMEM);
8656 sec_def->prog_type = prog_type;
8657 sec_def->expected_attach_type = exp_attach_type;
8658 sec_def->cookie = OPTS_GET(opts, cookie, 0);
8660 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8661 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8662 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8664 sec_def->handler_id = ++last_custom_sec_def_handler_id;
8667 custom_sec_def_cnt++;
8669 has_custom_fallback_def = true;
8671 return sec_def->handler_id;
8674 int libbpf_unregister_prog_handler(int handler_id)
8676 struct bpf_sec_def *sec_defs;
8679 if (handler_id <= 0)
8680 return libbpf_err(-EINVAL);
8682 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8683 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8684 has_custom_fallback_def = false;
8688 for (i = 0; i < custom_sec_def_cnt; i++) {
8689 if (custom_sec_defs[i].handler_id == handler_id)
8693 if (i == custom_sec_def_cnt)
8694 return libbpf_err(-ENOENT);
8696 free(custom_sec_defs[i].sec);
8697 for (i = i + 1; i < custom_sec_def_cnt; i++)
8698 custom_sec_defs[i - 1] = custom_sec_defs[i];
8699 custom_sec_def_cnt--;
8701 /* try to shrink the array, but it's ok if we couldn't */
8702 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8704 custom_sec_defs = sec_defs;
8709 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8711 size_t len = strlen(sec_def->sec);
8713 /* "type/" always has to have proper SEC("type/extras") form */
8714 if (sec_def->sec[len - 1] == '/') {
8715 if (str_has_pfx(sec_name, sec_def->sec))
8720 /* "type+" means it can be either exact SEC("type") or
8721 * well-formed SEC("type/extras") with proper '/' separator
8723 if (sec_def->sec[len - 1] == '+') {
8725 /* not even a prefix */
8726 if (strncmp(sec_name, sec_def->sec, len) != 0)
8728 /* exact match or has '/' separator */
8729 if (sec_name[len] == '\0' || sec_name[len] == '/')
8734 return strcmp(sec_name, sec_def->sec) == 0;
8737 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8739 const struct bpf_sec_def *sec_def;
8742 n = custom_sec_def_cnt;
8743 for (i = 0; i < n; i++) {
8744 sec_def = &custom_sec_defs[i];
8745 if (sec_def_matches(sec_def, sec_name))
8749 n = ARRAY_SIZE(section_defs);
8750 for (i = 0; i < n; i++) {
8751 sec_def = §ion_defs[i];
8752 if (sec_def_matches(sec_def, sec_name))
8756 if (has_custom_fallback_def)
8757 return &custom_fallback_def;
8762 #define MAX_TYPE_NAME_SIZE 32
8764 static char *libbpf_get_type_names(bool attach_type)
8766 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8774 /* Forge string buf with all available names */
8775 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8776 const struct bpf_sec_def *sec_def = §ion_defs[i];
8779 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8782 if (!(sec_def->cookie & SEC_ATTACHABLE))
8786 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8791 strcat(buf, section_defs[i].sec);
8797 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8798 enum bpf_attach_type *expected_attach_type)
8800 const struct bpf_sec_def *sec_def;
8804 return libbpf_err(-EINVAL);
8806 sec_def = find_sec_def(name);
8808 *prog_type = sec_def->prog_type;
8809 *expected_attach_type = sec_def->expected_attach_type;
8813 pr_debug("failed to guess program type from ELF section '%s'\n", name);
8814 type_names = libbpf_get_type_names(false);
8815 if (type_names != NULL) {
8816 pr_debug("supported section(type) names are:%s\n", type_names);
8820 return libbpf_err(-ESRCH);
8823 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8825 if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8828 return attach_type_name[t];
8831 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8833 if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8836 return link_type_name[t];
8839 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8841 if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8844 return map_type_name[t];
8847 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8849 if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8852 return prog_type_name[t];
8855 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8858 struct bpf_map *map;
8861 for (i = 0; i < obj->nr_maps; i++) {
8862 map = &obj->maps[i];
8863 if (!bpf_map__is_struct_ops(map))
8865 if (map->sec_offset <= offset &&
8866 offset - map->sec_offset < map->def.value_size)
8873 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8874 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8875 Elf64_Shdr *shdr, Elf_Data *data)
8877 const struct btf_member *member;
8878 struct bpf_struct_ops *st_ops;
8879 struct bpf_program *prog;
8880 unsigned int shdr_idx;
8881 const struct btf *btf;
8882 struct bpf_map *map;
8883 unsigned int moff, insn_idx;
8891 nrels = shdr->sh_size / shdr->sh_entsize;
8892 for (i = 0; i < nrels; i++) {
8893 rel = elf_rel_by_idx(data, i);
8895 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8896 return -LIBBPF_ERRNO__FORMAT;
8899 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8901 pr_warn("struct_ops reloc: symbol %zx not found\n",
8902 (size_t)ELF64_R_SYM(rel->r_info));
8903 return -LIBBPF_ERRNO__FORMAT;
8906 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8907 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8909 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8910 (size_t)rel->r_offset);
8914 moff = rel->r_offset - map->sec_offset;
8915 shdr_idx = sym->st_shndx;
8916 st_ops = map->st_ops;
8917 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",
8919 (long long)(rel->r_info >> 32),
8920 (long long)sym->st_value,
8921 shdr_idx, (size_t)rel->r_offset,
8922 map->sec_offset, sym->st_name, name);
8924 if (shdr_idx >= SHN_LORESERVE) {
8925 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8926 map->name, (size_t)rel->r_offset, shdr_idx);
8927 return -LIBBPF_ERRNO__RELOC;
8929 if (sym->st_value % BPF_INSN_SZ) {
8930 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8931 map->name, (unsigned long long)sym->st_value);
8932 return -LIBBPF_ERRNO__FORMAT;
8934 insn_idx = sym->st_value / BPF_INSN_SZ;
8936 member = find_member_by_offset(st_ops->type, moff * 8);
8938 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8942 member_idx = member - btf_members(st_ops->type);
8943 name = btf__name_by_offset(btf, member->name_off);
8945 if (!resolve_func_ptr(btf, member->type, NULL)) {
8946 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8951 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8953 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8954 map->name, shdr_idx, name);
8958 /* prevent the use of BPF prog with invalid type */
8959 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8960 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8961 map->name, prog->name);
8965 /* if we haven't yet processed this BPF program, record proper
8966 * attach_btf_id and member_idx
8968 if (!prog->attach_btf_id) {
8969 prog->attach_btf_id = st_ops->type_id;
8970 prog->expected_attach_type = member_idx;
8973 /* struct_ops BPF prog can be re-used between multiple
8974 * .struct_ops as long as it's the same struct_ops struct
8975 * definition and the same function pointer field
8977 if (prog->attach_btf_id != st_ops->type_id ||
8978 prog->expected_attach_type != member_idx) {
8979 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",
8980 map->name, prog->name, prog->sec_name, prog->type,
8981 prog->attach_btf_id, prog->expected_attach_type, name);
8985 st_ops->progs[member_idx] = prog;
8991 #define BTF_TRACE_PREFIX "btf_trace_"
8992 #define BTF_LSM_PREFIX "bpf_lsm_"
8993 #define BTF_ITER_PREFIX "bpf_iter_"
8994 #define BTF_MAX_NAME_SIZE 128
8996 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8997 const char **prefix, int *kind)
8999 switch (attach_type) {
9000 case BPF_TRACE_RAW_TP:
9001 *prefix = BTF_TRACE_PREFIX;
9002 *kind = BTF_KIND_TYPEDEF;
9005 case BPF_LSM_CGROUP:
9006 *prefix = BTF_LSM_PREFIX;
9007 *kind = BTF_KIND_FUNC;
9009 case BPF_TRACE_ITER:
9010 *prefix = BTF_ITER_PREFIX;
9011 *kind = BTF_KIND_FUNC;
9015 *kind = BTF_KIND_FUNC;
9019 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9020 const char *name, __u32 kind)
9022 char btf_type_name[BTF_MAX_NAME_SIZE];
9025 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9026 "%s%s", prefix, name);
9027 /* snprintf returns the number of characters written excluding the
9028 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9029 * indicates truncation.
9031 if (ret < 0 || ret >= sizeof(btf_type_name))
9032 return -ENAMETOOLONG;
9033 return btf__find_by_name_kind(btf, btf_type_name, kind);
9036 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9037 enum bpf_attach_type attach_type)
9042 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9043 return find_btf_by_prefix_kind(btf, prefix, name, kind);
9046 int libbpf_find_vmlinux_btf_id(const char *name,
9047 enum bpf_attach_type attach_type)
9052 btf = btf__load_vmlinux_btf();
9053 err = libbpf_get_error(btf);
9055 pr_warn("vmlinux BTF is not found\n");
9056 return libbpf_err(err);
9059 err = find_attach_btf_id(btf, name, attach_type);
9061 pr_warn("%s is not found in vmlinux BTF\n", name);
9064 return libbpf_err(err);
9067 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9069 struct bpf_prog_info info;
9070 __u32 info_len = sizeof(info);
9074 memset(&info, 0, info_len);
9075 err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9077 pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9078 attach_prog_fd, err);
9084 pr_warn("The target program doesn't have BTF\n");
9087 btf = btf__load_from_kernel_by_id(info.btf_id);
9088 err = libbpf_get_error(btf);
9090 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9093 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9096 pr_warn("%s is not found in prog's BTF\n", name);
9103 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9104 enum bpf_attach_type attach_type,
9105 int *btf_obj_fd, int *btf_type_id)
9109 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9111 *btf_obj_fd = 0; /* vmlinux BTF */
9118 ret = load_module_btfs(obj);
9122 for (i = 0; i < obj->btf_module_cnt; i++) {
9123 const struct module_btf *mod = &obj->btf_modules[i];
9125 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9127 *btf_obj_fd = mod->fd;
9140 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9141 int *btf_obj_fd, int *btf_type_id)
9143 enum bpf_attach_type attach_type = prog->expected_attach_type;
9144 __u32 attach_prog_fd = prog->attach_prog_fd;
9147 /* BPF program's BTF ID */
9148 if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9149 if (!attach_prog_fd) {
9150 pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9153 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9155 pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9156 prog->name, attach_prog_fd, attach_name, err);
9164 /* kernel/module BTF ID */
9165 if (prog->obj->gen_loader) {
9166 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9170 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9173 pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9174 prog->name, attach_name, err);
9180 int libbpf_attach_type_by_name(const char *name,
9181 enum bpf_attach_type *attach_type)
9184 const struct bpf_sec_def *sec_def;
9187 return libbpf_err(-EINVAL);
9189 sec_def = find_sec_def(name);
9191 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9192 type_names = libbpf_get_type_names(true);
9193 if (type_names != NULL) {
9194 pr_debug("attachable section(type) names are:%s\n", type_names);
9198 return libbpf_err(-EINVAL);
9201 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9202 return libbpf_err(-EINVAL);
9203 if (!(sec_def->cookie & SEC_ATTACHABLE))
9204 return libbpf_err(-EINVAL);
9206 *attach_type = sec_def->expected_attach_type;
9210 int bpf_map__fd(const struct bpf_map *map)
9212 return map ? map->fd : libbpf_err(-EINVAL);
9215 static bool map_uses_real_name(const struct bpf_map *map)
9217 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9218 * their user-visible name differs from kernel-visible name. Users see
9219 * such map's corresponding ELF section name as a map name.
9220 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9221 * maps to know which name has to be returned to the user.
9223 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9225 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9230 const char *bpf_map__name(const struct bpf_map *map)
9235 if (map_uses_real_name(map))
9236 return map->real_name;
9241 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9243 return map->def.type;
9246 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9249 return libbpf_err(-EBUSY);
9250 map->def.type = type;
9254 __u32 bpf_map__map_flags(const struct bpf_map *map)
9256 return map->def.map_flags;
9259 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9262 return libbpf_err(-EBUSY);
9263 map->def.map_flags = flags;
9267 __u64 bpf_map__map_extra(const struct bpf_map *map)
9269 return map->map_extra;
9272 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9275 return libbpf_err(-EBUSY);
9276 map->map_extra = map_extra;
9280 __u32 bpf_map__numa_node(const struct bpf_map *map)
9282 return map->numa_node;
9285 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9288 return libbpf_err(-EBUSY);
9289 map->numa_node = numa_node;
9293 __u32 bpf_map__key_size(const struct bpf_map *map)
9295 return map->def.key_size;
9298 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9301 return libbpf_err(-EBUSY);
9302 map->def.key_size = size;
9306 __u32 bpf_map__value_size(const struct bpf_map *map)
9308 return map->def.value_size;
9311 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9314 return libbpf_err(-EBUSY);
9315 map->def.value_size = size;
9319 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9321 return map ? map->btf_key_type_id : 0;
9324 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9326 return map ? map->btf_value_type_id : 0;
9329 int bpf_map__set_initial_value(struct bpf_map *map,
9330 const void *data, size_t size)
9332 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9333 size != map->def.value_size || map->fd >= 0)
9334 return libbpf_err(-EINVAL);
9336 memcpy(map->mmaped, data, size);
9340 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9344 *psize = map->def.value_size;
9348 bool bpf_map__is_internal(const struct bpf_map *map)
9350 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9353 __u32 bpf_map__ifindex(const struct bpf_map *map)
9355 return map->map_ifindex;
9358 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9361 return libbpf_err(-EBUSY);
9362 map->map_ifindex = ifindex;
9366 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9368 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9369 pr_warn("error: unsupported map type\n");
9370 return libbpf_err(-EINVAL);
9372 if (map->inner_map_fd != -1) {
9373 pr_warn("error: inner_map_fd already specified\n");
9374 return libbpf_err(-EINVAL);
9376 if (map->inner_map) {
9377 bpf_map__destroy(map->inner_map);
9378 zfree(&map->inner_map);
9380 map->inner_map_fd = fd;
9384 static struct bpf_map *
9385 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9388 struct bpf_map *s, *e;
9390 if (!obj || !obj->maps)
9391 return errno = EINVAL, NULL;
9394 e = obj->maps + obj->nr_maps;
9396 if ((m < s) || (m >= e)) {
9397 pr_warn("error in %s: map handler doesn't belong to object\n",
9399 return errno = EINVAL, NULL;
9402 idx = (m - obj->maps) + i;
9403 if (idx >= obj->nr_maps || idx < 0)
9405 return &obj->maps[idx];
9409 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9414 return __bpf_map__iter(prev, obj, 1);
9418 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9423 return obj->maps + obj->nr_maps - 1;
9426 return __bpf_map__iter(next, obj, -1);
9430 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9432 struct bpf_map *pos;
9434 bpf_object__for_each_map(pos, obj) {
9435 /* if it's a special internal map name (which always starts
9436 * with dot) then check if that special name matches the
9437 * real map name (ELF section name)
9439 if (name[0] == '.') {
9440 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9444 /* otherwise map name has to be an exact match */
9445 if (map_uses_real_name(pos)) {
9446 if (strcmp(pos->real_name, name) == 0)
9450 if (strcmp(pos->name, name) == 0)
9453 return errno = ENOENT, NULL;
9457 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9459 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9462 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9463 size_t value_sz, bool check_value_sz)
9468 if (map->def.key_size != key_sz) {
9469 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9470 map->name, key_sz, map->def.key_size);
9474 if (!check_value_sz)
9477 switch (map->def.type) {
9478 case BPF_MAP_TYPE_PERCPU_ARRAY:
9479 case BPF_MAP_TYPE_PERCPU_HASH:
9480 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9481 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9482 int num_cpu = libbpf_num_possible_cpus();
9483 size_t elem_sz = roundup(map->def.value_size, 8);
9485 if (value_sz != num_cpu * elem_sz) {
9486 pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9487 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9493 if (map->def.value_size != value_sz) {
9494 pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9495 map->name, value_sz, map->def.value_size);
9503 int bpf_map__lookup_elem(const struct bpf_map *map,
9504 const void *key, size_t key_sz,
9505 void *value, size_t value_sz, __u64 flags)
9509 err = validate_map_op(map, key_sz, value_sz, true);
9511 return libbpf_err(err);
9513 return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9516 int bpf_map__update_elem(const struct bpf_map *map,
9517 const void *key, size_t key_sz,
9518 const void *value, size_t value_sz, __u64 flags)
9522 err = validate_map_op(map, key_sz, value_sz, true);
9524 return libbpf_err(err);
9526 return bpf_map_update_elem(map->fd, key, value, flags);
9529 int bpf_map__delete_elem(const struct bpf_map *map,
9530 const void *key, size_t key_sz, __u64 flags)
9534 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9536 return libbpf_err(err);
9538 return bpf_map_delete_elem_flags(map->fd, key, flags);
9541 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9542 const void *key, size_t key_sz,
9543 void *value, size_t value_sz, __u64 flags)
9547 err = validate_map_op(map, key_sz, value_sz, true);
9549 return libbpf_err(err);
9551 return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9554 int bpf_map__get_next_key(const struct bpf_map *map,
9555 const void *cur_key, void *next_key, size_t key_sz)
9559 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9561 return libbpf_err(err);
9563 return bpf_map_get_next_key(map->fd, cur_key, next_key);
9566 long libbpf_get_error(const void *ptr)
9568 if (!IS_ERR_OR_NULL(ptr))
9572 errno = -PTR_ERR(ptr);
9574 /* If ptr == NULL, then errno should be already set by the failing
9575 * API, because libbpf never returns NULL on success and it now always
9576 * sets errno on error. So no extra errno handling for ptr == NULL
9582 /* Replace link's underlying BPF program with the new one */
9583 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9587 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9588 return libbpf_err_errno(ret);
9591 /* Release "ownership" of underlying BPF resource (typically, BPF program
9592 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9593 * link, when destructed through bpf_link__destroy() call won't attempt to
9594 * detach/unregisted that BPF resource. This is useful in situations where,
9595 * say, attached BPF program has to outlive userspace program that attached it
9596 * in the system. Depending on type of BPF program, though, there might be
9597 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9598 * exit of userspace program doesn't trigger automatic detachment and clean up
9599 * inside the kernel.
9601 void bpf_link__disconnect(struct bpf_link *link)
9603 link->disconnected = true;
9606 int bpf_link__destroy(struct bpf_link *link)
9610 if (IS_ERR_OR_NULL(link))
9613 if (!link->disconnected && link->detach)
9614 err = link->detach(link);
9616 free(link->pin_path);
9618 link->dealloc(link);
9622 return libbpf_err(err);
9625 int bpf_link__fd(const struct bpf_link *link)
9630 const char *bpf_link__pin_path(const struct bpf_link *link)
9632 return link->pin_path;
9635 static int bpf_link__detach_fd(struct bpf_link *link)
9637 return libbpf_err_errno(close(link->fd));
9640 struct bpf_link *bpf_link__open(const char *path)
9642 struct bpf_link *link;
9645 fd = bpf_obj_get(path);
9648 pr_warn("failed to open link at %s: %d\n", path, fd);
9649 return libbpf_err_ptr(fd);
9652 link = calloc(1, sizeof(*link));
9655 return libbpf_err_ptr(-ENOMEM);
9657 link->detach = &bpf_link__detach_fd;
9660 link->pin_path = strdup(path);
9661 if (!link->pin_path) {
9662 bpf_link__destroy(link);
9663 return libbpf_err_ptr(-ENOMEM);
9669 int bpf_link__detach(struct bpf_link *link)
9671 return bpf_link_detach(link->fd) ? -errno : 0;
9674 int bpf_link__pin(struct bpf_link *link, const char *path)
9679 return libbpf_err(-EBUSY);
9680 err = make_parent_dir(path);
9682 return libbpf_err(err);
9683 err = check_path(path);
9685 return libbpf_err(err);
9687 link->pin_path = strdup(path);
9688 if (!link->pin_path)
9689 return libbpf_err(-ENOMEM);
9691 if (bpf_obj_pin(link->fd, link->pin_path)) {
9693 zfree(&link->pin_path);
9694 return libbpf_err(err);
9697 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9701 int bpf_link__unpin(struct bpf_link *link)
9705 if (!link->pin_path)
9706 return libbpf_err(-EINVAL);
9708 err = unlink(link->pin_path);
9712 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9713 zfree(&link->pin_path);
9717 struct bpf_link_perf {
9718 struct bpf_link link;
9720 /* legacy kprobe support: keep track of probe identifier and type */
9721 char *legacy_probe_name;
9722 bool legacy_is_kprobe;
9723 bool legacy_is_retprobe;
9726 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9727 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9729 static int bpf_link_perf_detach(struct bpf_link *link)
9731 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9734 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9737 if (perf_link->perf_event_fd != link->fd)
9738 close(perf_link->perf_event_fd);
9741 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9742 if (perf_link->legacy_probe_name) {
9743 if (perf_link->legacy_is_kprobe) {
9744 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9745 perf_link->legacy_is_retprobe);
9747 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9748 perf_link->legacy_is_retprobe);
9755 static void bpf_link_perf_dealloc(struct bpf_link *link)
9757 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9759 free(perf_link->legacy_probe_name);
9763 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9764 const struct bpf_perf_event_opts *opts)
9766 char errmsg[STRERR_BUFSIZE];
9767 struct bpf_link_perf *link;
9768 int prog_fd, link_fd = -1, err;
9769 bool force_ioctl_attach;
9771 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9772 return libbpf_err_ptr(-EINVAL);
9775 pr_warn("prog '%s': invalid perf event FD %d\n",
9777 return libbpf_err_ptr(-EINVAL);
9779 prog_fd = bpf_program__fd(prog);
9781 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9783 return libbpf_err_ptr(-EINVAL);
9786 link = calloc(1, sizeof(*link));
9788 return libbpf_err_ptr(-ENOMEM);
9789 link->link.detach = &bpf_link_perf_detach;
9790 link->link.dealloc = &bpf_link_perf_dealloc;
9791 link->perf_event_fd = pfd;
9793 force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
9794 if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
9795 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9796 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9798 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9801 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9803 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9806 link->link.fd = link_fd;
9808 if (OPTS_GET(opts, bpf_cookie, 0)) {
9809 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9814 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9816 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9817 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9819 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9823 link->link.fd = pfd;
9825 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9827 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9828 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9837 return libbpf_err_ptr(err);
9840 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9842 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9846 * this function is expected to parse integer in the range of [0, 2^31-1] from
9847 * given file using scanf format string fmt. If actual parsed value is
9848 * negative, the result might be indistinguishable from error
9850 static int parse_uint_from_file(const char *file, const char *fmt)
9852 char buf[STRERR_BUFSIZE];
9856 f = fopen(file, "r");
9859 pr_debug("failed to open '%s': %s\n", file,
9860 libbpf_strerror_r(err, buf, sizeof(buf)));
9863 err = fscanf(f, fmt, &ret);
9865 err = err == EOF ? -EIO : -errno;
9866 pr_debug("failed to parse '%s': %s\n", file,
9867 libbpf_strerror_r(err, buf, sizeof(buf)));
9875 static int determine_kprobe_perf_type(void)
9877 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9879 return parse_uint_from_file(file, "%d\n");
9882 static int determine_uprobe_perf_type(void)
9884 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9886 return parse_uint_from_file(file, "%d\n");
9889 static int determine_kprobe_retprobe_bit(void)
9891 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9893 return parse_uint_from_file(file, "config:%d\n");
9896 static int determine_uprobe_retprobe_bit(void)
9898 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9900 return parse_uint_from_file(file, "config:%d\n");
9903 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9904 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9906 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9907 uint64_t offset, int pid, size_t ref_ctr_off)
9909 const size_t attr_sz = sizeof(struct perf_event_attr);
9910 struct perf_event_attr attr;
9911 char errmsg[STRERR_BUFSIZE];
9914 if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9917 memset(&attr, 0, attr_sz);
9919 type = uprobe ? determine_uprobe_perf_type()
9920 : determine_kprobe_perf_type();
9922 pr_warn("failed to determine %s perf type: %s\n",
9923 uprobe ? "uprobe" : "kprobe",
9924 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9928 int bit = uprobe ? determine_uprobe_retprobe_bit()
9929 : determine_kprobe_retprobe_bit();
9932 pr_warn("failed to determine %s retprobe bit: %s\n",
9933 uprobe ? "uprobe" : "kprobe",
9934 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9937 attr.config |= 1 << bit;
9939 attr.size = attr_sz;
9941 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9942 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9943 attr.config2 = offset; /* kprobe_addr or probe_offset */
9945 /* pid filter is meaningful only for uprobes */
9946 pfd = syscall(__NR_perf_event_open, &attr,
9947 pid < 0 ? -1 : pid /* pid */,
9948 pid == -1 ? 0 : -1 /* cpu */,
9949 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9950 return pfd >= 0 ? pfd : -errno;
9953 static int append_to_file(const char *file, const char *fmt, ...)
9960 n = vsnprintf(buf, sizeof(buf), fmt, ap);
9963 if (n < 0 || n >= sizeof(buf))
9966 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9970 if (write(fd, buf, n) < 0)
9977 #define DEBUGFS "/sys/kernel/debug/tracing"
9978 #define TRACEFS "/sys/kernel/tracing"
9980 static bool use_debugfs(void)
9982 static int has_debugfs = -1;
9984 if (has_debugfs < 0)
9985 has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
9987 return has_debugfs == 1;
9990 static const char *tracefs_path(void)
9992 return use_debugfs() ? DEBUGFS : TRACEFS;
9995 static const char *tracefs_kprobe_events(void)
9997 return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10000 static const char *tracefs_uprobe_events(void)
10002 return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10005 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10006 const char *kfunc_name, size_t offset)
10008 static int index = 0;
10011 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10012 __sync_fetch_and_add(&index, 1));
10014 /* sanitize binary_path in the probe name */
10015 for (i = 0; buf[i]; i++) {
10016 if (!isalnum(buf[i]))
10021 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10022 const char *kfunc_name, size_t offset)
10024 return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10025 retprobe ? 'r' : 'p',
10026 retprobe ? "kretprobes" : "kprobes",
10027 probe_name, kfunc_name, offset);
10030 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10032 return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10033 retprobe ? "kretprobes" : "kprobes", probe_name);
10036 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10040 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10041 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10043 return parse_uint_from_file(file, "%d\n");
10046 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10047 const char *kfunc_name, size_t offset, int pid)
10049 const size_t attr_sz = sizeof(struct perf_event_attr);
10050 struct perf_event_attr attr;
10051 char errmsg[STRERR_BUFSIZE];
10052 int type, pfd, err;
10054 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10056 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10057 kfunc_name, offset,
10058 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10061 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10064 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10065 kfunc_name, offset,
10066 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10067 goto err_clean_legacy;
10070 memset(&attr, 0, attr_sz);
10071 attr.size = attr_sz;
10072 attr.config = type;
10073 attr.type = PERF_TYPE_TRACEPOINT;
10075 pfd = syscall(__NR_perf_event_open, &attr,
10076 pid < 0 ? -1 : pid, /* pid */
10077 pid == -1 ? 0 : -1, /* cpu */
10078 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10081 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10082 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10083 goto err_clean_legacy;
10088 /* Clear the newly added legacy kprobe_event */
10089 remove_kprobe_event_legacy(probe_name, retprobe);
10093 static const char *arch_specific_syscall_pfx(void)
10095 #if defined(__x86_64__)
10097 #elif defined(__i386__)
10099 #elif defined(__s390x__)
10101 #elif defined(__s390__)
10103 #elif defined(__arm__)
10105 #elif defined(__aarch64__)
10107 #elif defined(__mips__)
10109 #elif defined(__riscv)
10111 #elif defined(__powerpc__)
10113 #elif defined(__powerpc64__)
10114 return "powerpc64";
10120 static int probe_kern_syscall_wrapper(void)
10122 char syscall_name[64];
10123 const char *ksys_pfx;
10125 ksys_pfx = arch_specific_syscall_pfx();
10129 snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10131 if (determine_kprobe_perf_type() >= 0) {
10134 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10138 return pfd >= 0 ? 1 : 0;
10139 } else { /* legacy mode */
10140 char probe_name[128];
10142 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10143 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10146 (void)remove_kprobe_event_legacy(probe_name, false);
10152 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10153 const char *func_name,
10154 const struct bpf_kprobe_opts *opts)
10156 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10157 enum probe_attach_mode attach_mode;
10158 char errmsg[STRERR_BUFSIZE];
10159 char *legacy_probe = NULL;
10160 struct bpf_link *link;
10162 bool retprobe, legacy;
10165 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10166 return libbpf_err_ptr(-EINVAL);
10168 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10169 retprobe = OPTS_GET(opts, retprobe, false);
10170 offset = OPTS_GET(opts, offset, 0);
10171 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10173 legacy = determine_kprobe_perf_type() < 0;
10174 switch (attach_mode) {
10175 case PROBE_ATTACH_MODE_LEGACY:
10177 pe_opts.force_ioctl_attach = true;
10179 case PROBE_ATTACH_MODE_PERF:
10181 return libbpf_err_ptr(-ENOTSUP);
10182 pe_opts.force_ioctl_attach = true;
10184 case PROBE_ATTACH_MODE_LINK:
10185 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10186 return libbpf_err_ptr(-ENOTSUP);
10188 case PROBE_ATTACH_MODE_DEFAULT:
10191 return libbpf_err_ptr(-EINVAL);
10195 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10197 -1 /* pid */, 0 /* ref_ctr_off */);
10199 char probe_name[256];
10201 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10202 func_name, offset);
10204 legacy_probe = strdup(probe_name);
10206 return libbpf_err_ptr(-ENOMEM);
10208 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10209 offset, -1 /* pid */);
10213 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10214 prog->name, retprobe ? "kretprobe" : "kprobe",
10216 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10219 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10220 err = libbpf_get_error(link);
10223 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10224 prog->name, retprobe ? "kretprobe" : "kprobe",
10226 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10227 goto err_clean_legacy;
10230 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10232 perf_link->legacy_probe_name = legacy_probe;
10233 perf_link->legacy_is_kprobe = true;
10234 perf_link->legacy_is_retprobe = retprobe;
10241 remove_kprobe_event_legacy(legacy_probe, retprobe);
10243 free(legacy_probe);
10244 return libbpf_err_ptr(err);
10247 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10249 const char *func_name)
10251 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10252 .retprobe = retprobe,
10255 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10258 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10259 const char *syscall_name,
10260 const struct bpf_ksyscall_opts *opts)
10262 LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10263 char func_name[128];
10265 if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10266 return libbpf_err_ptr(-EINVAL);
10268 if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10269 /* arch_specific_syscall_pfx() should never return NULL here
10270 * because it is guarded by kernel_supports(). However, since
10271 * compiler does not know that we have an explicit conditional
10274 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10275 arch_specific_syscall_pfx() ? : "", syscall_name);
10277 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10280 kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10281 kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10283 return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10286 /* Adapted from perf/util/string.c */
10287 static bool glob_match(const char *str, const char *pat)
10289 while (*str && *pat && *pat != '*') {
10290 if (*pat == '?') { /* Matches any single character */
10300 /* Check wild card */
10302 while (*pat == '*')
10304 if (!*pat) /* Tail wild card matches all */
10307 if (glob_match(str++, pat))
10310 return !*str && !*pat;
10313 struct kprobe_multi_resolve {
10314 const char *pattern;
10315 unsigned long *addrs;
10321 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10322 const char *sym_name, void *ctx)
10324 struct kprobe_multi_resolve *res = ctx;
10327 if (!glob_match(sym_name, res->pattern))
10330 err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10335 res->addrs[res->cnt++] = (unsigned long) sym_addr;
10340 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10341 const char *pattern,
10342 const struct bpf_kprobe_multi_opts *opts)
10344 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10345 struct kprobe_multi_resolve res = {
10346 .pattern = pattern,
10348 struct bpf_link *link = NULL;
10349 char errmsg[STRERR_BUFSIZE];
10350 const unsigned long *addrs;
10351 int err, link_fd, prog_fd;
10352 const __u64 *cookies;
10357 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10358 return libbpf_err_ptr(-EINVAL);
10360 syms = OPTS_GET(opts, syms, false);
10361 addrs = OPTS_GET(opts, addrs, false);
10362 cnt = OPTS_GET(opts, cnt, false);
10363 cookies = OPTS_GET(opts, cookies, false);
10365 if (!pattern && !addrs && !syms)
10366 return libbpf_err_ptr(-EINVAL);
10367 if (pattern && (addrs || syms || cookies || cnt))
10368 return libbpf_err_ptr(-EINVAL);
10369 if (!pattern && !cnt)
10370 return libbpf_err_ptr(-EINVAL);
10372 return libbpf_err_ptr(-EINVAL);
10375 err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10386 retprobe = OPTS_GET(opts, retprobe, false);
10388 lopts.kprobe_multi.syms = syms;
10389 lopts.kprobe_multi.addrs = addrs;
10390 lopts.kprobe_multi.cookies = cookies;
10391 lopts.kprobe_multi.cnt = cnt;
10392 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10394 link = calloc(1, sizeof(*link));
10399 link->detach = &bpf_link__detach_fd;
10401 prog_fd = bpf_program__fd(prog);
10402 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10405 pr_warn("prog '%s': failed to attach: %s\n",
10406 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10409 link->fd = link_fd;
10416 return libbpf_err_ptr(err);
10419 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10421 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10422 unsigned long offset = 0;
10423 const char *func_name;
10429 /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10430 if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10433 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10435 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10437 func_name = prog->sec_name + sizeof("kprobe/") - 1;
10439 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10441 pr_warn("kprobe name is invalid: %s\n", func_name);
10444 if (opts.retprobe && offset != 0) {
10446 pr_warn("kretprobes do not support offset specification\n");
10450 opts.offset = offset;
10451 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10453 return libbpf_get_error(*link);
10456 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10458 LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10459 const char *syscall_name;
10463 /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10464 if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10467 opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10469 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10471 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10473 *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10474 return *link ? 0 : -errno;
10477 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10479 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10486 /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10487 if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10488 strcmp(prog->sec_name, "kretprobe.multi") == 0)
10491 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10493 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10495 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10497 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10499 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10503 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10505 return libbpf_get_error(*link);
10508 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10509 const char *binary_path, uint64_t offset)
10513 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10515 /* sanitize binary_path in the probe name */
10516 for (i = 0; buf[i]; i++) {
10517 if (!isalnum(buf[i]))
10522 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10523 const char *binary_path, size_t offset)
10525 return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10526 retprobe ? 'r' : 'p',
10527 retprobe ? "uretprobes" : "uprobes",
10528 probe_name, binary_path, offset);
10531 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10533 return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10534 retprobe ? "uretprobes" : "uprobes", probe_name);
10537 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10541 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10542 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10544 return parse_uint_from_file(file, "%d\n");
10547 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10548 const char *binary_path, size_t offset, int pid)
10550 const size_t attr_sz = sizeof(struct perf_event_attr);
10551 struct perf_event_attr attr;
10552 int type, pfd, err;
10554 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10556 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10557 binary_path, (size_t)offset, err);
10560 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10563 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10564 binary_path, offset, err);
10565 goto err_clean_legacy;
10568 memset(&attr, 0, attr_sz);
10569 attr.size = attr_sz;
10570 attr.config = type;
10571 attr.type = PERF_TYPE_TRACEPOINT;
10573 pfd = syscall(__NR_perf_event_open, &attr,
10574 pid < 0 ? -1 : pid, /* pid */
10575 pid == -1 ? 0 : -1, /* cpu */
10576 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10579 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10580 goto err_clean_legacy;
10585 /* Clear the newly added legacy uprobe_event */
10586 remove_uprobe_event_legacy(probe_name, retprobe);
10590 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10591 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10593 while ((scn = elf_nextscn(elf, scn)) != NULL) {
10596 if (!gelf_getshdr(scn, &sh))
10598 if (sh.sh_type == sh_type)
10604 /* Find offset of function name in the provided ELF object. "binary_path" is
10605 * the path to the ELF binary represented by "elf", and only used for error
10606 * reporting matters. "name" matches symbol name or name@@LIB for library
10609 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
10611 int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10612 bool is_shared_lib, is_name_qualified;
10613 long ret = -ENOENT;
10617 if (!gelf_getehdr(elf, &ehdr)) {
10618 pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10619 ret = -LIBBPF_ERRNO__FORMAT;
10622 /* for shared lib case, we do not need to calculate relative offset */
10623 is_shared_lib = ehdr.e_type == ET_DYN;
10625 name_len = strlen(name);
10626 /* Does name specify "@@LIB"? */
10627 is_name_qualified = strstr(name, "@@") != NULL;
10629 /* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10630 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10631 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10632 * reported as a warning/error.
10634 for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10635 size_t nr_syms, strtabidx, idx;
10636 Elf_Data *symbols = NULL;
10637 Elf_Scn *scn = NULL;
10638 int last_bind = -1;
10642 scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10644 pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10648 if (!gelf_getshdr(scn, &sh))
10650 strtabidx = sh.sh_link;
10651 symbols = elf_getdata(scn, 0);
10653 pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10654 binary_path, elf_errmsg(-1));
10655 ret = -LIBBPF_ERRNO__FORMAT;
10658 nr_syms = symbols->d_size / sh.sh_entsize;
10660 for (idx = 0; idx < nr_syms; idx++) {
10666 if (!gelf_getsym(symbols, idx, &sym))
10669 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10672 sname = elf_strptr(elf, strtabidx, sym.st_name);
10676 curr_bind = GELF_ST_BIND(sym.st_info);
10678 /* User can specify func, func@@LIB or func@@LIB_VERSION. */
10679 if (strncmp(sname, name, name_len) != 0)
10681 /* ...but we don't want a search for "foo" to match 'foo2" also, so any
10682 * additional characters in sname should be of the form "@@LIB".
10684 if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10688 /* handle multiple matches */
10689 if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10690 /* Only accept one non-weak bind. */
10691 pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10692 sname, name, binary_path);
10693 ret = -LIBBPF_ERRNO__FORMAT;
10695 } else if (curr_bind == STB_WEAK) {
10696 /* already have a non-weak bind, and
10697 * this is a weak bind, so ignore.
10703 /* Transform symbol's virtual address (absolute for
10704 * binaries and relative for shared libs) into file
10705 * offset, which is what kernel is expecting for
10706 * uprobe/uretprobe attachment.
10707 * See Documentation/trace/uprobetracer.rst for more
10709 * This is done by looking up symbol's containing
10710 * section's header and using it's virtual address
10711 * (sh_addr) and corresponding file offset (sh_offset)
10712 * to transform sym.st_value (virtual address) into
10713 * desired final file offset.
10715 sym_scn = elf_getscn(elf, sym.st_shndx);
10718 if (!gelf_getshdr(sym_scn, &sym_sh))
10721 ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10722 last_bind = curr_bind;
10729 pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10733 pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10734 is_shared_lib ? "should not be 0 in a shared library" :
10735 "try using shared library path instead");
10738 pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10745 /* Find offset of function name in ELF object specified by path. "name" matches
10746 * symbol name or name@@LIB for library functions.
10748 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
10750 char errmsg[STRERR_BUFSIZE];
10751 long ret = -ENOENT;
10755 fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10758 pr_warn("failed to open %s: %s\n", binary_path,
10759 libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10762 elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10764 pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10766 return -LIBBPF_ERRNO__FORMAT;
10769 ret = elf_find_func_offset(elf, binary_path, name);
10775 /* Find offset of function name in archive specified by path. Currently
10776 * supported are .zip files that do not compress their contents, as used on
10777 * Android in the form of APKs, for example. "file_name" is the name of the ELF
10778 * file inside the archive. "func_name" matches symbol name or name@@LIB for
10779 * library functions.
10781 * An overview of the APK format specifically provided here:
10782 * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
10784 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
10785 const char *func_name)
10787 struct zip_archive *archive;
10788 struct zip_entry entry;
10792 archive = zip_archive_open(archive_path);
10793 if (IS_ERR(archive)) {
10794 ret = PTR_ERR(archive);
10795 pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
10799 ret = zip_archive_find_entry(archive, file_name, &entry);
10801 pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
10802 archive_path, ret);
10805 pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
10806 (unsigned long)entry.data_offset);
10808 if (entry.compression) {
10809 pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
10811 ret = -LIBBPF_ERRNO__FORMAT;
10815 elf = elf_memory((void *)entry.data, entry.data_length);
10817 pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
10819 ret = -LIBBPF_ERRNO__LIBELF;
10823 ret = elf_find_func_offset(elf, file_name, func_name);
10825 pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
10826 func_name, file_name, archive_path, entry.data_offset, ret,
10827 ret + entry.data_offset);
10828 ret += entry.data_offset;
10833 zip_archive_close(archive);
10837 static const char *arch_specific_lib_paths(void)
10840 * Based on https://packages.debian.org/sid/libc6.
10842 * Assume that the traced program is built for the same architecture
10843 * as libbpf, which should cover the vast majority of cases.
10845 #if defined(__x86_64__)
10846 return "/lib/x86_64-linux-gnu";
10847 #elif defined(__i386__)
10848 return "/lib/i386-linux-gnu";
10849 #elif defined(__s390x__)
10850 return "/lib/s390x-linux-gnu";
10851 #elif defined(__s390__)
10852 return "/lib/s390-linux-gnu";
10853 #elif defined(__arm__) && defined(__SOFTFP__)
10854 return "/lib/arm-linux-gnueabi";
10855 #elif defined(__arm__) && !defined(__SOFTFP__)
10856 return "/lib/arm-linux-gnueabihf";
10857 #elif defined(__aarch64__)
10858 return "/lib/aarch64-linux-gnu";
10859 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10860 return "/lib/mips64el-linux-gnuabi64";
10861 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10862 return "/lib/mipsel-linux-gnu";
10863 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10864 return "/lib/powerpc64le-linux-gnu";
10865 #elif defined(__sparc__) && defined(__arch64__)
10866 return "/lib/sparc64-linux-gnu";
10867 #elif defined(__riscv) && __riscv_xlen == 64
10868 return "/lib/riscv64-linux-gnu";
10874 /* Get full path to program/shared library. */
10875 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10877 const char *search_paths[3] = {};
10880 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10881 search_paths[0] = getenv("LD_LIBRARY_PATH");
10882 search_paths[1] = "/usr/lib64:/usr/lib";
10883 search_paths[2] = arch_specific_lib_paths();
10886 search_paths[0] = getenv("PATH");
10887 search_paths[1] = "/usr/bin:/usr/sbin";
10888 perm = R_OK | X_OK;
10891 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10894 if (!search_paths[i])
10896 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10902 next_path = strchr(s, ':');
10903 seg_len = next_path ? next_path - s : strlen(s);
10906 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10907 /* ensure it has required permissions */
10908 if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
10910 pr_debug("resolved '%s' to '%s'\n", file, result);
10917 LIBBPF_API struct bpf_link *
10918 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10919 const char *binary_path, size_t func_offset,
10920 const struct bpf_uprobe_opts *opts)
10922 const char *archive_path = NULL, *archive_sep = NULL;
10923 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10924 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10925 enum probe_attach_mode attach_mode;
10926 char full_path[PATH_MAX];
10927 struct bpf_link *link;
10928 size_t ref_ctr_off;
10930 bool retprobe, legacy;
10931 const char *func_name;
10933 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10934 return libbpf_err_ptr(-EINVAL);
10936 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10937 retprobe = OPTS_GET(opts, retprobe, false);
10938 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10939 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10942 return libbpf_err_ptr(-EINVAL);
10944 /* Check if "binary_path" refers to an archive. */
10945 archive_sep = strstr(binary_path, "!/");
10947 full_path[0] = '\0';
10948 libbpf_strlcpy(full_path, binary_path,
10949 min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
10950 archive_path = full_path;
10951 binary_path = archive_sep + 2;
10952 } else if (!strchr(binary_path, '/')) {
10953 err = resolve_full_path(binary_path, full_path, sizeof(full_path));
10955 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10956 prog->name, binary_path, err);
10957 return libbpf_err_ptr(err);
10959 binary_path = full_path;
10961 func_name = OPTS_GET(opts, func_name, NULL);
10965 if (archive_path) {
10966 sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
10968 binary_path = archive_path;
10970 sym_off = elf_find_func_offset_from_file(binary_path, func_name);
10973 return libbpf_err_ptr(sym_off);
10974 func_offset += sym_off;
10977 legacy = determine_uprobe_perf_type() < 0;
10978 switch (attach_mode) {
10979 case PROBE_ATTACH_MODE_LEGACY:
10981 pe_opts.force_ioctl_attach = true;
10983 case PROBE_ATTACH_MODE_PERF:
10985 return libbpf_err_ptr(-ENOTSUP);
10986 pe_opts.force_ioctl_attach = true;
10988 case PROBE_ATTACH_MODE_LINK:
10989 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10990 return libbpf_err_ptr(-ENOTSUP);
10992 case PROBE_ATTACH_MODE_DEFAULT:
10995 return libbpf_err_ptr(-EINVAL);
10999 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11000 func_offset, pid, ref_ctr_off);
11002 char probe_name[PATH_MAX + 64];
11005 return libbpf_err_ptr(-EINVAL);
11007 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11008 binary_path, func_offset);
11010 legacy_probe = strdup(probe_name);
11012 return libbpf_err_ptr(-ENOMEM);
11014 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11015 binary_path, func_offset, pid);
11019 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11020 prog->name, retprobe ? "uretprobe" : "uprobe",
11021 binary_path, func_offset,
11022 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11026 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11027 err = libbpf_get_error(link);
11030 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11031 prog->name, retprobe ? "uretprobe" : "uprobe",
11032 binary_path, func_offset,
11033 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11034 goto err_clean_legacy;
11037 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11039 perf_link->legacy_probe_name = legacy_probe;
11040 perf_link->legacy_is_kprobe = false;
11041 perf_link->legacy_is_retprobe = retprobe;
11047 remove_uprobe_event_legacy(legacy_probe, retprobe);
11049 free(legacy_probe);
11050 return libbpf_err_ptr(err);
11053 /* Format of u[ret]probe section definition supporting auto-attach:
11054 * u[ret]probe/binary:function[+offset]
11056 * binary can be an absolute/relative path or a filename; the latter is resolved to a
11057 * full binary path via bpf_program__attach_uprobe_opts.
11059 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11060 * specified (and auto-attach is not possible) or the above format is specified for
11063 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11065 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11066 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11067 int n, ret = -EINVAL;
11072 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11073 &probe_type, &binary_path, &func_name, &offset);
11076 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11080 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11081 prog->name, prog->sec_name);
11085 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11086 strcmp(probe_type, "uretprobe.s") == 0;
11087 if (opts.retprobe && offset != 0) {
11088 pr_warn("prog '%s': uretprobes do not support offset specification\n",
11092 opts.func_name = func_name;
11093 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11094 ret = libbpf_get_error(*link);
11097 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11108 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11109 bool retprobe, pid_t pid,
11110 const char *binary_path,
11111 size_t func_offset)
11113 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11115 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11118 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11119 pid_t pid, const char *binary_path,
11120 const char *usdt_provider, const char *usdt_name,
11121 const struct bpf_usdt_opts *opts)
11123 char resolved_path[512];
11124 struct bpf_object *obj = prog->obj;
11125 struct bpf_link *link;
11129 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11130 return libbpf_err_ptr(-EINVAL);
11132 if (bpf_program__fd(prog) < 0) {
11133 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11135 return libbpf_err_ptr(-EINVAL);
11139 return libbpf_err_ptr(-EINVAL);
11141 if (!strchr(binary_path, '/')) {
11142 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11144 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11145 prog->name, binary_path, err);
11146 return libbpf_err_ptr(err);
11148 binary_path = resolved_path;
11151 /* USDT manager is instantiated lazily on first USDT attach. It will
11152 * be destroyed together with BPF object in bpf_object__close().
11154 if (IS_ERR(obj->usdt_man))
11155 return libbpf_ptr(obj->usdt_man);
11156 if (!obj->usdt_man) {
11157 obj->usdt_man = usdt_manager_new(obj);
11158 if (IS_ERR(obj->usdt_man))
11159 return libbpf_ptr(obj->usdt_man);
11162 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11163 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11164 usdt_provider, usdt_name, usdt_cookie);
11165 err = libbpf_get_error(link);
11167 return libbpf_err_ptr(err);
11171 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11173 char *path = NULL, *provider = NULL, *name = NULL;
11174 const char *sec_name;
11177 sec_name = bpf_program__section_name(prog);
11178 if (strcmp(sec_name, "usdt") == 0) {
11179 /* no auto-attach for just SEC("usdt") */
11184 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11186 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11190 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11191 provider, name, NULL);
11192 err = libbpf_get_error(*link);
11200 static int determine_tracepoint_id(const char *tp_category,
11201 const char *tp_name)
11203 char file[PATH_MAX];
11206 ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11207 tracefs_path(), tp_category, tp_name);
11210 if (ret >= sizeof(file)) {
11211 pr_debug("tracepoint %s/%s path is too long\n",
11212 tp_category, tp_name);
11215 return parse_uint_from_file(file, "%d\n");
11218 static int perf_event_open_tracepoint(const char *tp_category,
11219 const char *tp_name)
11221 const size_t attr_sz = sizeof(struct perf_event_attr);
11222 struct perf_event_attr attr;
11223 char errmsg[STRERR_BUFSIZE];
11224 int tp_id, pfd, err;
11226 tp_id = determine_tracepoint_id(tp_category, tp_name);
11228 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11229 tp_category, tp_name,
11230 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11234 memset(&attr, 0, attr_sz);
11235 attr.type = PERF_TYPE_TRACEPOINT;
11236 attr.size = attr_sz;
11237 attr.config = tp_id;
11239 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11240 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11243 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11244 tp_category, tp_name,
11245 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11251 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11252 const char *tp_category,
11253 const char *tp_name,
11254 const struct bpf_tracepoint_opts *opts)
11256 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11257 char errmsg[STRERR_BUFSIZE];
11258 struct bpf_link *link;
11261 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11262 return libbpf_err_ptr(-EINVAL);
11264 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11266 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11268 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11269 prog->name, tp_category, tp_name,
11270 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11271 return libbpf_err_ptr(pfd);
11273 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11274 err = libbpf_get_error(link);
11277 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11278 prog->name, tp_category, tp_name,
11279 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11280 return libbpf_err_ptr(err);
11285 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11286 const char *tp_category,
11287 const char *tp_name)
11289 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11292 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11294 char *sec_name, *tp_cat, *tp_name;
11298 /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11299 if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11302 sec_name = strdup(prog->sec_name);
11306 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11307 if (str_has_pfx(prog->sec_name, "tp/"))
11308 tp_cat = sec_name + sizeof("tp/") - 1;
11310 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11311 tp_name = strchr(tp_cat, '/');
11319 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11321 return libbpf_get_error(*link);
11324 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11325 const char *tp_name)
11327 char errmsg[STRERR_BUFSIZE];
11328 struct bpf_link *link;
11331 prog_fd = bpf_program__fd(prog);
11333 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11334 return libbpf_err_ptr(-EINVAL);
11337 link = calloc(1, sizeof(*link));
11339 return libbpf_err_ptr(-ENOMEM);
11340 link->detach = &bpf_link__detach_fd;
11342 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11346 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11347 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11348 return libbpf_err_ptr(pfd);
11354 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11356 static const char *const prefixes[] = {
11360 "raw_tracepoint.w",
11363 const char *tp_name = NULL;
11367 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11370 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11373 pfx_len = strlen(prefixes[i]);
11374 /* no auto-attach case of, e.g., SEC("raw_tp") */
11375 if (prog->sec_name[pfx_len] == '\0')
11378 if (prog->sec_name[pfx_len] != '/')
11381 tp_name = prog->sec_name + pfx_len + 1;
11386 pr_warn("prog '%s': invalid section name '%s'\n",
11387 prog->name, prog->sec_name);
11391 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11392 return libbpf_get_error(*link);
11395 /* Common logic for all BPF program types that attach to a btf_id */
11396 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11397 const struct bpf_trace_opts *opts)
11399 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11400 char errmsg[STRERR_BUFSIZE];
11401 struct bpf_link *link;
11404 if (!OPTS_VALID(opts, bpf_trace_opts))
11405 return libbpf_err_ptr(-EINVAL);
11407 prog_fd = bpf_program__fd(prog);
11409 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11410 return libbpf_err_ptr(-EINVAL);
11413 link = calloc(1, sizeof(*link));
11415 return libbpf_err_ptr(-ENOMEM);
11416 link->detach = &bpf_link__detach_fd;
11418 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11419 link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11420 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11424 pr_warn("prog '%s': failed to attach: %s\n",
11425 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11426 return libbpf_err_ptr(pfd);
11432 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11434 return bpf_program__attach_btf_id(prog, NULL);
11437 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11438 const struct bpf_trace_opts *opts)
11440 return bpf_program__attach_btf_id(prog, opts);
11443 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11445 return bpf_program__attach_btf_id(prog, NULL);
11448 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11450 *link = bpf_program__attach_trace(prog);
11451 return libbpf_get_error(*link);
11454 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11456 *link = bpf_program__attach_lsm(prog);
11457 return libbpf_get_error(*link);
11460 static struct bpf_link *
11461 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11462 const char *target_name)
11464 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11465 .target_btf_id = btf_id);
11466 enum bpf_attach_type attach_type;
11467 char errmsg[STRERR_BUFSIZE];
11468 struct bpf_link *link;
11469 int prog_fd, link_fd;
11471 prog_fd = bpf_program__fd(prog);
11473 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11474 return libbpf_err_ptr(-EINVAL);
11477 link = calloc(1, sizeof(*link));
11479 return libbpf_err_ptr(-ENOMEM);
11480 link->detach = &bpf_link__detach_fd;
11482 attach_type = bpf_program__expected_attach_type(prog);
11483 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11487 pr_warn("prog '%s': failed to attach to %s: %s\n",
11488 prog->name, target_name,
11489 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11490 return libbpf_err_ptr(link_fd);
11492 link->fd = link_fd;
11497 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11499 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11503 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11505 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11508 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11510 /* target_fd/target_ifindex use the same field in LINK_CREATE */
11511 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11514 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11516 const char *attach_func_name)
11520 if (!!target_fd != !!attach_func_name) {
11521 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11523 return libbpf_err_ptr(-EINVAL);
11526 if (prog->type != BPF_PROG_TYPE_EXT) {
11527 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11529 return libbpf_err_ptr(-EINVAL);
11533 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11535 return libbpf_err_ptr(btf_id);
11537 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11539 /* no target, so use raw_tracepoint_open for compatibility
11542 return bpf_program__attach_trace(prog);
11547 bpf_program__attach_iter(const struct bpf_program *prog,
11548 const struct bpf_iter_attach_opts *opts)
11550 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11551 char errmsg[STRERR_BUFSIZE];
11552 struct bpf_link *link;
11553 int prog_fd, link_fd;
11554 __u32 target_fd = 0;
11556 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11557 return libbpf_err_ptr(-EINVAL);
11559 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11560 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11562 prog_fd = bpf_program__fd(prog);
11564 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11565 return libbpf_err_ptr(-EINVAL);
11568 link = calloc(1, sizeof(*link));
11570 return libbpf_err_ptr(-ENOMEM);
11571 link->detach = &bpf_link__detach_fd;
11573 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11574 &link_create_opts);
11578 pr_warn("prog '%s': failed to attach to iterator: %s\n",
11579 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11580 return libbpf_err_ptr(link_fd);
11582 link->fd = link_fd;
11586 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11588 *link = bpf_program__attach_iter(prog, NULL);
11589 return libbpf_get_error(*link);
11592 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11594 struct bpf_link *link = NULL;
11597 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11598 return libbpf_err_ptr(-EOPNOTSUPP);
11600 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11602 return libbpf_err_ptr(err);
11604 /* When calling bpf_program__attach() explicitly, auto-attach support
11605 * is expected to work, so NULL returned link is considered an error.
11606 * This is different for skeleton's attach, see comment in
11607 * bpf_object__attach_skeleton().
11610 return libbpf_err_ptr(-EOPNOTSUPP);
11615 struct bpf_link_struct_ops {
11616 struct bpf_link link;
11620 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11622 struct bpf_link_struct_ops *st_link;
11625 st_link = container_of(link, struct bpf_link_struct_ops, link);
11627 if (st_link->map_fd < 0)
11628 /* w/o a real link */
11629 return bpf_map_delete_elem(link->fd, &zero);
11631 return close(link->fd);
11634 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11636 struct bpf_link_struct_ops *link;
11640 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11641 return libbpf_err_ptr(-EINVAL);
11643 link = calloc(1, sizeof(*link));
11645 return libbpf_err_ptr(-EINVAL);
11647 /* kern_vdata should be prepared during the loading phase. */
11648 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11649 /* It can be EBUSY if the map has been used to create or
11650 * update a link before. We don't allow updating the value of
11651 * a struct_ops once it is set. That ensures that the value
11652 * never changed. So, it is safe to skip EBUSY.
11654 if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
11656 return libbpf_err_ptr(err);
11659 link->link.detach = bpf_link__detach_struct_ops;
11661 if (!(map->def.map_flags & BPF_F_LINK)) {
11662 /* w/o a real link */
11663 link->link.fd = map->fd;
11665 return &link->link;
11668 fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
11671 return libbpf_err_ptr(fd);
11674 link->link.fd = fd;
11675 link->map_fd = map->fd;
11677 return &link->link;
11681 * Swap the back struct_ops of a link with a new struct_ops map.
11683 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
11685 struct bpf_link_struct_ops *st_ops_link;
11689 if (!bpf_map__is_struct_ops(map) || map->fd < 0)
11692 st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
11693 /* Ensure the type of a link is correct */
11694 if (st_ops_link->map_fd < 0)
11697 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11698 /* It can be EBUSY if the map has been used to create or
11699 * update a link before. We don't allow updating the value of
11700 * a struct_ops once it is set. That ensures that the value
11701 * never changed. So, it is safe to skip EBUSY.
11703 if (err && err != -EBUSY)
11706 err = bpf_link_update(link->fd, map->fd, NULL);
11710 st_ops_link->map_fd = map->fd;
11715 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11716 void *private_data);
11718 static enum bpf_perf_event_ret
11719 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11720 void **copy_mem, size_t *copy_size,
11721 bpf_perf_event_print_t fn, void *private_data)
11723 struct perf_event_mmap_page *header = mmap_mem;
11724 __u64 data_head = ring_buffer_read_head(header);
11725 __u64 data_tail = header->data_tail;
11726 void *base = ((__u8 *)header) + page_size;
11727 int ret = LIBBPF_PERF_EVENT_CONT;
11728 struct perf_event_header *ehdr;
11731 while (data_head != data_tail) {
11732 ehdr = base + (data_tail & (mmap_size - 1));
11733 ehdr_size = ehdr->size;
11735 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11736 void *copy_start = ehdr;
11737 size_t len_first = base + mmap_size - copy_start;
11738 size_t len_secnd = ehdr_size - len_first;
11740 if (*copy_size < ehdr_size) {
11742 *copy_mem = malloc(ehdr_size);
11745 ret = LIBBPF_PERF_EVENT_ERROR;
11748 *copy_size = ehdr_size;
11751 memcpy(*copy_mem, copy_start, len_first);
11752 memcpy(*copy_mem + len_first, base, len_secnd);
11756 ret = fn(ehdr, private_data);
11757 data_tail += ehdr_size;
11758 if (ret != LIBBPF_PERF_EVENT_CONT)
11762 ring_buffer_write_tail(header, data_tail);
11763 return libbpf_err(ret);
11766 struct perf_buffer;
11768 struct perf_buffer_params {
11769 struct perf_event_attr *attr;
11770 /* if event_cb is specified, it takes precendence */
11771 perf_buffer_event_fn event_cb;
11772 /* sample_cb and lost_cb are higher-level common-case callbacks */
11773 perf_buffer_sample_fn sample_cb;
11774 perf_buffer_lost_fn lost_cb;
11781 struct perf_cpu_buf {
11782 struct perf_buffer *pb;
11783 void *base; /* mmap()'ed memory */
11784 void *buf; /* for reconstructing segmented data */
11791 struct perf_buffer {
11792 perf_buffer_event_fn event_cb;
11793 perf_buffer_sample_fn sample_cb;
11794 perf_buffer_lost_fn lost_cb;
11795 void *ctx; /* passed into callbacks */
11799 struct perf_cpu_buf **cpu_bufs;
11800 struct epoll_event *events;
11801 int cpu_cnt; /* number of allocated CPU buffers */
11802 int epoll_fd; /* perf event FD */
11803 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11806 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11807 struct perf_cpu_buf *cpu_buf)
11811 if (cpu_buf->base &&
11812 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11813 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11814 if (cpu_buf->fd >= 0) {
11815 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11816 close(cpu_buf->fd);
11818 free(cpu_buf->buf);
11822 void perf_buffer__free(struct perf_buffer *pb)
11826 if (IS_ERR_OR_NULL(pb))
11828 if (pb->cpu_bufs) {
11829 for (i = 0; i < pb->cpu_cnt; i++) {
11830 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11835 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11836 perf_buffer__free_cpu_buf(pb, cpu_buf);
11838 free(pb->cpu_bufs);
11840 if (pb->epoll_fd >= 0)
11841 close(pb->epoll_fd);
11846 static struct perf_cpu_buf *
11847 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11848 int cpu, int map_key)
11850 struct perf_cpu_buf *cpu_buf;
11851 char msg[STRERR_BUFSIZE];
11854 cpu_buf = calloc(1, sizeof(*cpu_buf));
11856 return ERR_PTR(-ENOMEM);
11859 cpu_buf->cpu = cpu;
11860 cpu_buf->map_key = map_key;
11862 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11863 -1, PERF_FLAG_FD_CLOEXEC);
11864 if (cpu_buf->fd < 0) {
11866 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11867 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11871 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11872 PROT_READ | PROT_WRITE, MAP_SHARED,
11874 if (cpu_buf->base == MAP_FAILED) {
11875 cpu_buf->base = NULL;
11877 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11878 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11882 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11884 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11885 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11892 perf_buffer__free_cpu_buf(pb, cpu_buf);
11893 return (struct perf_cpu_buf *)ERR_PTR(err);
11896 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11897 struct perf_buffer_params *p);
11899 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11900 perf_buffer_sample_fn sample_cb,
11901 perf_buffer_lost_fn lost_cb,
11903 const struct perf_buffer_opts *opts)
11905 const size_t attr_sz = sizeof(struct perf_event_attr);
11906 struct perf_buffer_params p = {};
11907 struct perf_event_attr attr;
11908 __u32 sample_period;
11910 if (!OPTS_VALID(opts, perf_buffer_opts))
11911 return libbpf_err_ptr(-EINVAL);
11913 sample_period = OPTS_GET(opts, sample_period, 1);
11914 if (!sample_period)
11917 memset(&attr, 0, attr_sz);
11918 attr.size = attr_sz;
11919 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11920 attr.type = PERF_TYPE_SOFTWARE;
11921 attr.sample_type = PERF_SAMPLE_RAW;
11922 attr.sample_period = sample_period;
11923 attr.wakeup_events = sample_period;
11926 p.sample_cb = sample_cb;
11927 p.lost_cb = lost_cb;
11930 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11933 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11934 struct perf_event_attr *attr,
11935 perf_buffer_event_fn event_cb, void *ctx,
11936 const struct perf_buffer_raw_opts *opts)
11938 struct perf_buffer_params p = {};
11941 return libbpf_err_ptr(-EINVAL);
11943 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11944 return libbpf_err_ptr(-EINVAL);
11947 p.event_cb = event_cb;
11949 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11950 p.cpus = OPTS_GET(opts, cpus, NULL);
11951 p.map_keys = OPTS_GET(opts, map_keys, NULL);
11953 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11956 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11957 struct perf_buffer_params *p)
11959 const char *online_cpus_file = "/sys/devices/system/cpu/online";
11960 struct bpf_map_info map;
11961 char msg[STRERR_BUFSIZE];
11962 struct perf_buffer *pb;
11963 bool *online = NULL;
11964 __u32 map_info_len;
11967 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
11968 pr_warn("page count should be power of two, but is %zu\n",
11970 return ERR_PTR(-EINVAL);
11973 /* best-effort sanity checks */
11974 memset(&map, 0, sizeof(map));
11975 map_info_len = sizeof(map);
11976 err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
11979 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11980 * -EBADFD, -EFAULT, or -E2BIG on real error
11982 if (err != -EINVAL) {
11983 pr_warn("failed to get map info for map FD %d: %s\n",
11984 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11985 return ERR_PTR(err);
11987 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11990 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11991 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11993 return ERR_PTR(-EINVAL);
11997 pb = calloc(1, sizeof(*pb));
11999 return ERR_PTR(-ENOMEM);
12001 pb->event_cb = p->event_cb;
12002 pb->sample_cb = p->sample_cb;
12003 pb->lost_cb = p->lost_cb;
12006 pb->page_size = getpagesize();
12007 pb->mmap_size = pb->page_size * page_cnt;
12008 pb->map_fd = map_fd;
12010 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12011 if (pb->epoll_fd < 0) {
12013 pr_warn("failed to create epoll instance: %s\n",
12014 libbpf_strerror_r(err, msg, sizeof(msg)));
12018 if (p->cpu_cnt > 0) {
12019 pb->cpu_cnt = p->cpu_cnt;
12021 pb->cpu_cnt = libbpf_num_possible_cpus();
12022 if (pb->cpu_cnt < 0) {
12026 if (map.max_entries && map.max_entries < pb->cpu_cnt)
12027 pb->cpu_cnt = map.max_entries;
12030 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12033 pr_warn("failed to allocate events: out of memory\n");
12036 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12037 if (!pb->cpu_bufs) {
12039 pr_warn("failed to allocate buffers: out of memory\n");
12043 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12045 pr_warn("failed to get online CPU mask: %d\n", err);
12049 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12050 struct perf_cpu_buf *cpu_buf;
12053 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12054 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12056 /* in case user didn't explicitly requested particular CPUs to
12057 * be attached to, skip offline/not present CPUs
12059 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12062 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12063 if (IS_ERR(cpu_buf)) {
12064 err = PTR_ERR(cpu_buf);
12068 pb->cpu_bufs[j] = cpu_buf;
12070 err = bpf_map_update_elem(pb->map_fd, &map_key,
12074 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12075 cpu, map_key, cpu_buf->fd,
12076 libbpf_strerror_r(err, msg, sizeof(msg)));
12080 pb->events[j].events = EPOLLIN;
12081 pb->events[j].data.ptr = cpu_buf;
12082 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12083 &pb->events[j]) < 0) {
12085 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12087 libbpf_strerror_r(err, msg, sizeof(msg)));
12100 perf_buffer__free(pb);
12101 return ERR_PTR(err);
12104 struct perf_sample_raw {
12105 struct perf_event_header header;
12110 struct perf_sample_lost {
12111 struct perf_event_header header;
12114 uint64_t sample_id;
12117 static enum bpf_perf_event_ret
12118 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12120 struct perf_cpu_buf *cpu_buf = ctx;
12121 struct perf_buffer *pb = cpu_buf->pb;
12124 /* user wants full control over parsing perf event */
12126 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12129 case PERF_RECORD_SAMPLE: {
12130 struct perf_sample_raw *s = data;
12133 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12136 case PERF_RECORD_LOST: {
12137 struct perf_sample_lost *s = data;
12140 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12144 pr_warn("unknown perf sample type %d\n", e->type);
12145 return LIBBPF_PERF_EVENT_ERROR;
12147 return LIBBPF_PERF_EVENT_CONT;
12150 static int perf_buffer__process_records(struct perf_buffer *pb,
12151 struct perf_cpu_buf *cpu_buf)
12153 enum bpf_perf_event_ret ret;
12155 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12156 pb->page_size, &cpu_buf->buf,
12157 &cpu_buf->buf_size,
12158 perf_buffer__process_record, cpu_buf);
12159 if (ret != LIBBPF_PERF_EVENT_CONT)
12164 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12166 return pb->epoll_fd;
12169 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12173 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12177 for (i = 0; i < cnt; i++) {
12178 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12180 err = perf_buffer__process_records(pb, cpu_buf);
12182 pr_warn("error while processing records: %d\n", err);
12183 return libbpf_err(err);
12189 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12192 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12194 return pb->cpu_cnt;
12198 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12199 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12200 * select()/poll()/epoll() Linux syscalls.
12202 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12204 struct perf_cpu_buf *cpu_buf;
12206 if (buf_idx >= pb->cpu_cnt)
12207 return libbpf_err(-EINVAL);
12209 cpu_buf = pb->cpu_bufs[buf_idx];
12211 return libbpf_err(-ENOENT);
12213 return cpu_buf->fd;
12216 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12218 struct perf_cpu_buf *cpu_buf;
12220 if (buf_idx >= pb->cpu_cnt)
12221 return libbpf_err(-EINVAL);
12223 cpu_buf = pb->cpu_bufs[buf_idx];
12225 return libbpf_err(-ENOENT);
12227 *buf = cpu_buf->base;
12228 *buf_size = pb->mmap_size;
12233 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12234 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12235 * consume, do nothing and return success.
12240 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12242 struct perf_cpu_buf *cpu_buf;
12244 if (buf_idx >= pb->cpu_cnt)
12245 return libbpf_err(-EINVAL);
12247 cpu_buf = pb->cpu_bufs[buf_idx];
12249 return libbpf_err(-ENOENT);
12251 return perf_buffer__process_records(pb, cpu_buf);
12254 int perf_buffer__consume(struct perf_buffer *pb)
12258 for (i = 0; i < pb->cpu_cnt; i++) {
12259 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12264 err = perf_buffer__process_records(pb, cpu_buf);
12266 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12267 return libbpf_err(err);
12273 int bpf_program__set_attach_target(struct bpf_program *prog,
12274 int attach_prog_fd,
12275 const char *attach_func_name)
12277 int btf_obj_fd = 0, btf_id = 0, err;
12279 if (!prog || attach_prog_fd < 0)
12280 return libbpf_err(-EINVAL);
12282 if (prog->obj->loaded)
12283 return libbpf_err(-EINVAL);
12285 if (attach_prog_fd && !attach_func_name) {
12286 /* remember attach_prog_fd and let bpf_program__load() find
12287 * BTF ID during the program load
12289 prog->attach_prog_fd = attach_prog_fd;
12293 if (attach_prog_fd) {
12294 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12297 return libbpf_err(btf_id);
12299 if (!attach_func_name)
12300 return libbpf_err(-EINVAL);
12302 /* load btf_vmlinux, if not yet */
12303 err = bpf_object__load_vmlinux_btf(prog->obj, true);
12305 return libbpf_err(err);
12306 err = find_kernel_btf_id(prog->obj, attach_func_name,
12307 prog->expected_attach_type,
12308 &btf_obj_fd, &btf_id);
12310 return libbpf_err(err);
12313 prog->attach_btf_id = btf_id;
12314 prog->attach_btf_obj_fd = btf_obj_fd;
12315 prog->attach_prog_fd = attach_prog_fd;
12319 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12321 int err = 0, n, len, start, end = -1;
12327 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12329 if (*s == ',' || *s == '\n') {
12333 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12334 if (n <= 0 || n > 2) {
12335 pr_warn("Failed to get CPU range %s: %d\n", s, n);
12338 } else if (n == 1) {
12341 if (start < 0 || start > end) {
12342 pr_warn("Invalid CPU range [%d,%d] in %s\n",
12347 tmp = realloc(*mask, end + 1);
12353 memset(tmp + *mask_sz, 0, start - *mask_sz);
12354 memset(tmp + start, 1, end - start + 1);
12355 *mask_sz = end + 1;
12359 pr_warn("Empty CPU range\n");
12369 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12371 int fd, err = 0, len;
12374 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12377 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12380 len = read(fd, buf, sizeof(buf));
12383 err = len ? -errno : -EINVAL;
12384 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12387 if (len >= sizeof(buf)) {
12388 pr_warn("CPU mask is too big in file %s\n", fcpu);
12393 return parse_cpu_mask_str(buf, mask, mask_sz);
12396 int libbpf_num_possible_cpus(void)
12398 static const char *fcpu = "/sys/devices/system/cpu/possible";
12400 int err, n, i, tmp_cpus;
12403 tmp_cpus = READ_ONCE(cpus);
12407 err = parse_cpu_mask_file(fcpu, &mask, &n);
12409 return libbpf_err(err);
12412 for (i = 0; i < n; i++) {
12418 WRITE_ONCE(cpus, tmp_cpus);
12422 static int populate_skeleton_maps(const struct bpf_object *obj,
12423 struct bpf_map_skeleton *maps,
12428 for (i = 0; i < map_cnt; i++) {
12429 struct bpf_map **map = maps[i].map;
12430 const char *name = maps[i].name;
12431 void **mmaped = maps[i].mmaped;
12433 *map = bpf_object__find_map_by_name(obj, name);
12435 pr_warn("failed to find skeleton map '%s'\n", name);
12439 /* externs shouldn't be pre-setup from user code */
12440 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12441 *mmaped = (*map)->mmaped;
12446 static int populate_skeleton_progs(const struct bpf_object *obj,
12447 struct bpf_prog_skeleton *progs,
12452 for (i = 0; i < prog_cnt; i++) {
12453 struct bpf_program **prog = progs[i].prog;
12454 const char *name = progs[i].name;
12456 *prog = bpf_object__find_program_by_name(obj, name);
12458 pr_warn("failed to find skeleton program '%s'\n", name);
12465 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12466 const struct bpf_object_open_opts *opts)
12468 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12469 .object_name = s->name,
12471 struct bpf_object *obj;
12474 /* Attempt to preserve opts->object_name, unless overriden by user
12475 * explicitly. Overwriting object name for skeletons is discouraged,
12476 * as it breaks global data maps, because they contain object name
12477 * prefix as their own map name prefix. When skeleton is generated,
12478 * bpftool is making an assumption that this name will stay the same.
12481 memcpy(&skel_opts, opts, sizeof(*opts));
12482 if (!opts->object_name)
12483 skel_opts.object_name = s->name;
12486 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12487 err = libbpf_get_error(obj);
12489 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12491 return libbpf_err(err);
12495 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12497 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12498 return libbpf_err(err);
12501 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12503 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12504 return libbpf_err(err);
12510 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12512 int err, len, var_idx, i;
12513 const char *var_name;
12514 const struct bpf_map *map;
12517 const struct btf_type *map_type, *var_type;
12518 const struct bpf_var_skeleton *var_skel;
12519 struct btf_var_secinfo *var;
12522 return libbpf_err(-EINVAL);
12524 btf = bpf_object__btf(s->obj);
12526 pr_warn("subskeletons require BTF at runtime (object %s)\n",
12527 bpf_object__name(s->obj));
12528 return libbpf_err(-errno);
12531 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12533 pr_warn("failed to populate subskeleton maps: %d\n", err);
12534 return libbpf_err(err);
12537 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12539 pr_warn("failed to populate subskeleton maps: %d\n", err);
12540 return libbpf_err(err);
12543 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12544 var_skel = &s->vars[var_idx];
12545 map = *var_skel->map;
12546 map_type_id = bpf_map__btf_value_type_id(map);
12547 map_type = btf__type_by_id(btf, map_type_id);
12549 if (!btf_is_datasec(map_type)) {
12550 pr_warn("type for map '%1$s' is not a datasec: %2$s",
12551 bpf_map__name(map),
12552 __btf_kind_str(btf_kind(map_type)));
12553 return libbpf_err(-EINVAL);
12556 len = btf_vlen(map_type);
12557 var = btf_var_secinfos(map_type);
12558 for (i = 0; i < len; i++, var++) {
12559 var_type = btf__type_by_id(btf, var->type);
12560 var_name = btf__name_by_offset(btf, var_type->name_off);
12561 if (strcmp(var_name, var_skel->name) == 0) {
12562 *var_skel->addr = map->mmaped + var->offset;
12570 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12580 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12584 err = bpf_object__load(*s->obj);
12586 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12587 return libbpf_err(err);
12590 for (i = 0; i < s->map_cnt; i++) {
12591 struct bpf_map *map = *s->maps[i].map;
12592 size_t mmap_sz = bpf_map_mmap_sz(map);
12593 int prot, map_fd = bpf_map__fd(map);
12594 void **mmaped = s->maps[i].mmaped;
12599 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12604 if (map->def.map_flags & BPF_F_RDONLY_PROG)
12607 prot = PROT_READ | PROT_WRITE;
12609 /* Remap anonymous mmap()-ed "map initialization image" as
12610 * a BPF map-backed mmap()-ed memory, but preserving the same
12611 * memory address. This will cause kernel to change process'
12612 * page table to point to a different piece of kernel memory,
12613 * but from userspace point of view memory address (and its
12614 * contents, being identical at this point) will stay the
12615 * same. This mapping will be released by bpf_object__close()
12616 * as per normal clean up procedure, so we don't need to worry
12617 * about it from skeleton's clean up perspective.
12619 *mmaped = mmap(map->mmaped, mmap_sz, prot,
12620 MAP_SHARED | MAP_FIXED, map_fd, 0);
12621 if (*mmaped == MAP_FAILED) {
12624 pr_warn("failed to re-mmap() map '%s': %d\n",
12625 bpf_map__name(map), err);
12626 return libbpf_err(err);
12633 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12637 for (i = 0; i < s->prog_cnt; i++) {
12638 struct bpf_program *prog = *s->progs[i].prog;
12639 struct bpf_link **link = s->progs[i].link;
12641 if (!prog->autoload || !prog->autoattach)
12644 /* auto-attaching not supported for this program */
12645 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12648 /* if user already set the link manually, don't attempt auto-attach */
12652 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12654 pr_warn("prog '%s': failed to auto-attach: %d\n",
12655 bpf_program__name(prog), err);
12656 return libbpf_err(err);
12659 /* It's possible that for some SEC() definitions auto-attach
12660 * is supported in some cases (e.g., if definition completely
12661 * specifies target information), but is not in other cases.
12662 * SEC("uprobe") is one such case. If user specified target
12663 * binary and function name, such BPF program can be
12664 * auto-attached. But if not, it shouldn't trigger skeleton's
12665 * attach to fail. It should just be skipped.
12666 * attach_fn signals such case with returning 0 (no error) and
12667 * setting link to NULL.
12674 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12678 for (i = 0; i < s->prog_cnt; i++) {
12679 struct bpf_link **link = s->progs[i].link;
12681 bpf_link__destroy(*link);
12686 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12692 bpf_object__detach_skeleton(s);
12694 bpf_object__close(*s->obj);