1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
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_UNIX_CONNECT] = "cgroup_unix_connect",
86 [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
87 [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
88 [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
89 [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
90 [BPF_CGROUP_UNIX_GETPEERNAME] = "cgroup_unix_getpeername",
91 [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
92 [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
93 [BPF_CGROUP_UNIX_GETSOCKNAME] = "cgroup_unix_getsockname",
94 [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
95 [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
96 [BPF_CGROUP_UNIX_SENDMSG] = "cgroup_unix_sendmsg",
97 [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
98 [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
99 [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
100 [BPF_CGROUP_UNIX_RECVMSG] = "cgroup_unix_recvmsg",
101 [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
102 [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
103 [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
104 [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
105 [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
106 [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
107 [BPF_LIRC_MODE2] = "lirc_mode2",
108 [BPF_FLOW_DISSECTOR] = "flow_dissector",
109 [BPF_TRACE_RAW_TP] = "trace_raw_tp",
110 [BPF_TRACE_FENTRY] = "trace_fentry",
111 [BPF_TRACE_FEXIT] = "trace_fexit",
112 [BPF_MODIFY_RETURN] = "modify_return",
113 [BPF_LSM_MAC] = "lsm_mac",
114 [BPF_LSM_CGROUP] = "lsm_cgroup",
115 [BPF_SK_LOOKUP] = "sk_lookup",
116 [BPF_TRACE_ITER] = "trace_iter",
117 [BPF_XDP_DEVMAP] = "xdp_devmap",
118 [BPF_XDP_CPUMAP] = "xdp_cpumap",
120 [BPF_SK_REUSEPORT_SELECT] = "sk_reuseport_select",
121 [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE] = "sk_reuseport_select_or_migrate",
122 [BPF_PERF_EVENT] = "perf_event",
123 [BPF_TRACE_KPROBE_MULTI] = "trace_kprobe_multi",
124 [BPF_STRUCT_OPS] = "struct_ops",
125 [BPF_NETFILTER] = "netfilter",
126 [BPF_TCX_INGRESS] = "tcx_ingress",
127 [BPF_TCX_EGRESS] = "tcx_egress",
128 [BPF_TRACE_UPROBE_MULTI] = "trace_uprobe_multi",
129 [BPF_NETKIT_PRIMARY] = "netkit_primary",
130 [BPF_NETKIT_PEER] = "netkit_peer",
133 static const char * const link_type_name[] = {
134 [BPF_LINK_TYPE_UNSPEC] = "unspec",
135 [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
136 [BPF_LINK_TYPE_TRACING] = "tracing",
137 [BPF_LINK_TYPE_CGROUP] = "cgroup",
138 [BPF_LINK_TYPE_ITER] = "iter",
139 [BPF_LINK_TYPE_NETNS] = "netns",
140 [BPF_LINK_TYPE_XDP] = "xdp",
141 [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
142 [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
143 [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
144 [BPF_LINK_TYPE_NETFILTER] = "netfilter",
145 [BPF_LINK_TYPE_TCX] = "tcx",
146 [BPF_LINK_TYPE_UPROBE_MULTI] = "uprobe_multi",
147 [BPF_LINK_TYPE_NETKIT] = "netkit",
150 static const char * const map_type_name[] = {
151 [BPF_MAP_TYPE_UNSPEC] = "unspec",
152 [BPF_MAP_TYPE_HASH] = "hash",
153 [BPF_MAP_TYPE_ARRAY] = "array",
154 [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
155 [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
156 [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
157 [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
158 [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
159 [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
160 [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
161 [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
162 [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
163 [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
164 [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
165 [BPF_MAP_TYPE_DEVMAP] = "devmap",
166 [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
167 [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
168 [BPF_MAP_TYPE_CPUMAP] = "cpumap",
169 [BPF_MAP_TYPE_XSKMAP] = "xskmap",
170 [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
171 [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
172 [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
173 [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
174 [BPF_MAP_TYPE_QUEUE] = "queue",
175 [BPF_MAP_TYPE_STACK] = "stack",
176 [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
177 [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
178 [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
179 [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
180 [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
181 [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
182 [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
183 [BPF_MAP_TYPE_CGRP_STORAGE] = "cgrp_storage",
186 static const char * const prog_type_name[] = {
187 [BPF_PROG_TYPE_UNSPEC] = "unspec",
188 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
189 [BPF_PROG_TYPE_KPROBE] = "kprobe",
190 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
191 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
192 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
193 [BPF_PROG_TYPE_XDP] = "xdp",
194 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
195 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
196 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
197 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
198 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
199 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
200 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
201 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
202 [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
203 [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
204 [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
205 [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
206 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
207 [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
208 [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
209 [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
210 [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
211 [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
212 [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
213 [BPF_PROG_TYPE_TRACING] = "tracing",
214 [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
215 [BPF_PROG_TYPE_EXT] = "ext",
216 [BPF_PROG_TYPE_LSM] = "lsm",
217 [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
218 [BPF_PROG_TYPE_SYSCALL] = "syscall",
219 [BPF_PROG_TYPE_NETFILTER] = "netfilter",
222 static int __base_pr(enum libbpf_print_level level, const char *format,
225 if (level == LIBBPF_DEBUG)
228 return vfprintf(stderr, format, args);
231 static libbpf_print_fn_t __libbpf_pr = __base_pr;
233 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
235 libbpf_print_fn_t old_print_fn;
237 old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
243 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
247 libbpf_print_fn_t print_fn;
249 print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
255 va_start(args, format);
256 __libbpf_pr(level, format, args);
262 static void pr_perm_msg(int err)
267 if (err != -EPERM || geteuid() != 0)
270 err = getrlimit(RLIMIT_MEMLOCK, &limit);
274 if (limit.rlim_cur == RLIM_INFINITY)
277 if (limit.rlim_cur < 1024)
278 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
279 else if (limit.rlim_cur < 1024*1024)
280 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
282 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
284 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
288 #define STRERR_BUFSIZE 128
290 /* Copied from tools/perf/util/util.h */
292 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
296 # define zclose(fd) ({ \
299 ___err = close((fd)); \
304 static inline __u64 ptr_to_u64(const void *ptr)
306 return (__u64) (unsigned long) ptr;
309 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
311 /* as of v1.0 libbpf_set_strict_mode() is a no-op */
315 __u32 libbpf_major_version(void)
317 return LIBBPF_MAJOR_VERSION;
320 __u32 libbpf_minor_version(void)
322 return LIBBPF_MINOR_VERSION;
325 const char *libbpf_version_string(void)
329 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
345 enum reloc_type type;
348 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
357 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
360 /* expected_attach_type is optional, if kernel doesn't support that */
361 SEC_EXP_ATTACH_OPT = 1,
362 /* legacy, only used by libbpf_get_type_names() and
363 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
364 * This used to be associated with cgroup (and few other) BPF programs
365 * that were attachable through BPF_PROG_ATTACH command. Pretty
366 * meaningless nowadays, though.
369 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
370 /* attachment target is specified through BTF ID in either kernel or
371 * other BPF program's BTF object
374 /* BPF program type allows sleeping/blocking in kernel */
376 /* BPF program support non-linear XDP buffer */
378 /* Setup proper attach type for usdt probes. */
384 enum bpf_prog_type prog_type;
385 enum bpf_attach_type expected_attach_type;
389 libbpf_prog_setup_fn_t prog_setup_fn;
390 libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
391 libbpf_prog_attach_fn_t prog_attach_fn;
395 * bpf_prog should be a better name but it has been used in
402 const struct bpf_sec_def *sec_def;
403 /* this program's instruction offset (in number of instructions)
404 * within its containing ELF section
407 /* number of original instructions in ELF section belonging to this
408 * program, not taking into account subprogram instructions possible
409 * appended later during relocation
412 /* Offset (in number of instructions) of the start of instruction
413 * belonging to this BPF program within its containing main BPF
414 * program. For the entry-point (main) BPF program, this is always
415 * zero. For a sub-program, this gets reset before each of main BPF
416 * programs are processed and relocated and is used to determined
417 * whether sub-program was already appended to the main program, and
418 * if yes, at which instruction offset.
422 /* instructions that belong to BPF program; insns[0] is located at
423 * sec_insn_off instruction within its ELF section in ELF file, so
424 * when mapping ELF file instruction index to the local instruction,
425 * one needs to subtract sec_insn_off; and vice versa.
427 struct bpf_insn *insns;
428 /* actual number of instruction in this BPF program's image; for
429 * entry-point BPF programs this includes the size of main program
430 * itself plus all the used sub-programs, appended at the end
434 struct reloc_desc *reloc_desc;
437 /* BPF verifier log settings */
442 struct bpf_object *obj;
448 bool mark_btf_static;
449 enum bpf_prog_type type;
450 enum bpf_attach_type expected_attach_type;
451 int exception_cb_idx;
454 __u32 attach_btf_obj_fd;
456 __u32 attach_prog_fd;
459 __u32 func_info_rec_size;
463 __u32 line_info_rec_size;
468 struct bpf_struct_ops {
470 const struct btf_type *type;
471 struct bpf_program **progs;
472 __u32 *kern_func_off;
473 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
475 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
476 * btf_vmlinux's format.
477 * struct bpf_struct_ops_tcp_congestion_ops {
478 * [... some other kernel fields ...]
479 * struct tcp_congestion_ops data;
481 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
482 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
489 #define DATA_SEC ".data"
490 #define BSS_SEC ".bss"
491 #define RODATA_SEC ".rodata"
492 #define KCONFIG_SEC ".kconfig"
493 #define KSYMS_SEC ".ksyms"
494 #define STRUCT_OPS_SEC ".struct_ops"
495 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
497 enum libbpf_map_type {
507 unsigned int key_size;
508 unsigned int value_size;
509 unsigned int max_entries;
510 unsigned int map_flags;
514 struct bpf_object *obj;
516 /* real_name is defined for special internal maps (.rodata*,
517 * .data*, .bss, .kconfig) and preserves their original ELF section
518 * name. This is important to be able to find corresponding BTF
519 * DATASEC information.
527 struct bpf_map_def def;
530 __u32 btf_key_type_id;
531 __u32 btf_value_type_id;
532 __u32 btf_vmlinux_value_type_id;
533 enum libbpf_map_type libbpf_type;
535 struct bpf_struct_ops *st_ops;
536 struct bpf_map *inner_map;
562 enum extern_type type;
579 unsigned long long addr;
581 /* target btf_id of the corresponding kernel var. */
582 int kernel_btf_obj_fd;
585 /* local btf_id of the ksym extern's type. */
587 /* BTF fd index to be patched in for insn->off, this is
588 * 0 for vmlinux BTF, index in obj->fd_array for module
612 struct elf_sec_desc {
613 enum sec_type sec_type;
625 Elf_Data *st_ops_data;
626 Elf_Data *st_ops_link_data;
627 size_t shstrndx; /* section index for section name strings */
629 struct elf_sec_desc *secs;
632 __u32 btf_maps_sec_btf_id;
636 int st_ops_link_shndx;
642 char name[BPF_OBJ_NAME_LEN];
646 struct bpf_program *programs;
648 struct bpf_map *maps;
653 struct extern_desc *externs;
661 struct bpf_gen *gen_loader;
663 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
664 struct elf_state efile;
667 struct btf_ext *btf_ext;
669 /* Parse and load BTF vmlinux if any of the programs in the object need
672 struct btf *btf_vmlinux;
673 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
674 * override for vmlinux BTF.
676 char *btf_custom_path;
677 /* vmlinux BTF override for CO-RE relocations */
678 struct btf *btf_vmlinux_override;
679 /* Lazily initialized kernel module BTFs */
680 struct module_btf *btf_modules;
681 bool btf_modules_loaded;
682 size_t btf_module_cnt;
683 size_t btf_module_cap;
685 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
694 struct usdt_manager *usdt_man;
699 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
700 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
701 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
702 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
703 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
704 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
705 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
706 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
707 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
709 void bpf_program__unload(struct bpf_program *prog)
716 zfree(&prog->func_info);
717 zfree(&prog->line_info);
720 static void bpf_program__exit(struct bpf_program *prog)
725 bpf_program__unload(prog);
727 zfree(&prog->sec_name);
729 zfree(&prog->reloc_desc);
736 static bool insn_is_subprog_call(const struct bpf_insn *insn)
738 return BPF_CLASS(insn->code) == BPF_JMP &&
739 BPF_OP(insn->code) == BPF_CALL &&
740 BPF_SRC(insn->code) == BPF_K &&
741 insn->src_reg == BPF_PSEUDO_CALL &&
742 insn->dst_reg == 0 &&
746 static bool is_call_insn(const struct bpf_insn *insn)
748 return insn->code == (BPF_JMP | BPF_CALL);
751 static bool insn_is_pseudo_func(struct bpf_insn *insn)
753 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
757 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
758 const char *name, size_t sec_idx, const char *sec_name,
759 size_t sec_off, void *insn_data, size_t insn_data_sz)
761 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
762 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
763 sec_name, name, sec_off, insn_data_sz);
767 memset(prog, 0, sizeof(*prog));
770 prog->sec_idx = sec_idx;
771 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
772 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
773 /* insns_cnt can later be increased by appending used subprograms */
774 prog->insns_cnt = prog->sec_insn_cnt;
776 prog->type = BPF_PROG_TYPE_UNSPEC;
778 prog->exception_cb_idx = -1;
780 /* libbpf's convention for SEC("?abc...") is that it's just like
781 * SEC("abc...") but the corresponding bpf_program starts out with
782 * autoload set to false.
784 if (sec_name[0] == '?') {
785 prog->autoload = false;
786 /* from now on forget there was ? in section name */
789 prog->autoload = true;
792 prog->autoattach = true;
794 /* inherit object's log_level */
795 prog->log_level = obj->log_level;
797 prog->sec_name = strdup(sec_name);
801 prog->name = strdup(name);
805 prog->insns = malloc(insn_data_sz);
808 memcpy(prog->insns, insn_data, insn_data_sz);
812 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
813 bpf_program__exit(prog);
818 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
819 const char *sec_name, int sec_idx)
821 Elf_Data *symbols = obj->efile.symbols;
822 struct bpf_program *prog, *progs;
823 void *data = sec_data->d_buf;
824 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
825 int nr_progs, err, i;
829 progs = obj->programs;
830 nr_progs = obj->nr_programs;
831 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
833 for (i = 0; i < nr_syms; i++) {
834 sym = elf_sym_by_idx(obj, i);
836 if (sym->st_shndx != sec_idx)
838 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
841 prog_sz = sym->st_size;
842 sec_off = sym->st_value;
844 name = elf_sym_str(obj, sym->st_name);
846 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
848 return -LIBBPF_ERRNO__FORMAT;
851 if (sec_off + prog_sz > sec_sz) {
852 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
854 return -LIBBPF_ERRNO__FORMAT;
857 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
858 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
862 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
863 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
865 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
868 * In this case the original obj->programs
869 * is still valid, so don't need special treat for
870 * bpf_close_object().
872 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
876 obj->programs = progs;
878 prog = &progs[nr_progs];
880 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
881 sec_off, data + sec_off, prog_sz);
885 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
886 prog->sym_global = true;
888 /* if function is a global/weak symbol, but has restricted
889 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
890 * as static to enable more permissive BPF verification mode
891 * with more outside context available to BPF verifier
893 if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
894 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
895 prog->mark_btf_static = true;
898 obj->nr_programs = nr_progs;
904 static const struct btf_member *
905 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
907 struct btf_member *m;
910 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
911 if (btf_member_bit_offset(t, i) == bit_offset)
918 static const struct btf_member *
919 find_member_by_name(const struct btf *btf, const struct btf_type *t,
922 struct btf_member *m;
925 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
926 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
933 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
934 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
935 const char *name, __u32 kind);
938 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
939 const struct btf_type **type, __u32 *type_id,
940 const struct btf_type **vtype, __u32 *vtype_id,
941 const struct btf_member **data_member)
943 const struct btf_type *kern_type, *kern_vtype;
944 const struct btf_member *kern_data_member;
945 __s32 kern_vtype_id, kern_type_id;
948 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
949 if (kern_type_id < 0) {
950 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
954 kern_type = btf__type_by_id(btf, kern_type_id);
956 /* Find the corresponding "map_value" type that will be used
957 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
958 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
961 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
962 tname, BTF_KIND_STRUCT);
963 if (kern_vtype_id < 0) {
964 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
965 STRUCT_OPS_VALUE_PREFIX, tname);
966 return kern_vtype_id;
968 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
970 /* Find "struct tcp_congestion_ops" from
971 * struct bpf_struct_ops_tcp_congestion_ops {
973 * struct tcp_congestion_ops data;
976 kern_data_member = btf_members(kern_vtype);
977 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
978 if (kern_data_member->type == kern_type_id)
981 if (i == btf_vlen(kern_vtype)) {
982 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
983 tname, STRUCT_OPS_VALUE_PREFIX, tname);
988 *type_id = kern_type_id;
990 *vtype_id = kern_vtype_id;
991 *data_member = kern_data_member;
996 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
998 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1001 /* Init the map's fields that depend on kern_btf */
1002 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1003 const struct btf *btf,
1004 const struct btf *kern_btf)
1006 const struct btf_member *member, *kern_member, *kern_data_member;
1007 const struct btf_type *type, *kern_type, *kern_vtype;
1008 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1009 struct bpf_struct_ops *st_ops;
1010 void *data, *kern_data;
1014 st_ops = map->st_ops;
1015 type = st_ops->type;
1016 tname = st_ops->tname;
1017 err = find_struct_ops_kern_types(kern_btf, tname,
1018 &kern_type, &kern_type_id,
1019 &kern_vtype, &kern_vtype_id,
1024 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1025 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1027 map->def.value_size = kern_vtype->size;
1028 map->btf_vmlinux_value_type_id = kern_vtype_id;
1030 st_ops->kern_vdata = calloc(1, kern_vtype->size);
1031 if (!st_ops->kern_vdata)
1034 data = st_ops->data;
1035 kern_data_off = kern_data_member->offset / 8;
1036 kern_data = st_ops->kern_vdata + kern_data_off;
1038 member = btf_members(type);
1039 for (i = 0; i < btf_vlen(type); i++, member++) {
1040 const struct btf_type *mtype, *kern_mtype;
1041 __u32 mtype_id, kern_mtype_id;
1042 void *mdata, *kern_mdata;
1043 __s64 msize, kern_msize;
1044 __u32 moff, kern_moff;
1045 __u32 kern_member_idx;
1048 mname = btf__name_by_offset(btf, member->name_off);
1049 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1051 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1056 kern_member_idx = kern_member - btf_members(kern_type);
1057 if (btf_member_bitfield_size(type, i) ||
1058 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1059 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1064 moff = member->offset / 8;
1065 kern_moff = kern_member->offset / 8;
1067 mdata = data + moff;
1068 kern_mdata = kern_data + kern_moff;
1070 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1071 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1073 if (BTF_INFO_KIND(mtype->info) !=
1074 BTF_INFO_KIND(kern_mtype->info)) {
1075 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1076 map->name, mname, BTF_INFO_KIND(mtype->info),
1077 BTF_INFO_KIND(kern_mtype->info));
1081 if (btf_is_ptr(mtype)) {
1082 struct bpf_program *prog;
1084 prog = st_ops->progs[i];
1088 kern_mtype = skip_mods_and_typedefs(kern_btf,
1092 /* mtype->type must be a func_proto which was
1093 * guaranteed in bpf_object__collect_st_ops_relos(),
1094 * so only check kern_mtype for func_proto here.
1096 if (!btf_is_func_proto(kern_mtype)) {
1097 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1102 prog->attach_btf_id = kern_type_id;
1103 prog->expected_attach_type = kern_member_idx;
1105 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1107 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1108 map->name, mname, prog->name, moff,
1114 msize = btf__resolve_size(btf, mtype_id);
1115 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1116 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1117 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1118 map->name, mname, (ssize_t)msize,
1119 (ssize_t)kern_msize);
1123 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1124 map->name, mname, (unsigned int)msize,
1126 memcpy(kern_mdata, mdata, msize);
1132 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1134 struct bpf_map *map;
1138 for (i = 0; i < obj->nr_maps; i++) {
1139 map = &obj->maps[i];
1141 if (!bpf_map__is_struct_ops(map))
1144 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1153 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1154 int shndx, Elf_Data *data, __u32 map_flags)
1156 const struct btf_type *type, *datasec;
1157 const struct btf_var_secinfo *vsi;
1158 struct bpf_struct_ops *st_ops;
1159 const char *tname, *var_name;
1160 __s32 type_id, datasec_id;
1161 const struct btf *btf;
1162 struct bpf_map *map;
1169 datasec_id = btf__find_by_name_kind(btf, sec_name,
1171 if (datasec_id < 0) {
1172 pr_warn("struct_ops init: DATASEC %s not found\n",
1177 datasec = btf__type_by_id(btf, datasec_id);
1178 vsi = btf_var_secinfos(datasec);
1179 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1180 type = btf__type_by_id(obj->btf, vsi->type);
1181 var_name = btf__name_by_offset(obj->btf, type->name_off);
1183 type_id = btf__resolve_type(obj->btf, vsi->type);
1185 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1186 vsi->type, sec_name);
1190 type = btf__type_by_id(obj->btf, type_id);
1191 tname = btf__name_by_offset(obj->btf, type->name_off);
1193 pr_warn("struct_ops init: anonymous type is not supported\n");
1196 if (!btf_is_struct(type)) {
1197 pr_warn("struct_ops init: %s is not a struct\n", tname);
1201 map = bpf_object__add_map(obj);
1203 return PTR_ERR(map);
1205 map->sec_idx = shndx;
1206 map->sec_offset = vsi->offset;
1207 map->name = strdup(var_name);
1211 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1212 map->def.key_size = sizeof(int);
1213 map->def.value_size = type->size;
1214 map->def.max_entries = 1;
1215 map->def.map_flags = map_flags;
1217 map->st_ops = calloc(1, sizeof(*map->st_ops));
1220 st_ops = map->st_ops;
1221 st_ops->data = malloc(type->size);
1222 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1223 st_ops->kern_func_off = malloc(btf_vlen(type) *
1224 sizeof(*st_ops->kern_func_off));
1225 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1228 if (vsi->offset + type->size > data->d_size) {
1229 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1230 var_name, sec_name);
1234 memcpy(st_ops->data,
1235 data->d_buf + vsi->offset,
1237 st_ops->tname = tname;
1238 st_ops->type = type;
1239 st_ops->type_id = type_id;
1241 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1242 tname, type_id, var_name, vsi->offset);
1248 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1252 err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1253 obj->efile.st_ops_data, 0);
1254 err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1255 obj->efile.st_ops_link_shndx,
1256 obj->efile.st_ops_link_data,
1261 static struct bpf_object *bpf_object__new(const char *path,
1262 const void *obj_buf,
1264 const char *obj_name)
1266 struct bpf_object *obj;
1269 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1271 pr_warn("alloc memory failed for %s\n", path);
1272 return ERR_PTR(-ENOMEM);
1275 strcpy(obj->path, path);
1277 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1279 /* Using basename() GNU version which doesn't modify arg. */
1280 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1281 end = strchr(obj->name, '.');
1288 * Caller of this function should also call
1289 * bpf_object__elf_finish() after data collection to return
1290 * obj_buf to user. If not, we should duplicate the buffer to
1291 * avoid user freeing them before elf finish.
1293 obj->efile.obj_buf = obj_buf;
1294 obj->efile.obj_buf_sz = obj_buf_sz;
1295 obj->efile.btf_maps_shndx = -1;
1296 obj->efile.st_ops_shndx = -1;
1297 obj->efile.st_ops_link_shndx = -1;
1298 obj->kconfig_map_idx = -1;
1300 obj->kern_version = get_kernel_version();
1301 obj->loaded = false;
1306 static void bpf_object__elf_finish(struct bpf_object *obj)
1308 if (!obj->efile.elf)
1311 elf_end(obj->efile.elf);
1312 obj->efile.elf = NULL;
1313 obj->efile.symbols = NULL;
1314 obj->efile.st_ops_data = NULL;
1315 obj->efile.st_ops_link_data = NULL;
1317 zfree(&obj->efile.secs);
1318 obj->efile.sec_cnt = 0;
1319 zclose(obj->efile.fd);
1320 obj->efile.obj_buf = NULL;
1321 obj->efile.obj_buf_sz = 0;
1324 static int bpf_object__elf_init(struct bpf_object *obj)
1330 if (obj->efile.elf) {
1331 pr_warn("elf: init internal error\n");
1332 return -LIBBPF_ERRNO__LIBELF;
1335 if (obj->efile.obj_buf_sz > 0) {
1336 /* obj_buf should have been validated by bpf_object__open_mem(). */
1337 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1339 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1340 if (obj->efile.fd < 0) {
1341 char errmsg[STRERR_BUFSIZE], *cp;
1344 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1345 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1349 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1353 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1354 err = -LIBBPF_ERRNO__LIBELF;
1358 obj->efile.elf = elf;
1360 if (elf_kind(elf) != ELF_K_ELF) {
1361 err = -LIBBPF_ERRNO__FORMAT;
1362 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1366 if (gelf_getclass(elf) != ELFCLASS64) {
1367 err = -LIBBPF_ERRNO__FORMAT;
1368 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1372 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1373 if (!obj->efile.ehdr) {
1374 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1375 err = -LIBBPF_ERRNO__FORMAT;
1379 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1380 pr_warn("elf: failed to get section names section index for %s: %s\n",
1381 obj->path, elf_errmsg(-1));
1382 err = -LIBBPF_ERRNO__FORMAT;
1386 /* ELF is corrupted/truncated, avoid calling elf_strptr. */
1387 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1388 pr_warn("elf: failed to get section names strings from %s: %s\n",
1389 obj->path, elf_errmsg(-1));
1390 err = -LIBBPF_ERRNO__FORMAT;
1394 /* Old LLVM set e_machine to EM_NONE */
1395 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1396 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1397 err = -LIBBPF_ERRNO__FORMAT;
1403 bpf_object__elf_finish(obj);
1407 static int bpf_object__check_endianness(struct bpf_object *obj)
1409 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1410 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1412 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1413 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1416 # error "Unrecognized __BYTE_ORDER__"
1418 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1419 return -LIBBPF_ERRNO__ENDIAN;
1423 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1426 pr_warn("invalid license section in %s\n", obj->path);
1427 return -LIBBPF_ERRNO__FORMAT;
1429 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1430 * go over allowed ELF data section buffer
1432 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1433 pr_debug("license of %s is %s\n", obj->path, obj->license);
1438 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1442 if (!data || size != sizeof(kver)) {
1443 pr_warn("invalid kver section in %s\n", obj->path);
1444 return -LIBBPF_ERRNO__FORMAT;
1446 memcpy(&kver, data, sizeof(kver));
1447 obj->kern_version = kver;
1448 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1452 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1454 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1455 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1460 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1468 scn = elf_sec_by_name(obj, name);
1469 data = elf_sec_data(obj, scn);
1471 *size = data->d_size;
1472 return 0; /* found it */
1478 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1480 Elf_Data *symbols = obj->efile.symbols;
1484 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1485 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1487 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1490 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1491 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1494 sname = elf_sym_str(obj, sym->st_name);
1496 pr_warn("failed to get sym name string for var %s\n", name);
1497 return ERR_PTR(-EIO);
1499 if (strcmp(name, sname) == 0)
1503 return ERR_PTR(-ENOENT);
1506 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1508 struct bpf_map *map;
1511 err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1512 sizeof(*obj->maps), obj->nr_maps + 1);
1514 return ERR_PTR(err);
1516 map = &obj->maps[obj->nr_maps++];
1519 map->inner_map_fd = -1;
1520 map->autocreate = true;
1525 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1527 const long page_sz = sysconf(_SC_PAGE_SIZE);
1530 map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1531 map_sz = roundup(map_sz, page_sz);
1535 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1542 if (old_sz == new_sz)
1545 mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1546 if (mmaped == MAP_FAILED)
1549 memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1550 munmap(map->mmaped, old_sz);
1551 map->mmaped = mmaped;
1555 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1557 char map_name[BPF_OBJ_NAME_LEN], *p;
1558 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1560 /* This is one of the more confusing parts of libbpf for various
1561 * reasons, some of which are historical. The original idea for naming
1562 * internal names was to include as much of BPF object name prefix as
1563 * possible, so that it can be distinguished from similar internal
1564 * maps of a different BPF object.
1565 * As an example, let's say we have bpf_object named 'my_object_name'
1566 * and internal map corresponding to '.rodata' ELF section. The final
1567 * map name advertised to user and to the kernel will be
1568 * 'my_objec.rodata', taking first 8 characters of object name and
1569 * entire 7 characters of '.rodata'.
1570 * Somewhat confusingly, if internal map ELF section name is shorter
1571 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1572 * for the suffix, even though we only have 4 actual characters, and
1573 * resulting map will be called 'my_objec.bss', not even using all 15
1574 * characters allowed by the kernel. Oh well, at least the truncated
1575 * object name is somewhat consistent in this case. But if the map
1576 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1577 * (8 chars) and thus will be left with only first 7 characters of the
1578 * object name ('my_obje'). Happy guessing, user, that the final map
1579 * name will be "my_obje.kconfig".
1580 * Now, with libbpf starting to support arbitrarily named .rodata.*
1581 * and .data.* data sections, it's possible that ELF section name is
1582 * longer than allowed 15 chars, so we now need to be careful to take
1583 * only up to 15 first characters of ELF name, taking no BPF object
1584 * name characters at all. So '.rodata.abracadabra' will result in
1585 * '.rodata.abracad' kernel and user-visible name.
1586 * We need to keep this convoluted logic intact for .data, .bss and
1587 * .rodata maps, but for new custom .data.custom and .rodata.custom
1588 * maps we use their ELF names as is, not prepending bpf_object name
1589 * in front. We still need to truncate them to 15 characters for the
1590 * kernel. Full name can be recovered for such maps by using DATASEC
1591 * BTF type associated with such map's value type, though.
1593 if (sfx_len >= BPF_OBJ_NAME_LEN)
1594 sfx_len = BPF_OBJ_NAME_LEN - 1;
1596 /* if there are two or more dots in map name, it's a custom dot map */
1597 if (strchr(real_name + 1, '.') != NULL)
1600 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1602 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1603 sfx_len, real_name);
1605 /* sanitise map name to characters allowed by kernel */
1606 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1607 if (!isalnum(*p) && *p != '_' && *p != '.')
1610 return strdup(map_name);
1614 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1616 /* Internal BPF map is mmap()'able only if at least one of corresponding
1617 * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1618 * variable and it's not marked as __hidden (which turns it into, effectively,
1619 * a STATIC variable).
1621 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1623 const struct btf_type *t, *vt;
1624 struct btf_var_secinfo *vsi;
1627 if (!map->btf_value_type_id)
1630 t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1631 if (!btf_is_datasec(t))
1634 vsi = btf_var_secinfos(t);
1635 for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1636 vt = btf__type_by_id(obj->btf, vsi->type);
1637 if (!btf_is_var(vt))
1640 if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1648 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1649 const char *real_name, int sec_idx, void *data, size_t data_sz)
1651 struct bpf_map_def *def;
1652 struct bpf_map *map;
1656 map = bpf_object__add_map(obj);
1658 return PTR_ERR(map);
1660 map->libbpf_type = type;
1661 map->sec_idx = sec_idx;
1662 map->sec_offset = 0;
1663 map->real_name = strdup(real_name);
1664 map->name = internal_map_name(obj, real_name);
1665 if (!map->real_name || !map->name) {
1666 zfree(&map->real_name);
1672 def->type = BPF_MAP_TYPE_ARRAY;
1673 def->key_size = sizeof(int);
1674 def->value_size = data_sz;
1675 def->max_entries = 1;
1676 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1677 ? BPF_F_RDONLY_PROG : 0;
1679 /* failures are fine because of maps like .rodata.str1.1 */
1680 (void) map_fill_btf_type_info(obj, map);
1682 if (map_is_mmapable(obj, map))
1683 def->map_flags |= BPF_F_MMAPABLE;
1685 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1686 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1688 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1689 map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1690 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1691 if (map->mmaped == MAP_FAILED) {
1694 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1696 zfree(&map->real_name);
1702 memcpy(map->mmaped, data, data_sz);
1704 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1708 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1710 struct elf_sec_desc *sec_desc;
1711 const char *sec_name;
1712 int err = 0, sec_idx;
1715 * Populate obj->maps with libbpf internal maps.
1717 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1718 sec_desc = &obj->efile.secs[sec_idx];
1720 /* Skip recognized sections with size 0. */
1721 if (!sec_desc->data || sec_desc->data->d_size == 0)
1724 switch (sec_desc->sec_type) {
1726 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1729 sec_desc->data->d_buf,
1730 sec_desc->data->d_size);
1733 obj->has_rodata = true;
1734 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1735 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1737 sec_desc->data->d_buf,
1738 sec_desc->data->d_size);
1741 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1742 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1745 sec_desc->data->d_size);
1758 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1763 for (i = 0; i < obj->nr_extern; i++) {
1764 if (strcmp(obj->externs[i].name, name) == 0)
1765 return &obj->externs[i];
1770 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1773 switch (ext->kcfg.type) {
1776 pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1780 *(bool *)ext_val = value == 'y' ? true : false;
1784 *(enum libbpf_tristate *)ext_val = TRI_YES;
1785 else if (value == 'm')
1786 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1787 else /* value == 'n' */
1788 *(enum libbpf_tristate *)ext_val = TRI_NO;
1791 *(char *)ext_val = value;
1797 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1805 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1810 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1811 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1816 len = strlen(value);
1817 if (value[len - 1] != '"') {
1818 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1825 if (len >= ext->kcfg.sz) {
1826 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1827 ext->name, value, len, ext->kcfg.sz - 1);
1828 len = ext->kcfg.sz - 1;
1830 memcpy(ext_val, value + 1, len);
1831 ext_val[len] = '\0';
1836 static int parse_u64(const char *value, __u64 *res)
1842 *res = strtoull(value, &value_end, 0);
1845 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1849 pr_warn("failed to parse '%s' as integer completely\n", value);
1855 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1857 int bit_sz = ext->kcfg.sz * 8;
1859 if (ext->kcfg.sz == 8)
1862 /* Validate that value stored in u64 fits in integer of `ext->sz`
1863 * bytes size without any loss of information. If the target integer
1864 * is signed, we rely on the following limits of integer type of
1865 * Y bits and subsequent transformation:
1867 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1868 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1869 * 0 <= X + 2^(Y-1) < 2^Y
1871 * For unsigned target integer, check that all the (64 - Y) bits are
1874 if (ext->kcfg.is_signed)
1875 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1877 return (v >> bit_sz) == 0;
1880 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1883 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1884 ext->kcfg.type != KCFG_BOOL) {
1885 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1886 ext->name, (unsigned long long)value);
1889 if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1890 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1891 ext->name, (unsigned long long)value);
1895 if (!is_kcfg_value_in_range(ext, value)) {
1896 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1897 ext->name, (unsigned long long)value, ext->kcfg.sz);
1900 switch (ext->kcfg.sz) {
1902 *(__u8 *)ext_val = value;
1905 *(__u16 *)ext_val = value;
1908 *(__u32 *)ext_val = value;
1911 *(__u64 *)ext_val = value;
1920 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1921 char *buf, void *data)
1923 struct extern_desc *ext;
1929 if (!str_has_pfx(buf, "CONFIG_"))
1932 sep = strchr(buf, '=');
1934 pr_warn("failed to parse '%s': no separator\n", buf);
1938 /* Trim ending '\n' */
1940 if (buf[len - 1] == '\n')
1941 buf[len - 1] = '\0';
1942 /* Split on '=' and ensure that a value is present. */
1946 pr_warn("failed to parse '%s': no value\n", buf);
1950 ext = find_extern_by_name(obj, buf);
1951 if (!ext || ext->is_set)
1954 ext_val = data + ext->kcfg.data_off;
1958 case 'y': case 'n': case 'm':
1959 err = set_kcfg_value_tri(ext, ext_val, *value);
1962 err = set_kcfg_value_str(ext, ext_val, value);
1965 /* assume integer */
1966 err = parse_u64(value, &num);
1968 pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1971 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1972 pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1975 err = set_kcfg_value_num(ext, ext_val, num);
1980 pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1984 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1992 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1995 else if (len >= PATH_MAX)
1996 return -ENAMETOOLONG;
1998 /* gzopen also accepts uncompressed files. */
1999 file = gzopen(buf, "re");
2001 file = gzopen("/proc/config.gz", "re");
2004 pr_warn("failed to open system Kconfig\n");
2008 while (gzgets(file, buf, sizeof(buf))) {
2009 err = bpf_object__process_kconfig_line(obj, buf, data);
2011 pr_warn("error parsing system Kconfig line '%s': %d\n",
2022 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2023 const char *config, void *data)
2029 file = fmemopen((void *)config, strlen(config), "r");
2032 pr_warn("failed to open in-memory Kconfig: %d\n", err);
2036 while (fgets(buf, sizeof(buf), file)) {
2037 err = bpf_object__process_kconfig_line(obj, buf, data);
2039 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2049 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2051 struct extern_desc *last_ext = NULL, *ext;
2055 for (i = 0; i < obj->nr_extern; i++) {
2056 ext = &obj->externs[i];
2057 if (ext->type == EXT_KCFG)
2064 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2065 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2066 ".kconfig", obj->efile.symbols_shndx,
2071 obj->kconfig_map_idx = obj->nr_maps - 1;
2076 const struct btf_type *
2077 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2079 const struct btf_type *t = btf__type_by_id(btf, id);
2084 while (btf_is_mod(t) || btf_is_typedef(t)) {
2087 t = btf__type_by_id(btf, t->type);
2093 static const struct btf_type *
2094 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2096 const struct btf_type *t;
2098 t = skip_mods_and_typedefs(btf, id, NULL);
2102 t = skip_mods_and_typedefs(btf, t->type, res_id);
2104 return btf_is_func_proto(t) ? t : NULL;
2107 static const char *__btf_kind_str(__u16 kind)
2110 case BTF_KIND_UNKN: return "void";
2111 case BTF_KIND_INT: return "int";
2112 case BTF_KIND_PTR: return "ptr";
2113 case BTF_KIND_ARRAY: return "array";
2114 case BTF_KIND_STRUCT: return "struct";
2115 case BTF_KIND_UNION: return "union";
2116 case BTF_KIND_ENUM: return "enum";
2117 case BTF_KIND_FWD: return "fwd";
2118 case BTF_KIND_TYPEDEF: return "typedef";
2119 case BTF_KIND_VOLATILE: return "volatile";
2120 case BTF_KIND_CONST: return "const";
2121 case BTF_KIND_RESTRICT: return "restrict";
2122 case BTF_KIND_FUNC: return "func";
2123 case BTF_KIND_FUNC_PROTO: return "func_proto";
2124 case BTF_KIND_VAR: return "var";
2125 case BTF_KIND_DATASEC: return "datasec";
2126 case BTF_KIND_FLOAT: return "float";
2127 case BTF_KIND_DECL_TAG: return "decl_tag";
2128 case BTF_KIND_TYPE_TAG: return "type_tag";
2129 case BTF_KIND_ENUM64: return "enum64";
2130 default: return "unknown";
2134 const char *btf_kind_str(const struct btf_type *t)
2136 return __btf_kind_str(btf_kind(t));
2140 * Fetch integer attribute of BTF map definition. Such attributes are
2141 * represented using a pointer to an array, in which dimensionality of array
2142 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2143 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2144 * type definition, while using only sizeof(void *) space in ELF data section.
2146 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2147 const struct btf_member *m, __u32 *res)
2149 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2150 const char *name = btf__name_by_offset(btf, m->name_off);
2151 const struct btf_array *arr_info;
2152 const struct btf_type *arr_t;
2154 if (!btf_is_ptr(t)) {
2155 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2156 map_name, name, btf_kind_str(t));
2160 arr_t = btf__type_by_id(btf, t->type);
2162 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2163 map_name, name, t->type);
2166 if (!btf_is_array(arr_t)) {
2167 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2168 map_name, name, btf_kind_str(arr_t));
2171 arr_info = btf_array(arr_t);
2172 *res = arr_info->nelems;
2176 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2180 len = snprintf(buf, buf_sz, "%s/%s", path, name);
2184 return -ENAMETOOLONG;
2189 static int build_map_pin_path(struct bpf_map *map, const char *path)
2195 path = "/sys/fs/bpf";
2197 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2201 return bpf_map__set_pin_path(map, buf);
2204 /* should match definition in bpf_helpers.h */
2205 enum libbpf_pin_type {
2207 /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2211 int parse_btf_map_def(const char *map_name, struct btf *btf,
2212 const struct btf_type *def_t, bool strict,
2213 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2215 const struct btf_type *t;
2216 const struct btf_member *m;
2217 bool is_inner = inner_def == NULL;
2220 vlen = btf_vlen(def_t);
2221 m = btf_members(def_t);
2222 for (i = 0; i < vlen; i++, m++) {
2223 const char *name = btf__name_by_offset(btf, m->name_off);
2226 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2229 if (strcmp(name, "type") == 0) {
2230 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2232 map_def->parts |= MAP_DEF_MAP_TYPE;
2233 } else if (strcmp(name, "max_entries") == 0) {
2234 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2236 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2237 } else if (strcmp(name, "map_flags") == 0) {
2238 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2240 map_def->parts |= MAP_DEF_MAP_FLAGS;
2241 } else if (strcmp(name, "numa_node") == 0) {
2242 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2244 map_def->parts |= MAP_DEF_NUMA_NODE;
2245 } else if (strcmp(name, "key_size") == 0) {
2248 if (!get_map_field_int(map_name, btf, m, &sz))
2250 if (map_def->key_size && map_def->key_size != sz) {
2251 pr_warn("map '%s': conflicting key size %u != %u.\n",
2252 map_name, map_def->key_size, sz);
2255 map_def->key_size = sz;
2256 map_def->parts |= MAP_DEF_KEY_SIZE;
2257 } else if (strcmp(name, "key") == 0) {
2260 t = btf__type_by_id(btf, m->type);
2262 pr_warn("map '%s': key type [%d] not found.\n",
2266 if (!btf_is_ptr(t)) {
2267 pr_warn("map '%s': key spec is not PTR: %s.\n",
2268 map_name, btf_kind_str(t));
2271 sz = btf__resolve_size(btf, t->type);
2273 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2274 map_name, t->type, (ssize_t)sz);
2277 if (map_def->key_size && map_def->key_size != sz) {
2278 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2279 map_name, map_def->key_size, (ssize_t)sz);
2282 map_def->key_size = sz;
2283 map_def->key_type_id = t->type;
2284 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2285 } else if (strcmp(name, "value_size") == 0) {
2288 if (!get_map_field_int(map_name, btf, m, &sz))
2290 if (map_def->value_size && map_def->value_size != sz) {
2291 pr_warn("map '%s': conflicting value size %u != %u.\n",
2292 map_name, map_def->value_size, sz);
2295 map_def->value_size = sz;
2296 map_def->parts |= MAP_DEF_VALUE_SIZE;
2297 } else if (strcmp(name, "value") == 0) {
2300 t = btf__type_by_id(btf, m->type);
2302 pr_warn("map '%s': value type [%d] not found.\n",
2306 if (!btf_is_ptr(t)) {
2307 pr_warn("map '%s': value spec is not PTR: %s.\n",
2308 map_name, btf_kind_str(t));
2311 sz = btf__resolve_size(btf, t->type);
2313 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2314 map_name, t->type, (ssize_t)sz);
2317 if (map_def->value_size && map_def->value_size != sz) {
2318 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2319 map_name, map_def->value_size, (ssize_t)sz);
2322 map_def->value_size = sz;
2323 map_def->value_type_id = t->type;
2324 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2326 else if (strcmp(name, "values") == 0) {
2327 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2328 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2329 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2330 char inner_map_name[128];
2334 pr_warn("map '%s': multi-level inner maps not supported.\n",
2338 if (i != vlen - 1) {
2339 pr_warn("map '%s': '%s' member should be last.\n",
2343 if (!is_map_in_map && !is_prog_array) {
2344 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2348 if (map_def->value_size && map_def->value_size != 4) {
2349 pr_warn("map '%s': conflicting value size %u != 4.\n",
2350 map_name, map_def->value_size);
2353 map_def->value_size = 4;
2354 t = btf__type_by_id(btf, m->type);
2356 pr_warn("map '%s': %s type [%d] not found.\n",
2357 map_name, desc, m->type);
2360 if (!btf_is_array(t) || btf_array(t)->nelems) {
2361 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2365 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2366 if (!btf_is_ptr(t)) {
2367 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2368 map_name, desc, btf_kind_str(t));
2371 t = skip_mods_and_typedefs(btf, t->type, NULL);
2372 if (is_prog_array) {
2373 if (!btf_is_func_proto(t)) {
2374 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2375 map_name, btf_kind_str(t));
2380 if (!btf_is_struct(t)) {
2381 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2382 map_name, btf_kind_str(t));
2386 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2387 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2391 map_def->parts |= MAP_DEF_INNER_MAP;
2392 } else if (strcmp(name, "pinning") == 0) {
2396 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2399 if (!get_map_field_int(map_name, btf, m, &val))
2401 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2402 pr_warn("map '%s': invalid pinning value %u.\n",
2406 map_def->pinning = val;
2407 map_def->parts |= MAP_DEF_PINNING;
2408 } else if (strcmp(name, "map_extra") == 0) {
2411 if (!get_map_field_int(map_name, btf, m, &map_extra))
2413 map_def->map_extra = map_extra;
2414 map_def->parts |= MAP_DEF_MAP_EXTRA;
2417 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2420 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2424 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2425 pr_warn("map '%s': map type isn't specified.\n", map_name);
2432 static size_t adjust_ringbuf_sz(size_t sz)
2434 __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2437 /* if user forgot to set any size, make sure they see error */
2440 /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2441 * a power-of-2 multiple of kernel's page size. If user diligently
2442 * satisified these conditions, pass the size through.
2444 if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2447 /* Otherwise find closest (page_sz * power_of_2) product bigger than
2448 * user-set size to satisfy both user size request and kernel
2449 * requirements and substitute correct max_entries for map creation.
2451 for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2452 if (mul * page_sz > sz)
2453 return mul * page_sz;
2456 /* if it's impossible to satisfy the conditions (i.e., user size is
2457 * very close to UINT_MAX but is not a power-of-2 multiple of
2458 * page_size) then just return original size and let kernel reject it
2463 static bool map_is_ringbuf(const struct bpf_map *map)
2465 return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2466 map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2469 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2471 map->def.type = def->map_type;
2472 map->def.key_size = def->key_size;
2473 map->def.value_size = def->value_size;
2474 map->def.max_entries = def->max_entries;
2475 map->def.map_flags = def->map_flags;
2476 map->map_extra = def->map_extra;
2478 map->numa_node = def->numa_node;
2479 map->btf_key_type_id = def->key_type_id;
2480 map->btf_value_type_id = def->value_type_id;
2482 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2483 if (map_is_ringbuf(map))
2484 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2486 if (def->parts & MAP_DEF_MAP_TYPE)
2487 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2489 if (def->parts & MAP_DEF_KEY_TYPE)
2490 pr_debug("map '%s': found key [%u], sz = %u.\n",
2491 map->name, def->key_type_id, def->key_size);
2492 else if (def->parts & MAP_DEF_KEY_SIZE)
2493 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2495 if (def->parts & MAP_DEF_VALUE_TYPE)
2496 pr_debug("map '%s': found value [%u], sz = %u.\n",
2497 map->name, def->value_type_id, def->value_size);
2498 else if (def->parts & MAP_DEF_VALUE_SIZE)
2499 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2501 if (def->parts & MAP_DEF_MAX_ENTRIES)
2502 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2503 if (def->parts & MAP_DEF_MAP_FLAGS)
2504 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2505 if (def->parts & MAP_DEF_MAP_EXTRA)
2506 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2507 (unsigned long long)def->map_extra);
2508 if (def->parts & MAP_DEF_PINNING)
2509 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2510 if (def->parts & MAP_DEF_NUMA_NODE)
2511 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2513 if (def->parts & MAP_DEF_INNER_MAP)
2514 pr_debug("map '%s': found inner map definition.\n", map->name);
2517 static const char *btf_var_linkage_str(__u32 linkage)
2520 case BTF_VAR_STATIC: return "static";
2521 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2522 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2523 default: return "unknown";
2527 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2528 const struct btf_type *sec,
2529 int var_idx, int sec_idx,
2530 const Elf_Data *data, bool strict,
2531 const char *pin_root_path)
2533 struct btf_map_def map_def = {}, inner_def = {};
2534 const struct btf_type *var, *def;
2535 const struct btf_var_secinfo *vi;
2536 const struct btf_var *var_extra;
2537 const char *map_name;
2538 struct bpf_map *map;
2541 vi = btf_var_secinfos(sec) + var_idx;
2542 var = btf__type_by_id(obj->btf, vi->type);
2543 var_extra = btf_var(var);
2544 map_name = btf__name_by_offset(obj->btf, var->name_off);
2546 if (map_name == NULL || map_name[0] == '\0') {
2547 pr_warn("map #%d: empty name.\n", var_idx);
2550 if ((__u64)vi->offset + vi->size > data->d_size) {
2551 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2554 if (!btf_is_var(var)) {
2555 pr_warn("map '%s': unexpected var kind %s.\n",
2556 map_name, btf_kind_str(var));
2559 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2560 pr_warn("map '%s': unsupported map linkage %s.\n",
2561 map_name, btf_var_linkage_str(var_extra->linkage));
2565 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2566 if (!btf_is_struct(def)) {
2567 pr_warn("map '%s': unexpected def kind %s.\n",
2568 map_name, btf_kind_str(var));
2571 if (def->size > vi->size) {
2572 pr_warn("map '%s': invalid def size.\n", map_name);
2576 map = bpf_object__add_map(obj);
2578 return PTR_ERR(map);
2579 map->name = strdup(map_name);
2581 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2584 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2585 map->def.type = BPF_MAP_TYPE_UNSPEC;
2586 map->sec_idx = sec_idx;
2587 map->sec_offset = vi->offset;
2588 map->btf_var_idx = var_idx;
2589 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2590 map_name, map->sec_idx, map->sec_offset);
2592 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2596 fill_map_from_def(map, &map_def);
2598 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2599 err = build_map_pin_path(map, pin_root_path);
2601 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2606 if (map_def.parts & MAP_DEF_INNER_MAP) {
2607 map->inner_map = calloc(1, sizeof(*map->inner_map));
2608 if (!map->inner_map)
2610 map->inner_map->fd = -1;
2611 map->inner_map->sec_idx = sec_idx;
2612 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2613 if (!map->inner_map->name)
2615 sprintf(map->inner_map->name, "%s.inner", map_name);
2617 fill_map_from_def(map->inner_map, &inner_def);
2620 err = map_fill_btf_type_info(obj, map);
2627 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2628 const char *pin_root_path)
2630 const struct btf_type *sec = NULL;
2631 int nr_types, i, vlen, err;
2632 const struct btf_type *t;
2637 if (obj->efile.btf_maps_shndx < 0)
2640 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2641 data = elf_sec_data(obj, scn);
2642 if (!scn || !data) {
2643 pr_warn("elf: failed to get %s map definitions for %s\n",
2644 MAPS_ELF_SEC, obj->path);
2648 nr_types = btf__type_cnt(obj->btf);
2649 for (i = 1; i < nr_types; i++) {
2650 t = btf__type_by_id(obj->btf, i);
2651 if (!btf_is_datasec(t))
2653 name = btf__name_by_offset(obj->btf, t->name_off);
2654 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2656 obj->efile.btf_maps_sec_btf_id = i;
2662 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2666 vlen = btf_vlen(sec);
2667 for (i = 0; i < vlen; i++) {
2668 err = bpf_object__init_user_btf_map(obj, sec, i,
2669 obj->efile.btf_maps_shndx,
2679 static int bpf_object__init_maps(struct bpf_object *obj,
2680 const struct bpf_object_open_opts *opts)
2682 const char *pin_root_path;
2686 strict = !OPTS_GET(opts, relaxed_maps, false);
2687 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2689 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2690 err = err ?: bpf_object__init_global_data_maps(obj);
2691 err = err ?: bpf_object__init_kconfig_map(obj);
2692 err = err ?: bpf_object_init_struct_ops(obj);
2697 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2701 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2705 return sh->sh_flags & SHF_EXECINSTR;
2708 static bool btf_needs_sanitization(struct bpf_object *obj)
2710 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2711 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2712 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2713 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2714 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2715 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2716 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2718 return !has_func || !has_datasec || !has_func_global || !has_float ||
2719 !has_decl_tag || !has_type_tag || !has_enum64;
2722 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2724 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2725 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2726 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2727 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2728 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2729 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2730 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2731 int enum64_placeholder_id = 0;
2735 for (i = 1; i < btf__type_cnt(btf); i++) {
2736 t = (struct btf_type *)btf__type_by_id(btf, i);
2738 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2739 /* replace VAR/DECL_TAG with INT */
2740 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2742 * using size = 1 is the safest choice, 4 will be too
2743 * big and cause kernel BTF validation failure if
2744 * original variable took less than 4 bytes
2747 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2748 } else if (!has_datasec && btf_is_datasec(t)) {
2749 /* replace DATASEC with STRUCT */
2750 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2751 struct btf_member *m = btf_members(t);
2752 struct btf_type *vt;
2755 name = (char *)btf__name_by_offset(btf, t->name_off);
2763 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2764 for (j = 0; j < vlen; j++, v++, m++) {
2765 /* order of field assignments is important */
2766 m->offset = v->offset * 8;
2768 /* preserve variable name as member name */
2769 vt = (void *)btf__type_by_id(btf, v->type);
2770 m->name_off = vt->name_off;
2772 } else if (!has_func && btf_is_func_proto(t)) {
2773 /* replace FUNC_PROTO with ENUM */
2775 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2776 t->size = sizeof(__u32); /* kernel enforced */
2777 } else if (!has_func && btf_is_func(t)) {
2778 /* replace FUNC with TYPEDEF */
2779 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2780 } else if (!has_func_global && btf_is_func(t)) {
2781 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2782 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2783 } else if (!has_float && btf_is_float(t)) {
2784 /* replace FLOAT with an equally-sized empty STRUCT;
2785 * since C compilers do not accept e.g. "float" as a
2786 * valid struct name, make it anonymous
2789 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2790 } else if (!has_type_tag && btf_is_type_tag(t)) {
2791 /* replace TYPE_TAG with a CONST */
2793 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2794 } else if (!has_enum64 && btf_is_enum(t)) {
2795 /* clear the kflag */
2796 t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2797 } else if (!has_enum64 && btf_is_enum64(t)) {
2798 /* replace ENUM64 with a union */
2799 struct btf_member *m;
2801 if (enum64_placeholder_id == 0) {
2802 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2803 if (enum64_placeholder_id < 0)
2804 return enum64_placeholder_id;
2806 t = (struct btf_type *)btf__type_by_id(btf, i);
2811 t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2812 for (j = 0; j < vlen; j++, m++) {
2813 m->type = enum64_placeholder_id;
2822 static bool libbpf_needs_btf(const struct bpf_object *obj)
2824 return obj->efile.btf_maps_shndx >= 0 ||
2825 obj->efile.st_ops_shndx >= 0 ||
2826 obj->efile.st_ops_link_shndx >= 0 ||
2830 static bool kernel_needs_btf(const struct bpf_object *obj)
2832 return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2835 static int bpf_object__init_btf(struct bpf_object *obj,
2837 Elf_Data *btf_ext_data)
2842 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2843 err = libbpf_get_error(obj->btf);
2846 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2849 /* enforce 8-byte pointers for BPF-targeted BTFs */
2850 btf__set_pointer_size(obj->btf, 8);
2853 struct btf_ext_info *ext_segs[3];
2854 int seg_num, sec_num;
2857 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2858 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2861 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2862 err = libbpf_get_error(obj->btf_ext);
2864 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2865 BTF_EXT_ELF_SEC, err);
2866 obj->btf_ext = NULL;
2870 /* setup .BTF.ext to ELF section mapping */
2871 ext_segs[0] = &obj->btf_ext->func_info;
2872 ext_segs[1] = &obj->btf_ext->line_info;
2873 ext_segs[2] = &obj->btf_ext->core_relo_info;
2874 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2875 struct btf_ext_info *seg = ext_segs[seg_num];
2876 const struct btf_ext_info_sec *sec;
2877 const char *sec_name;
2880 if (seg->sec_cnt == 0)
2883 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2884 if (!seg->sec_idxs) {
2890 for_each_btf_ext_sec(seg, sec) {
2891 /* preventively increment index to avoid doing
2892 * this before every continue below
2896 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2897 if (str_is_empty(sec_name))
2899 scn = elf_sec_by_name(obj, sec_name);
2903 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2908 if (err && libbpf_needs_btf(obj)) {
2909 pr_warn("BTF is required, but is missing or corrupted.\n");
2915 static int compare_vsi_off(const void *_a, const void *_b)
2917 const struct btf_var_secinfo *a = _a;
2918 const struct btf_var_secinfo *b = _b;
2920 return a->offset - b->offset;
2923 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2926 __u32 size = 0, i, vars = btf_vlen(t);
2927 const char *sec_name = btf__name_by_offset(btf, t->name_off);
2928 struct btf_var_secinfo *vsi;
2929 bool fixup_offsets = false;
2933 pr_debug("No name found in string section for DATASEC kind.\n");
2937 /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2938 * variable offsets set at the previous step. Further, not every
2939 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2940 * all fixups altogether for such sections and go straight to sorting
2941 * VARs within their DATASEC.
2943 if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2946 /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2947 * fix this up. But BPF static linker already fixes this up and fills
2948 * all the sizes and offsets during static linking. So this step has
2949 * to be optional. But the STV_HIDDEN handling is non-optional for any
2950 * non-extern DATASEC, so the variable fixup loop below handles both
2951 * functions at the same time, paying the cost of BTF VAR <-> ELF
2952 * symbol matching just once.
2955 err = find_elf_sec_sz(obj, sec_name, &size);
2957 pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2958 sec_name, size, err);
2963 fixup_offsets = true;
2966 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2967 const struct btf_type *t_var;
2968 struct btf_var *var;
2969 const char *var_name;
2972 t_var = btf__type_by_id(btf, vsi->type);
2973 if (!t_var || !btf_is_var(t_var)) {
2974 pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2978 var = btf_var(t_var);
2979 if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2982 var_name = btf__name_by_offset(btf, t_var->name_off);
2984 pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2989 sym = find_elf_var_sym(obj, var_name);
2991 pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2992 sec_name, var_name);
2997 vsi->offset = sym->st_value;
2999 /* if variable is a global/weak symbol, but has restricted
3000 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3001 * as static. This follows similar logic for functions (BPF
3002 * subprogs) and influences libbpf's further decisions about
3003 * whether to make global data BPF array maps as
3006 if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3007 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3008 var->linkage = BTF_VAR_STATIC;
3012 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3016 static int bpf_object_fixup_btf(struct bpf_object *obj)
3023 n = btf__type_cnt(obj->btf);
3024 for (i = 1; i < n; i++) {
3025 struct btf_type *t = btf_type_by_id(obj->btf, i);
3027 /* Loader needs to fix up some of the things compiler
3028 * couldn't get its hands on while emitting BTF. This
3029 * is section size and global variable offset. We use
3030 * the info from the ELF itself for this purpose.
3032 if (btf_is_datasec(t)) {
3033 err = btf_fixup_datasec(obj, obj->btf, t);
3042 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3044 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3045 prog->type == BPF_PROG_TYPE_LSM)
3048 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3049 * also need vmlinux BTF
3051 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3057 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3059 struct bpf_program *prog;
3062 /* CO-RE relocations need kernel BTF, only when btf_custom_path
3065 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3068 /* Support for typed ksyms needs kernel BTF */
3069 for (i = 0; i < obj->nr_extern; i++) {
3070 const struct extern_desc *ext;
3072 ext = &obj->externs[i];
3073 if (ext->type == EXT_KSYM && ext->ksym.type_id)
3077 bpf_object__for_each_program(prog, obj) {
3078 if (!prog->autoload)
3080 if (prog_needs_vmlinux_btf(prog))
3087 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3091 /* btf_vmlinux could be loaded earlier */
3092 if (obj->btf_vmlinux || obj->gen_loader)
3095 if (!force && !obj_needs_vmlinux_btf(obj))
3098 obj->btf_vmlinux = btf__load_vmlinux_btf();
3099 err = libbpf_get_error(obj->btf_vmlinux);
3101 pr_warn("Error loading vmlinux BTF: %d\n", err);
3102 obj->btf_vmlinux = NULL;
3108 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3110 struct btf *kern_btf = obj->btf;
3111 bool btf_mandatory, sanitize;
3117 if (!kernel_supports(obj, FEAT_BTF)) {
3118 if (kernel_needs_btf(obj)) {
3122 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3126 /* Even though some subprogs are global/weak, user might prefer more
3127 * permissive BPF verification process that BPF verifier performs for
3128 * static functions, taking into account more context from the caller
3129 * functions. In such case, they need to mark such subprogs with
3130 * __attribute__((visibility("hidden"))) and libbpf will adjust
3131 * corresponding FUNC BTF type to be marked as static and trigger more
3132 * involved BPF verification process.
3134 for (i = 0; i < obj->nr_programs; i++) {
3135 struct bpf_program *prog = &obj->programs[i];
3140 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3143 n = btf__type_cnt(obj->btf);
3144 for (j = 1; j < n; j++) {
3145 t = btf_type_by_id(obj->btf, j);
3146 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3149 name = btf__str_by_offset(obj->btf, t->name_off);
3150 if (strcmp(name, prog->name) != 0)
3153 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3158 if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3159 goto skip_exception_cb;
3160 for (i = 0; i < obj->nr_programs; i++) {
3161 struct bpf_program *prog = &obj->programs[i];
3164 if (prog_is_subprog(obj, prog))
3166 n = btf__type_cnt(obj->btf);
3167 for (j = 1; j < n; j++) {
3168 const char *str = "exception_callback:", *name;
3169 size_t len = strlen(str);
3172 t = btf_type_by_id(obj->btf, j);
3173 if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3176 name = btf__str_by_offset(obj->btf, t->name_off);
3177 if (strncmp(name, str, len))
3180 t = btf_type_by_id(obj->btf, t->type);
3181 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3182 pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3186 if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3188 /* Multiple callbacks are specified for the same prog,
3189 * the verifier will eventually return an error for this
3190 * case, hence simply skip appending a subprog.
3192 if (prog->exception_cb_idx >= 0) {
3193 prog->exception_cb_idx = -1;
3198 if (str_is_empty(name)) {
3199 pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3204 for (k = 0; k < obj->nr_programs; k++) {
3205 struct bpf_program *subprog = &obj->programs[k];
3207 if (!prog_is_subprog(obj, subprog))
3209 if (strcmp(name, subprog->name))
3211 /* Enforce non-hidden, as from verifier point of
3212 * view it expects global functions, whereas the
3213 * mark_btf_static fixes up linkage as static.
3215 if (!subprog->sym_global || subprog->mark_btf_static) {
3216 pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3217 prog->name, subprog->name);
3220 /* Let's see if we already saw a static exception callback with the same name */
3221 if (prog->exception_cb_idx >= 0) {
3222 pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3223 prog->name, subprog->name);
3226 prog->exception_cb_idx = k;
3230 if (prog->exception_cb_idx >= 0)
3232 pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3238 sanitize = btf_needs_sanitization(obj);
3240 const void *raw_data;
3243 /* clone BTF to sanitize a copy and leave the original intact */
3244 raw_data = btf__raw_data(obj->btf, &sz);
3245 kern_btf = btf__new(raw_data, sz);
3246 err = libbpf_get_error(kern_btf);
3250 /* enforce 8-byte pointers for BPF-targeted BTFs */
3251 btf__set_pointer_size(obj->btf, 8);
3252 err = bpf_object__sanitize_btf(obj, kern_btf);
3257 if (obj->gen_loader) {
3259 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3263 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3264 /* Pretend to have valid FD to pass various fd >= 0 checks.
3265 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3267 btf__set_fd(kern_btf, 0);
3269 /* currently BPF_BTF_LOAD only supports log_level 1 */
3270 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3271 obj->log_level ? 1 : 0);
3275 /* move fd to libbpf's BTF */
3276 btf__set_fd(obj->btf, btf__fd(kern_btf));
3277 btf__set_fd(kern_btf, -1);
3279 btf__free(kern_btf);
3283 btf_mandatory = kernel_needs_btf(obj);
3284 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3285 btf_mandatory ? "BTF is mandatory, can't proceed."
3286 : "BTF is optional, ignoring.");
3293 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3297 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3299 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3300 off, obj->path, elf_errmsg(-1));
3307 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3311 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3313 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3314 off, obj->path, elf_errmsg(-1));
3321 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3325 scn = elf_getscn(obj->efile.elf, idx);
3327 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3328 idx, obj->path, elf_errmsg(-1));
3334 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3336 Elf_Scn *scn = NULL;
3337 Elf *elf = obj->efile.elf;
3338 const char *sec_name;
3340 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3341 sec_name = elf_sec_name(obj, scn);
3345 if (strcmp(sec_name, name) != 0)
3353 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3360 shdr = elf64_getshdr(scn);
3362 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3363 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3370 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3378 sh = elf_sec_hdr(obj, scn);
3382 name = elf_sec_str(obj, sh->sh_name);
3384 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3385 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3392 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3399 data = elf_getdata(scn, 0);
3401 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3402 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3403 obj->path, elf_errmsg(-1));
3410 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3412 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3415 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3418 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3420 if (idx >= data->d_size / sizeof(Elf64_Rel))
3423 return (Elf64_Rel *)data->d_buf + idx;
3426 static bool is_sec_name_dwarf(const char *name)
3428 /* approximation, but the actual list is too long */
3429 return str_has_pfx(name, ".debug_");
3432 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3434 /* no special handling of .strtab */
3435 if (hdr->sh_type == SHT_STRTAB)
3438 /* ignore .llvm_addrsig section as well */
3439 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3442 /* no subprograms will lead to an empty .text section, ignore it */
3443 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3444 strcmp(name, ".text") == 0)
3447 /* DWARF sections */
3448 if (is_sec_name_dwarf(name))
3451 if (str_has_pfx(name, ".rel")) {
3452 name += sizeof(".rel") - 1;
3453 /* DWARF section relocations */
3454 if (is_sec_name_dwarf(name))
3457 /* .BTF and .BTF.ext don't need relocations */
3458 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3459 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3466 static int cmp_progs(const void *_a, const void *_b)
3468 const struct bpf_program *a = _a;
3469 const struct bpf_program *b = _b;
3471 if (a->sec_idx != b->sec_idx)
3472 return a->sec_idx < b->sec_idx ? -1 : 1;
3474 /* sec_insn_off can't be the same within the section */
3475 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3478 static int bpf_object__elf_collect(struct bpf_object *obj)
3480 struct elf_sec_desc *sec_desc;
3481 Elf *elf = obj->efile.elf;
3482 Elf_Data *btf_ext_data = NULL;
3483 Elf_Data *btf_data = NULL;
3484 int idx = 0, err = 0;
3490 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3491 * section. Since section count retrieved by elf_getshdrnum() does
3492 * include sec #0, it is already the necessary size of an array to keep
3495 if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3496 pr_warn("elf: failed to get the number of sections for %s: %s\n",
3497 obj->path, elf_errmsg(-1));
3498 return -LIBBPF_ERRNO__FORMAT;
3500 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3501 if (!obj->efile.secs)
3504 /* a bunch of ELF parsing functionality depends on processing symbols,
3505 * so do the first pass and find the symbol table
3508 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3509 sh = elf_sec_hdr(obj, scn);
3511 return -LIBBPF_ERRNO__FORMAT;
3513 if (sh->sh_type == SHT_SYMTAB) {
3514 if (obj->efile.symbols) {
3515 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3516 return -LIBBPF_ERRNO__FORMAT;
3519 data = elf_sec_data(obj, scn);
3521 return -LIBBPF_ERRNO__FORMAT;
3523 idx = elf_ndxscn(scn);
3525 obj->efile.symbols = data;
3526 obj->efile.symbols_shndx = idx;
3527 obj->efile.strtabidx = sh->sh_link;
3531 if (!obj->efile.symbols) {
3532 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3538 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3539 idx = elf_ndxscn(scn);
3540 sec_desc = &obj->efile.secs[idx];
3542 sh = elf_sec_hdr(obj, scn);
3544 return -LIBBPF_ERRNO__FORMAT;
3546 name = elf_sec_str(obj, sh->sh_name);
3548 return -LIBBPF_ERRNO__FORMAT;
3550 if (ignore_elf_section(sh, name))
3553 data = elf_sec_data(obj, scn);
3555 return -LIBBPF_ERRNO__FORMAT;
3557 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3558 idx, name, (unsigned long)data->d_size,
3559 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3562 if (strcmp(name, "license") == 0) {
3563 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3566 } else if (strcmp(name, "version") == 0) {
3567 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3570 } else if (strcmp(name, "maps") == 0) {
3571 pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3573 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3574 obj->efile.btf_maps_shndx = idx;
3575 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3576 if (sh->sh_type != SHT_PROGBITS)
3577 return -LIBBPF_ERRNO__FORMAT;
3579 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3580 if (sh->sh_type != SHT_PROGBITS)
3581 return -LIBBPF_ERRNO__FORMAT;
3582 btf_ext_data = data;
3583 } else if (sh->sh_type == SHT_SYMTAB) {
3584 /* already processed during the first pass above */
3585 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3586 if (sh->sh_flags & SHF_EXECINSTR) {
3587 if (strcmp(name, ".text") == 0)
3588 obj->efile.text_shndx = idx;
3589 err = bpf_object__add_programs(obj, data, name, idx);
3592 } else if (strcmp(name, DATA_SEC) == 0 ||
3593 str_has_pfx(name, DATA_SEC ".")) {
3594 sec_desc->sec_type = SEC_DATA;
3595 sec_desc->shdr = sh;
3596 sec_desc->data = data;
3597 } else if (strcmp(name, RODATA_SEC) == 0 ||
3598 str_has_pfx(name, RODATA_SEC ".")) {
3599 sec_desc->sec_type = SEC_RODATA;
3600 sec_desc->shdr = sh;
3601 sec_desc->data = data;
3602 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3603 obj->efile.st_ops_data = data;
3604 obj->efile.st_ops_shndx = idx;
3605 } else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3606 obj->efile.st_ops_link_data = data;
3607 obj->efile.st_ops_link_shndx = idx;
3609 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3612 } else if (sh->sh_type == SHT_REL) {
3613 int targ_sec_idx = sh->sh_info; /* points to other section */
3615 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3616 targ_sec_idx >= obj->efile.sec_cnt)
3617 return -LIBBPF_ERRNO__FORMAT;
3619 /* Only do relo for section with exec instructions */
3620 if (!section_have_execinstr(obj, targ_sec_idx) &&
3621 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3622 strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3623 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3624 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3625 idx, name, targ_sec_idx,
3626 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3630 sec_desc->sec_type = SEC_RELO;
3631 sec_desc->shdr = sh;
3632 sec_desc->data = data;
3633 } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3634 str_has_pfx(name, BSS_SEC "."))) {
3635 sec_desc->sec_type = SEC_BSS;
3636 sec_desc->shdr = sh;
3637 sec_desc->data = data;
3639 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3640 (size_t)sh->sh_size);
3644 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3645 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3646 return -LIBBPF_ERRNO__FORMAT;
3649 /* sort BPF programs by section name and in-section instruction offset
3652 if (obj->nr_programs)
3653 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3655 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3658 static bool sym_is_extern(const Elf64_Sym *sym)
3660 int bind = ELF64_ST_BIND(sym->st_info);
3661 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3662 return sym->st_shndx == SHN_UNDEF &&
3663 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3664 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3667 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3669 int bind = ELF64_ST_BIND(sym->st_info);
3670 int type = ELF64_ST_TYPE(sym->st_info);
3672 /* in .text section */
3673 if (sym->st_shndx != text_shndx)
3676 /* local function */
3677 if (bind == STB_LOCAL && type == STT_SECTION)
3680 /* global function */
3681 return bind == STB_GLOBAL && type == STT_FUNC;
3684 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3686 const struct btf_type *t;
3693 n = btf__type_cnt(btf);
3694 for (i = 1; i < n; i++) {
3695 t = btf__type_by_id(btf, i);
3697 if (!btf_is_var(t) && !btf_is_func(t))
3700 tname = btf__name_by_offset(btf, t->name_off);
3701 if (strcmp(tname, ext_name))
3704 if (btf_is_var(t) &&
3705 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3708 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3717 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3718 const struct btf_var_secinfo *vs;
3719 const struct btf_type *t;
3725 n = btf__type_cnt(btf);
3726 for (i = 1; i < n; i++) {
3727 t = btf__type_by_id(btf, i);
3729 if (!btf_is_datasec(t))
3732 vs = btf_var_secinfos(t);
3733 for (j = 0; j < btf_vlen(t); j++, vs++) {
3734 if (vs->type == ext_btf_id)
3742 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3745 const struct btf_type *t;
3748 t = skip_mods_and_typedefs(btf, id, NULL);
3749 name = btf__name_by_offset(btf, t->name_off);
3753 switch (btf_kind(t)) {
3754 case BTF_KIND_INT: {
3755 int enc = btf_int_encoding(t);
3757 if (enc & BTF_INT_BOOL)
3758 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3760 *is_signed = enc & BTF_INT_SIGNED;
3763 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3764 return KCFG_UNKNOWN;
3769 return KCFG_UNKNOWN;
3770 if (strcmp(name, "libbpf_tristate"))
3771 return KCFG_UNKNOWN;
3772 return KCFG_TRISTATE;
3773 case BTF_KIND_ENUM64:
3774 if (strcmp(name, "libbpf_tristate"))
3775 return KCFG_UNKNOWN;
3776 return KCFG_TRISTATE;
3777 case BTF_KIND_ARRAY:
3778 if (btf_array(t)->nelems == 0)
3779 return KCFG_UNKNOWN;
3780 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3781 return KCFG_UNKNOWN;
3782 return KCFG_CHAR_ARR;
3784 return KCFG_UNKNOWN;
3788 static int cmp_externs(const void *_a, const void *_b)
3790 const struct extern_desc *a = _a;
3791 const struct extern_desc *b = _b;
3793 if (a->type != b->type)
3794 return a->type < b->type ? -1 : 1;
3796 if (a->type == EXT_KCFG) {
3797 /* descending order by alignment requirements */
3798 if (a->kcfg.align != b->kcfg.align)
3799 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3800 /* ascending order by size, within same alignment class */
3801 if (a->kcfg.sz != b->kcfg.sz)
3802 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3805 /* resolve ties by name */
3806 return strcmp(a->name, b->name);
3809 static int find_int_btf_id(const struct btf *btf)
3811 const struct btf_type *t;
3814 n = btf__type_cnt(btf);
3815 for (i = 1; i < n; i++) {
3816 t = btf__type_by_id(btf, i);
3818 if (btf_is_int(t) && btf_int_bits(t) == 32)
3825 static int add_dummy_ksym_var(struct btf *btf)
3827 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3828 const struct btf_var_secinfo *vs;
3829 const struct btf_type *sec;
3834 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3839 sec = btf__type_by_id(btf, sec_btf_id);
3840 vs = btf_var_secinfos(sec);
3841 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3842 const struct btf_type *vt;
3844 vt = btf__type_by_id(btf, vs->type);
3845 if (btf_is_func(vt))
3849 /* No func in ksyms sec. No need to add dummy var. */
3850 if (i == btf_vlen(sec))
3853 int_btf_id = find_int_btf_id(btf);
3854 dummy_var_btf_id = btf__add_var(btf,
3856 BTF_VAR_GLOBAL_ALLOCATED,
3858 if (dummy_var_btf_id < 0)
3859 pr_warn("cannot create a dummy_ksym var\n");
3861 return dummy_var_btf_id;
3864 static int bpf_object__collect_externs(struct bpf_object *obj)
3866 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3867 const struct btf_type *t;
3868 struct extern_desc *ext;
3869 int i, n, off, dummy_var_btf_id;
3870 const char *ext_name, *sec_name;
3871 size_t ext_essent_len;
3875 if (!obj->efile.symbols)
3878 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3879 sh = elf_sec_hdr(obj, scn);
3880 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3881 return -LIBBPF_ERRNO__FORMAT;
3883 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3884 if (dummy_var_btf_id < 0)
3885 return dummy_var_btf_id;
3887 n = sh->sh_size / sh->sh_entsize;
3888 pr_debug("looking for externs among %d symbols...\n", n);
3890 for (i = 0; i < n; i++) {
3891 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3894 return -LIBBPF_ERRNO__FORMAT;
3895 if (!sym_is_extern(sym))
3897 ext_name = elf_sym_str(obj, sym->st_name);
3898 if (!ext_name || !ext_name[0])
3902 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3906 ext = &ext[obj->nr_extern];
3907 memset(ext, 0, sizeof(*ext));
3910 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3911 if (ext->btf_id <= 0) {
3912 pr_warn("failed to find BTF for extern '%s': %d\n",
3913 ext_name, ext->btf_id);
3916 t = btf__type_by_id(obj->btf, ext->btf_id);
3917 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3919 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3921 ext_essent_len = bpf_core_essential_name_len(ext->name);
3922 ext->essent_name = NULL;
3923 if (ext_essent_len != strlen(ext->name)) {
3924 ext->essent_name = strndup(ext->name, ext_essent_len);
3925 if (!ext->essent_name)
3929 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3930 if (ext->sec_btf_id <= 0) {
3931 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3932 ext_name, ext->btf_id, ext->sec_btf_id);
3933 return ext->sec_btf_id;
3935 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3936 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3938 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3939 if (btf_is_func(t)) {
3940 pr_warn("extern function %s is unsupported under %s section\n",
3941 ext->name, KCONFIG_SEC);
3945 ext->type = EXT_KCFG;
3946 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3947 if (ext->kcfg.sz <= 0) {
3948 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3949 ext_name, ext->kcfg.sz);
3950 return ext->kcfg.sz;
3952 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3953 if (ext->kcfg.align <= 0) {
3954 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3955 ext_name, ext->kcfg.align);
3958 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3959 &ext->kcfg.is_signed);
3960 if (ext->kcfg.type == KCFG_UNKNOWN) {
3961 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3964 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3966 ext->type = EXT_KSYM;
3967 skip_mods_and_typedefs(obj->btf, t->type,
3968 &ext->ksym.type_id);
3970 pr_warn("unrecognized extern section '%s'\n", sec_name);
3974 pr_debug("collected %d externs total\n", obj->nr_extern);
3976 if (!obj->nr_extern)
3979 /* sort externs by type, for kcfg ones also by (align, size, name) */
3980 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3982 /* for .ksyms section, we need to turn all externs into allocated
3983 * variables in BTF to pass kernel verification; we do this by
3984 * pretending that each extern is a 8-byte variable
3987 /* find existing 4-byte integer type in BTF to use for fake
3988 * extern variables in DATASEC
3990 int int_btf_id = find_int_btf_id(obj->btf);
3991 /* For extern function, a dummy_var added earlier
3992 * will be used to replace the vs->type and
3993 * its name string will be used to refill
3994 * the missing param's name.
3996 const struct btf_type *dummy_var;
3998 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3999 for (i = 0; i < obj->nr_extern; i++) {
4000 ext = &obj->externs[i];
4001 if (ext->type != EXT_KSYM)
4003 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4004 i, ext->sym_idx, ext->name);
4009 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4010 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4011 struct btf_type *vt;
4013 vt = (void *)btf__type_by_id(obj->btf, vs->type);
4014 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4015 ext = find_extern_by_name(obj, ext_name);
4017 pr_warn("failed to find extern definition for BTF %s '%s'\n",
4018 btf_kind_str(vt), ext_name);
4021 if (btf_is_func(vt)) {
4022 const struct btf_type *func_proto;
4023 struct btf_param *param;
4026 func_proto = btf__type_by_id(obj->btf,
4028 param = btf_params(func_proto);
4029 /* Reuse the dummy_var string if the
4030 * func proto does not have param name.
4032 for (j = 0; j < btf_vlen(func_proto); j++)
4033 if (param[j].type && !param[j].name_off)
4035 dummy_var->name_off;
4036 vs->type = dummy_var_btf_id;
4037 vt->info &= ~0xffff;
4038 vt->info |= BTF_FUNC_GLOBAL;
4040 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4041 vt->type = int_btf_id;
4044 vs->size = sizeof(int);
4051 /* for kcfg externs calculate their offsets within a .kconfig map */
4053 for (i = 0; i < obj->nr_extern; i++) {
4054 ext = &obj->externs[i];
4055 if (ext->type != EXT_KCFG)
4058 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4059 off = ext->kcfg.data_off + ext->kcfg.sz;
4060 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4061 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4065 for (i = 0; i < n; i++) {
4066 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4068 t = btf__type_by_id(obj->btf, vs->type);
4069 ext_name = btf__name_by_offset(obj->btf, t->name_off);
4070 ext = find_extern_by_name(obj, ext_name);
4072 pr_warn("failed to find extern definition for BTF var '%s'\n",
4076 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4077 vs->offset = ext->kcfg.data_off;
4083 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4085 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4088 struct bpf_program *
4089 bpf_object__find_program_by_name(const struct bpf_object *obj,
4092 struct bpf_program *prog;
4094 bpf_object__for_each_program(prog, obj) {
4095 if (prog_is_subprog(obj, prog))
4097 if (!strcmp(prog->name, name))
4100 return errno = ENOENT, NULL;
4103 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4106 switch (obj->efile.secs[shndx].sec_type) {
4116 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4119 return shndx == obj->efile.btf_maps_shndx;
4122 static enum libbpf_map_type
4123 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4125 if (shndx == obj->efile.symbols_shndx)
4126 return LIBBPF_MAP_KCONFIG;
4128 switch (obj->efile.secs[shndx].sec_type) {
4130 return LIBBPF_MAP_BSS;
4132 return LIBBPF_MAP_DATA;
4134 return LIBBPF_MAP_RODATA;
4136 return LIBBPF_MAP_UNSPEC;
4140 static int bpf_program__record_reloc(struct bpf_program *prog,
4141 struct reloc_desc *reloc_desc,
4142 __u32 insn_idx, const char *sym_name,
4143 const Elf64_Sym *sym, const Elf64_Rel *rel)
4145 struct bpf_insn *insn = &prog->insns[insn_idx];
4146 size_t map_idx, nr_maps = prog->obj->nr_maps;
4147 struct bpf_object *obj = prog->obj;
4148 __u32 shdr_idx = sym->st_shndx;
4149 enum libbpf_map_type type;
4150 const char *sym_sec_name;
4151 struct bpf_map *map;
4153 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4154 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4155 prog->name, sym_name, insn_idx, insn->code);
4156 return -LIBBPF_ERRNO__RELOC;
4159 if (sym_is_extern(sym)) {
4160 int sym_idx = ELF64_R_SYM(rel->r_info);
4161 int i, n = obj->nr_extern;
4162 struct extern_desc *ext;
4164 for (i = 0; i < n; i++) {
4165 ext = &obj->externs[i];
4166 if (ext->sym_idx == sym_idx)
4170 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4171 prog->name, sym_name, sym_idx);
4172 return -LIBBPF_ERRNO__RELOC;
4174 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4175 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4176 if (insn->code == (BPF_JMP | BPF_CALL))
4177 reloc_desc->type = RELO_EXTERN_CALL;
4179 reloc_desc->type = RELO_EXTERN_LD64;
4180 reloc_desc->insn_idx = insn_idx;
4181 reloc_desc->ext_idx = i;
4185 /* sub-program call relocation */
4186 if (is_call_insn(insn)) {
4187 if (insn->src_reg != BPF_PSEUDO_CALL) {
4188 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4189 return -LIBBPF_ERRNO__RELOC;
4191 /* text_shndx can be 0, if no default "main" program exists */
4192 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4193 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4194 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4195 prog->name, sym_name, sym_sec_name);
4196 return -LIBBPF_ERRNO__RELOC;
4198 if (sym->st_value % BPF_INSN_SZ) {
4199 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4200 prog->name, sym_name, (size_t)sym->st_value);
4201 return -LIBBPF_ERRNO__RELOC;
4203 reloc_desc->type = RELO_CALL;
4204 reloc_desc->insn_idx = insn_idx;
4205 reloc_desc->sym_off = sym->st_value;
4209 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4210 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4211 prog->name, sym_name, shdr_idx);
4212 return -LIBBPF_ERRNO__RELOC;
4215 /* loading subprog addresses */
4216 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4217 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4218 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4220 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4221 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4222 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4223 return -LIBBPF_ERRNO__RELOC;
4226 reloc_desc->type = RELO_SUBPROG_ADDR;
4227 reloc_desc->insn_idx = insn_idx;
4228 reloc_desc->sym_off = sym->st_value;
4232 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4233 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4235 /* generic map reference relocation */
4236 if (type == LIBBPF_MAP_UNSPEC) {
4237 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4238 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4239 prog->name, sym_name, sym_sec_name);
4240 return -LIBBPF_ERRNO__RELOC;
4242 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4243 map = &obj->maps[map_idx];
4244 if (map->libbpf_type != type ||
4245 map->sec_idx != sym->st_shndx ||
4246 map->sec_offset != sym->st_value)
4248 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4249 prog->name, map_idx, map->name, map->sec_idx,
4250 map->sec_offset, insn_idx);
4253 if (map_idx >= nr_maps) {
4254 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4255 prog->name, sym_sec_name, (size_t)sym->st_value);
4256 return -LIBBPF_ERRNO__RELOC;
4258 reloc_desc->type = RELO_LD64;
4259 reloc_desc->insn_idx = insn_idx;
4260 reloc_desc->map_idx = map_idx;
4261 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4265 /* global data map relocation */
4266 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4267 pr_warn("prog '%s': bad data relo against section '%s'\n",
4268 prog->name, sym_sec_name);
4269 return -LIBBPF_ERRNO__RELOC;
4271 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4272 map = &obj->maps[map_idx];
4273 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4275 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4276 prog->name, map_idx, map->name, map->sec_idx,
4277 map->sec_offset, insn_idx);
4280 if (map_idx >= nr_maps) {
4281 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4282 prog->name, sym_sec_name);
4283 return -LIBBPF_ERRNO__RELOC;
4286 reloc_desc->type = RELO_DATA;
4287 reloc_desc->insn_idx = insn_idx;
4288 reloc_desc->map_idx = map_idx;
4289 reloc_desc->sym_off = sym->st_value;
4293 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4295 return insn_idx >= prog->sec_insn_off &&
4296 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4299 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4300 size_t sec_idx, size_t insn_idx)
4302 int l = 0, r = obj->nr_programs - 1, m;
4303 struct bpf_program *prog;
4305 if (!obj->nr_programs)
4309 m = l + (r - l + 1) / 2;
4310 prog = &obj->programs[m];
4312 if (prog->sec_idx < sec_idx ||
4313 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4318 /* matching program could be at index l, but it still might be the
4319 * wrong one, so we need to double check conditions for the last time
4321 prog = &obj->programs[l];
4322 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4328 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4330 const char *relo_sec_name, *sec_name;
4331 size_t sec_idx = shdr->sh_info, sym_idx;
4332 struct bpf_program *prog;
4333 struct reloc_desc *relos;
4335 const char *sym_name;
4342 if (sec_idx >= obj->efile.sec_cnt)
4345 scn = elf_sec_by_idx(obj, sec_idx);
4346 scn_data = elf_sec_data(obj, scn);
4348 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4349 sec_name = elf_sec_name(obj, scn);
4350 if (!relo_sec_name || !sec_name)
4353 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4354 relo_sec_name, sec_idx, sec_name);
4355 nrels = shdr->sh_size / shdr->sh_entsize;
4357 for (i = 0; i < nrels; i++) {
4358 rel = elf_rel_by_idx(data, i);
4360 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4361 return -LIBBPF_ERRNO__FORMAT;
4364 sym_idx = ELF64_R_SYM(rel->r_info);
4365 sym = elf_sym_by_idx(obj, sym_idx);
4367 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4368 relo_sec_name, sym_idx, i);
4369 return -LIBBPF_ERRNO__FORMAT;
4372 if (sym->st_shndx >= obj->efile.sec_cnt) {
4373 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4374 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4375 return -LIBBPF_ERRNO__FORMAT;
4378 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4379 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4380 relo_sec_name, (size_t)rel->r_offset, i);
4381 return -LIBBPF_ERRNO__FORMAT;
4384 insn_idx = rel->r_offset / BPF_INSN_SZ;
4385 /* relocations against static functions are recorded as
4386 * relocations against the section that contains a function;
4387 * in such case, symbol will be STT_SECTION and sym.st_name
4388 * will point to empty string (0), so fetch section name
4391 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4392 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4394 sym_name = elf_sym_str(obj, sym->st_name);
4395 sym_name = sym_name ?: "<?";
4397 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4398 relo_sec_name, i, insn_idx, sym_name);
4400 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4402 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4403 relo_sec_name, i, sec_name, insn_idx);
4407 relos = libbpf_reallocarray(prog->reloc_desc,
4408 prog->nr_reloc + 1, sizeof(*relos));
4411 prog->reloc_desc = relos;
4413 /* adjust insn_idx to local BPF program frame of reference */
4414 insn_idx -= prog->sec_insn_off;
4415 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4416 insn_idx, sym_name, sym, rel);
4425 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4432 /* if it's BTF-defined map, we don't need to search for type IDs.
4433 * For struct_ops map, it does not need btf_key_type_id and
4434 * btf_value_type_id.
4436 if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4440 * LLVM annotates global data differently in BTF, that is,
4441 * only as '.data', '.bss' or '.rodata'.
4443 if (!bpf_map__is_internal(map))
4446 id = btf__find_by_name(obj->btf, map->real_name);
4450 map->btf_key_type_id = 0;
4451 map->btf_value_type_id = id;
4455 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4457 char file[PATH_MAX], buff[4096];
4462 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4463 memset(info, 0, sizeof(*info));
4465 fp = fopen(file, "re");
4468 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4473 while (fgets(buff, sizeof(buff), fp)) {
4474 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4476 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4477 info->key_size = val;
4478 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4479 info->value_size = val;
4480 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4481 info->max_entries = val;
4482 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4483 info->map_flags = val;
4491 bool bpf_map__autocreate(const struct bpf_map *map)
4493 return map->autocreate;
4496 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4498 if (map->obj->loaded)
4499 return libbpf_err(-EBUSY);
4501 map->autocreate = autocreate;
4505 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4507 struct bpf_map_info info;
4508 __u32 len = sizeof(info), name_len;
4512 memset(&info, 0, len);
4513 err = bpf_map_get_info_by_fd(fd, &info, &len);
4514 if (err && errno == EINVAL)
4515 err = bpf_get_map_info_from_fdinfo(fd, &info);
4517 return libbpf_err(err);
4519 name_len = strlen(info.name);
4520 if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4521 new_name = strdup(map->name);
4523 new_name = strdup(info.name);
4526 return libbpf_err(-errno);
4529 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4530 * This is similar to what we do in ensure_good_fd(), but without
4531 * closing original FD.
4533 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4536 goto err_free_new_name;
4539 err = zclose(map->fd);
4542 goto err_close_new_fd;
4547 map->name = new_name;
4548 map->def.type = info.type;
4549 map->def.key_size = info.key_size;
4550 map->def.value_size = info.value_size;
4551 map->def.max_entries = info.max_entries;
4552 map->def.map_flags = info.map_flags;
4553 map->btf_key_type_id = info.btf_key_type_id;
4554 map->btf_value_type_id = info.btf_value_type_id;
4556 map->map_extra = info.map_extra;
4564 return libbpf_err(err);
4567 __u32 bpf_map__max_entries(const struct bpf_map *map)
4569 return map->def.max_entries;
4572 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4574 if (!bpf_map_type__is_map_in_map(map->def.type))
4575 return errno = EINVAL, NULL;
4577 return map->inner_map;
4580 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4582 if (map->obj->loaded)
4583 return libbpf_err(-EBUSY);
4585 map->def.max_entries = max_entries;
4587 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4588 if (map_is_ringbuf(map))
4589 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4595 bpf_object__probe_loading(struct bpf_object *obj)
4597 char *cp, errmsg[STRERR_BUFSIZE];
4598 struct bpf_insn insns[] = {
4599 BPF_MOV64_IMM(BPF_REG_0, 0),
4602 int ret, insn_cnt = ARRAY_SIZE(insns);
4604 if (obj->gen_loader)
4607 ret = bump_rlimit_memlock();
4609 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4611 /* make sure basic loading works */
4612 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4614 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4617 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4618 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4619 "program. Make sure your kernel supports BPF "
4620 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4621 "set to big enough value.\n", __func__, cp, ret);
4629 static int probe_fd(int fd)
4636 static int probe_kern_prog_name(void)
4638 const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4639 struct bpf_insn insns[] = {
4640 BPF_MOV64_IMM(BPF_REG_0, 0),
4643 union bpf_attr attr;
4646 memset(&attr, 0, attr_sz);
4647 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4648 attr.license = ptr_to_u64("GPL");
4649 attr.insns = ptr_to_u64(insns);
4650 attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4651 libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4653 /* make sure loading with name works */
4654 ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4655 return probe_fd(ret);
4658 static int probe_kern_global_data(void)
4660 char *cp, errmsg[STRERR_BUFSIZE];
4661 struct bpf_insn insns[] = {
4662 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4663 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4664 BPF_MOV64_IMM(BPF_REG_0, 0),
4667 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4669 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4672 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4673 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4674 __func__, cp, -ret);
4680 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4682 return probe_fd(ret);
4685 static int probe_kern_btf(void)
4687 static const char strs[] = "\0int";
4690 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4693 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4694 strs, sizeof(strs)));
4697 static int probe_kern_btf_func(void)
4699 static const char strs[] = "\0int\0x\0a";
4700 /* void x(int a) {} */
4703 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4704 /* FUNC_PROTO */ /* [2] */
4705 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4706 BTF_PARAM_ENC(7, 1),
4707 /* FUNC x */ /* [3] */
4708 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4711 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4712 strs, sizeof(strs)));
4715 static int probe_kern_btf_func_global(void)
4717 static const char strs[] = "\0int\0x\0a";
4718 /* static void x(int a) {} */
4721 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4722 /* FUNC_PROTO */ /* [2] */
4723 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4724 BTF_PARAM_ENC(7, 1),
4725 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4726 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4729 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4730 strs, sizeof(strs)));
4733 static int probe_kern_btf_datasec(void)
4735 static const char strs[] = "\0x\0.data";
4739 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4740 /* VAR x */ /* [2] */
4741 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4743 /* DATASEC val */ /* [3] */
4744 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4745 BTF_VAR_SECINFO_ENC(2, 0, 4),
4748 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4749 strs, sizeof(strs)));
4752 static int probe_kern_btf_float(void)
4754 static const char strs[] = "\0float";
4757 BTF_TYPE_FLOAT_ENC(1, 4),
4760 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4761 strs, sizeof(strs)));
4764 static int probe_kern_btf_decl_tag(void)
4766 static const char strs[] = "\0tag";
4769 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4770 /* VAR x */ /* [2] */
4771 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4774 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4777 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4778 strs, sizeof(strs)));
4781 static int probe_kern_btf_type_tag(void)
4783 static const char strs[] = "\0tag";
4786 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4788 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4790 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4793 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4794 strs, sizeof(strs)));
4797 static int probe_kern_array_mmap(void)
4799 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4802 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4803 return probe_fd(fd);
4806 static int probe_kern_exp_attach_type(void)
4808 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4809 struct bpf_insn insns[] = {
4810 BPF_MOV64_IMM(BPF_REG_0, 0),
4813 int fd, insn_cnt = ARRAY_SIZE(insns);
4815 /* use any valid combination of program type and (optional)
4816 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4817 * to see if kernel supports expected_attach_type field for
4818 * BPF_PROG_LOAD command
4820 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4821 return probe_fd(fd);
4824 static int probe_kern_probe_read_kernel(void)
4826 struct bpf_insn insns[] = {
4827 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4828 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4829 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4830 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4831 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4834 int fd, insn_cnt = ARRAY_SIZE(insns);
4836 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4837 return probe_fd(fd);
4840 static int probe_prog_bind_map(void)
4842 char *cp, errmsg[STRERR_BUFSIZE];
4843 struct bpf_insn insns[] = {
4844 BPF_MOV64_IMM(BPF_REG_0, 0),
4847 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4849 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4852 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4853 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4854 __func__, cp, -ret);
4858 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4864 ret = bpf_prog_bind_map(prog, map, NULL);
4872 static int probe_module_btf(void)
4874 static const char strs[] = "\0int";
4877 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4879 struct bpf_btf_info info;
4880 __u32 len = sizeof(info);
4884 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4886 return 0; /* BTF not supported at all */
4888 memset(&info, 0, sizeof(info));
4889 info.name = ptr_to_u64(name);
4890 info.name_len = sizeof(name);
4892 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4893 * kernel's module BTF support coincides with support for
4894 * name/name_len fields in struct bpf_btf_info.
4896 err = bpf_btf_get_info_by_fd(fd, &info, &len);
4901 static int probe_perf_link(void)
4903 struct bpf_insn insns[] = {
4904 BPF_MOV64_IMM(BPF_REG_0, 0),
4907 int prog_fd, link_fd, err;
4909 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4910 insns, ARRAY_SIZE(insns), NULL);
4914 /* use invalid perf_event FD to get EBADF, if link is supported;
4915 * otherwise EINVAL should be returned
4917 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4918 err = -errno; /* close() can clobber errno */
4924 return link_fd < 0 && err == -EBADF;
4927 static int probe_uprobe_multi_link(void)
4929 LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4930 .expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4932 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4933 struct bpf_insn insns[] = {
4934 BPF_MOV64_IMM(BPF_REG_0, 0),
4937 int prog_fd, link_fd, err;
4938 unsigned long offset = 0;
4940 prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4941 insns, ARRAY_SIZE(insns), &load_opts);
4945 /* Creating uprobe in '/' binary should fail with -EBADF. */
4946 link_opts.uprobe_multi.path = "/";
4947 link_opts.uprobe_multi.offsets = &offset;
4948 link_opts.uprobe_multi.cnt = 1;
4950 link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4951 err = -errno; /* close() can clobber errno */
4957 return link_fd < 0 && err == -EBADF;
4960 static int probe_kern_bpf_cookie(void)
4962 struct bpf_insn insns[] = {
4963 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4966 int ret, insn_cnt = ARRAY_SIZE(insns);
4968 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4969 return probe_fd(ret);
4972 static int probe_kern_btf_enum64(void)
4974 static const char strs[] = "\0enum64";
4976 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4979 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4980 strs, sizeof(strs)));
4983 static int probe_kern_syscall_wrapper(void);
4985 enum kern_feature_result {
4991 typedef int (*feature_probe_fn)(void);
4993 static struct kern_feature_desc {
4995 feature_probe_fn probe;
4996 enum kern_feature_result res;
4997 } feature_probes[__FEAT_CNT] = {
4998 [FEAT_PROG_NAME] = {
4999 "BPF program name", probe_kern_prog_name,
5001 [FEAT_GLOBAL_DATA] = {
5002 "global variables", probe_kern_global_data,
5005 "minimal BTF", probe_kern_btf,
5008 "BTF functions", probe_kern_btf_func,
5010 [FEAT_BTF_GLOBAL_FUNC] = {
5011 "BTF global function", probe_kern_btf_func_global,
5013 [FEAT_BTF_DATASEC] = {
5014 "BTF data section and variable", probe_kern_btf_datasec,
5016 [FEAT_ARRAY_MMAP] = {
5017 "ARRAY map mmap()", probe_kern_array_mmap,
5019 [FEAT_EXP_ATTACH_TYPE] = {
5020 "BPF_PROG_LOAD expected_attach_type attribute",
5021 probe_kern_exp_attach_type,
5023 [FEAT_PROBE_READ_KERN] = {
5024 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5026 [FEAT_PROG_BIND_MAP] = {
5027 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5029 [FEAT_MODULE_BTF] = {
5030 "module BTF support", probe_module_btf,
5032 [FEAT_BTF_FLOAT] = {
5033 "BTF_KIND_FLOAT support", probe_kern_btf_float,
5035 [FEAT_PERF_LINK] = {
5036 "BPF perf link support", probe_perf_link,
5038 [FEAT_BTF_DECL_TAG] = {
5039 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5041 [FEAT_BTF_TYPE_TAG] = {
5042 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5044 [FEAT_MEMCG_ACCOUNT] = {
5045 "memcg-based memory accounting", probe_memcg_account,
5047 [FEAT_BPF_COOKIE] = {
5048 "BPF cookie support", probe_kern_bpf_cookie,
5050 [FEAT_BTF_ENUM64] = {
5051 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5053 [FEAT_SYSCALL_WRAPPER] = {
5054 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5056 [FEAT_UPROBE_MULTI_LINK] = {
5057 "BPF multi-uprobe link support", probe_uprobe_multi_link,
5061 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5063 struct kern_feature_desc *feat = &feature_probes[feat_id];
5066 if (obj && obj->gen_loader)
5067 /* To generate loader program assume the latest kernel
5068 * to avoid doing extra prog_load, map_create syscalls.
5072 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5073 ret = feat->probe();
5075 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5076 } else if (ret == 0) {
5077 WRITE_ONCE(feat->res, FEAT_MISSING);
5079 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5080 WRITE_ONCE(feat->res, FEAT_MISSING);
5084 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5087 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5089 struct bpf_map_info map_info;
5090 char msg[STRERR_BUFSIZE];
5091 __u32 map_info_len = sizeof(map_info);
5094 memset(&map_info, 0, map_info_len);
5095 err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5096 if (err && errno == EINVAL)
5097 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5099 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5100 libbpf_strerror_r(errno, msg, sizeof(msg)));
5104 return (map_info.type == map->def.type &&
5105 map_info.key_size == map->def.key_size &&
5106 map_info.value_size == map->def.value_size &&
5107 map_info.max_entries == map->def.max_entries &&
5108 map_info.map_flags == map->def.map_flags &&
5109 map_info.map_extra == map->map_extra);
5113 bpf_object__reuse_map(struct bpf_map *map)
5115 char *cp, errmsg[STRERR_BUFSIZE];
5118 pin_fd = bpf_obj_get(map->pin_path);
5121 if (err == -ENOENT) {
5122 pr_debug("found no pinned map to reuse at '%s'\n",
5127 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5128 pr_warn("couldn't retrieve pinned map '%s': %s\n",
5133 if (!map_is_reuse_compat(map, pin_fd)) {
5134 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5140 err = bpf_map__reuse_fd(map, pin_fd);
5146 pr_debug("reused pinned map at '%s'\n", map->pin_path);
5152 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5154 enum libbpf_map_type map_type = map->libbpf_type;
5155 char *cp, errmsg[STRERR_BUFSIZE];
5158 if (obj->gen_loader) {
5159 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5160 map->mmaped, map->def.value_size);
5161 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5162 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5165 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5168 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5169 pr_warn("Error setting initial map(%s) contents: %s\n",
5174 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
5175 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5176 err = bpf_map_freeze(map->fd);
5179 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5180 pr_warn("Error freezing map(%s) as read-only: %s\n",
5188 static void bpf_map__destroy(struct bpf_map *map);
5190 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5192 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5193 struct bpf_map_def *def = &map->def;
5194 const char *map_name = NULL;
5197 if (kernel_supports(obj, FEAT_PROG_NAME))
5198 map_name = map->name;
5199 create_attr.map_ifindex = map->map_ifindex;
5200 create_attr.map_flags = def->map_flags;
5201 create_attr.numa_node = map->numa_node;
5202 create_attr.map_extra = map->map_extra;
5204 if (bpf_map__is_struct_ops(map))
5205 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5207 if (obj->btf && btf__fd(obj->btf) >= 0) {
5208 create_attr.btf_fd = btf__fd(obj->btf);
5209 create_attr.btf_key_type_id = map->btf_key_type_id;
5210 create_attr.btf_value_type_id = map->btf_value_type_id;
5213 if (bpf_map_type__is_map_in_map(def->type)) {
5214 if (map->inner_map) {
5215 err = bpf_object__create_map(obj, map->inner_map, true);
5217 pr_warn("map '%s': failed to create inner map: %d\n",
5221 map->inner_map_fd = bpf_map__fd(map->inner_map);
5223 if (map->inner_map_fd >= 0)
5224 create_attr.inner_map_fd = map->inner_map_fd;
5227 switch (def->type) {
5228 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5229 case BPF_MAP_TYPE_CGROUP_ARRAY:
5230 case BPF_MAP_TYPE_STACK_TRACE:
5231 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5232 case BPF_MAP_TYPE_HASH_OF_MAPS:
5233 case BPF_MAP_TYPE_DEVMAP:
5234 case BPF_MAP_TYPE_DEVMAP_HASH:
5235 case BPF_MAP_TYPE_CPUMAP:
5236 case BPF_MAP_TYPE_XSKMAP:
5237 case BPF_MAP_TYPE_SOCKMAP:
5238 case BPF_MAP_TYPE_SOCKHASH:
5239 case BPF_MAP_TYPE_QUEUE:
5240 case BPF_MAP_TYPE_STACK:
5241 create_attr.btf_fd = 0;
5242 create_attr.btf_key_type_id = 0;
5243 create_attr.btf_value_type_id = 0;
5244 map->btf_key_type_id = 0;
5245 map->btf_value_type_id = 0;
5250 if (obj->gen_loader) {
5251 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5252 def->key_size, def->value_size, def->max_entries,
5253 &create_attr, is_inner ? -1 : map - obj->maps);
5254 /* Pretend to have valid FD to pass various fd >= 0 checks.
5255 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5259 map->fd = bpf_map_create(def->type, map_name,
5260 def->key_size, def->value_size,
5261 def->max_entries, &create_attr);
5263 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5264 create_attr.btf_value_type_id)) {
5265 char *cp, errmsg[STRERR_BUFSIZE];
5268 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5269 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5270 map->name, cp, err);
5271 create_attr.btf_fd = 0;
5272 create_attr.btf_key_type_id = 0;
5273 create_attr.btf_value_type_id = 0;
5274 map->btf_key_type_id = 0;
5275 map->btf_value_type_id = 0;
5276 map->fd = bpf_map_create(def->type, map_name,
5277 def->key_size, def->value_size,
5278 def->max_entries, &create_attr);
5281 err = map->fd < 0 ? -errno : 0;
5283 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5284 if (obj->gen_loader)
5285 map->inner_map->fd = -1;
5286 bpf_map__destroy(map->inner_map);
5287 zfree(&map->inner_map);
5293 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5295 const struct bpf_map *targ_map;
5299 for (i = 0; i < map->init_slots_sz; i++) {
5300 if (!map->init_slots[i])
5303 targ_map = map->init_slots[i];
5304 fd = bpf_map__fd(targ_map);
5306 if (obj->gen_loader) {
5307 bpf_gen__populate_outer_map(obj->gen_loader,
5309 targ_map - obj->maps);
5311 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5315 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5316 map->name, i, targ_map->name, fd, err);
5319 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5320 map->name, i, targ_map->name, fd);
5323 zfree(&map->init_slots);
5324 map->init_slots_sz = 0;
5329 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5331 const struct bpf_program *targ_prog;
5335 if (obj->gen_loader)
5338 for (i = 0; i < map->init_slots_sz; i++) {
5339 if (!map->init_slots[i])
5342 targ_prog = map->init_slots[i];
5343 fd = bpf_program__fd(targ_prog);
5345 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5348 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5349 map->name, i, targ_prog->name, fd, err);
5352 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5353 map->name, i, targ_prog->name, fd);
5356 zfree(&map->init_slots);
5357 map->init_slots_sz = 0;
5362 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5364 struct bpf_map *map;
5367 for (i = 0; i < obj->nr_maps; i++) {
5368 map = &obj->maps[i];
5370 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5373 err = init_prog_array_slots(obj, map);
5382 static int map_set_def_max_entries(struct bpf_map *map)
5384 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5387 nr_cpus = libbpf_num_possible_cpus();
5389 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5390 map->name, nr_cpus);
5393 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5394 map->def.max_entries = nr_cpus;
5401 bpf_object__create_maps(struct bpf_object *obj)
5403 struct bpf_map *map;
5404 char *cp, errmsg[STRERR_BUFSIZE];
5409 for (i = 0; i < obj->nr_maps; i++) {
5410 map = &obj->maps[i];
5412 /* To support old kernels, we skip creating global data maps
5413 * (.rodata, .data, .kconfig, etc); later on, during program
5414 * loading, if we detect that at least one of the to-be-loaded
5415 * programs is referencing any global data map, we'll error
5416 * out with program name and relocation index logged.
5417 * This approach allows to accommodate Clang emitting
5418 * unnecessary .rodata.str1.1 sections for string literals,
5419 * but also it allows to have CO-RE applications that use
5420 * global variables in some of BPF programs, but not others.
5421 * If those global variable-using programs are not loaded at
5422 * runtime due to bpf_program__set_autoload(prog, false),
5423 * bpf_object loading will succeed just fine even on old
5426 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5427 map->autocreate = false;
5429 if (!map->autocreate) {
5430 pr_debug("map '%s': skipped auto-creating...\n", map->name);
5434 err = map_set_def_max_entries(map);
5440 if (map->pin_path) {
5441 err = bpf_object__reuse_map(map);
5443 pr_warn("map '%s': error reusing pinned map\n",
5447 if (retried && map->fd < 0) {
5448 pr_warn("map '%s': cannot find pinned map\n",
5456 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5457 map->name, map->fd);
5459 err = bpf_object__create_map(obj, map, false);
5463 pr_debug("map '%s': created successfully, fd=%d\n",
5464 map->name, map->fd);
5466 if (bpf_map__is_internal(map)) {
5467 err = bpf_object__populate_internal_map(obj, map);
5474 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5475 err = init_map_in_map_slots(obj, map);
5483 if (map->pin_path && !map->pinned) {
5484 err = bpf_map__pin(map, NULL);
5487 if (!retried && err == -EEXIST) {
5491 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5492 map->name, map->pin_path, err);
5501 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5502 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5504 for (j = 0; j < i; j++)
5505 zclose(obj->maps[j].fd);
5509 static bool bpf_core_is_flavor_sep(const char *s)
5511 /* check X___Y name pattern, where X and Y are not underscores */
5512 return s[0] != '_' && /* X */
5513 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5514 s[4] != '_'; /* Y */
5517 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5518 * before last triple underscore. Struct name part after last triple
5519 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5521 size_t bpf_core_essential_name_len(const char *name)
5523 size_t n = strlen(name);
5526 for (i = n - 5; i >= 0; i--) {
5527 if (bpf_core_is_flavor_sep(name + i))
5533 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5542 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5543 size_t local_essent_len,
5544 const struct btf *targ_btf,
5545 const char *targ_btf_name,
5547 struct bpf_core_cand_list *cands)
5549 struct bpf_core_cand *new_cands, *cand;
5550 const struct btf_type *t, *local_t;
5551 const char *targ_name, *local_name;
5552 size_t targ_essent_len;
5555 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5556 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5558 n = btf__type_cnt(targ_btf);
5559 for (i = targ_start_id; i < n; i++) {
5560 t = btf__type_by_id(targ_btf, i);
5561 if (!btf_kind_core_compat(t, local_t))
5564 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5565 if (str_is_empty(targ_name))
5568 targ_essent_len = bpf_core_essential_name_len(targ_name);
5569 if (targ_essent_len != local_essent_len)
5572 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5575 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5576 local_cand->id, btf_kind_str(local_t),
5577 local_name, i, btf_kind_str(t), targ_name,
5579 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5580 sizeof(*cands->cands));
5584 cand = &new_cands[cands->len];
5585 cand->btf = targ_btf;
5588 cands->cands = new_cands;
5594 static int load_module_btfs(struct bpf_object *obj)
5596 struct bpf_btf_info info;
5597 struct module_btf *mod_btf;
5603 if (obj->btf_modules_loaded)
5606 if (obj->gen_loader)
5609 /* don't do this again, even if we find no module BTFs */
5610 obj->btf_modules_loaded = true;
5612 /* kernel too old to support module BTFs */
5613 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5617 err = bpf_btf_get_next_id(id, &id);
5618 if (err && errno == ENOENT)
5620 if (err && errno == EPERM) {
5621 pr_debug("skipping module BTFs loading, missing privileges\n");
5626 pr_warn("failed to iterate BTF objects: %d\n", err);
5630 fd = bpf_btf_get_fd_by_id(id);
5632 if (errno == ENOENT)
5633 continue; /* expected race: BTF was unloaded */
5635 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5640 memset(&info, 0, sizeof(info));
5641 info.name = ptr_to_u64(name);
5642 info.name_len = sizeof(name);
5644 err = bpf_btf_get_info_by_fd(fd, &info, &len);
5647 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5651 /* ignore non-module BTFs */
5652 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5657 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5658 err = libbpf_get_error(btf);
5660 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5665 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5666 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5670 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5675 mod_btf->name = strdup(name);
5676 if (!mod_btf->name) {
5690 static struct bpf_core_cand_list *
5691 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5693 struct bpf_core_cand local_cand = {};
5694 struct bpf_core_cand_list *cands;
5695 const struct btf *main_btf;
5696 const struct btf_type *local_t;
5697 const char *local_name;
5698 size_t local_essent_len;
5701 local_cand.btf = local_btf;
5702 local_cand.id = local_type_id;
5703 local_t = btf__type_by_id(local_btf, local_type_id);
5705 return ERR_PTR(-EINVAL);
5707 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5708 if (str_is_empty(local_name))
5709 return ERR_PTR(-EINVAL);
5710 local_essent_len = bpf_core_essential_name_len(local_name);
5712 cands = calloc(1, sizeof(*cands));
5714 return ERR_PTR(-ENOMEM);
5716 /* Attempt to find target candidates in vmlinux BTF first */
5717 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5718 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5722 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5726 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5727 if (obj->btf_vmlinux_override)
5730 /* now look through module BTFs, trying to still find candidates */
5731 err = load_module_btfs(obj);
5735 for (i = 0; i < obj->btf_module_cnt; i++) {
5736 err = bpf_core_add_cands(&local_cand, local_essent_len,
5737 obj->btf_modules[i].btf,
5738 obj->btf_modules[i].name,
5739 btf__type_cnt(obj->btf_vmlinux),
5747 bpf_core_free_cands(cands);
5748 return ERR_PTR(err);
5751 /* Check local and target types for compatibility. This check is used for
5752 * type-based CO-RE relocations and follow slightly different rules than
5753 * field-based relocations. This function assumes that root types were already
5754 * checked for name match. Beyond that initial root-level name check, names
5755 * are completely ignored. Compatibility rules are as follows:
5756 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5757 * kind should match for local and target types (i.e., STRUCT is not
5758 * compatible with UNION);
5759 * - for ENUMs, the size is ignored;
5760 * - for INT, size and signedness are ignored;
5761 * - for ARRAY, dimensionality is ignored, element types are checked for
5762 * compatibility recursively;
5763 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5764 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5765 * - FUNC_PROTOs are compatible if they have compatible signature: same
5766 * number of input args and compatible return and argument types.
5767 * These rules are not set in stone and probably will be adjusted as we get
5768 * more experience with using BPF CO-RE relocations.
5770 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5771 const struct btf *targ_btf, __u32 targ_id)
5773 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5776 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5777 const struct btf *targ_btf, __u32 targ_id)
5779 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5782 static size_t bpf_core_hash_fn(const long key, void *ctx)
5787 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5792 static int record_relo_core(struct bpf_program *prog,
5793 const struct bpf_core_relo *core_relo, int insn_idx)
5795 struct reloc_desc *relos, *relo;
5797 relos = libbpf_reallocarray(prog->reloc_desc,
5798 prog->nr_reloc + 1, sizeof(*relos));
5801 relo = &relos[prog->nr_reloc];
5802 relo->type = RELO_CORE;
5803 relo->insn_idx = insn_idx;
5804 relo->core_relo = core_relo;
5805 prog->reloc_desc = relos;
5810 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5812 struct reloc_desc *relo;
5815 for (i = 0; i < prog->nr_reloc; i++) {
5816 relo = &prog->reloc_desc[i];
5817 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5820 return relo->core_relo;
5826 static int bpf_core_resolve_relo(struct bpf_program *prog,
5827 const struct bpf_core_relo *relo,
5829 const struct btf *local_btf,
5830 struct hashmap *cand_cache,
5831 struct bpf_core_relo_res *targ_res)
5833 struct bpf_core_spec specs_scratch[3] = {};
5834 struct bpf_core_cand_list *cands = NULL;
5835 const char *prog_name = prog->name;
5836 const struct btf_type *local_type;
5837 const char *local_name;
5838 __u32 local_id = relo->type_id;
5841 local_type = btf__type_by_id(local_btf, local_id);
5845 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5849 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5850 !hashmap__find(cand_cache, local_id, &cands)) {
5851 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5852 if (IS_ERR(cands)) {
5853 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5854 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5855 local_name, PTR_ERR(cands));
5856 return PTR_ERR(cands);
5858 err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5860 bpf_core_free_cands(cands);
5865 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5870 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5872 const struct btf_ext_info_sec *sec;
5873 struct bpf_core_relo_res targ_res;
5874 const struct bpf_core_relo *rec;
5875 const struct btf_ext_info *seg;
5876 struct hashmap_entry *entry;
5877 struct hashmap *cand_cache = NULL;
5878 struct bpf_program *prog;
5879 struct bpf_insn *insn;
5880 const char *sec_name;
5881 int i, err = 0, insn_idx, sec_idx, sec_num;
5883 if (obj->btf_ext->core_relo_info.len == 0)
5886 if (targ_btf_path) {
5887 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5888 err = libbpf_get_error(obj->btf_vmlinux_override);
5890 pr_warn("failed to parse target BTF: %d\n", err);
5895 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5896 if (IS_ERR(cand_cache)) {
5897 err = PTR_ERR(cand_cache);
5901 seg = &obj->btf_ext->core_relo_info;
5903 for_each_btf_ext_sec(seg, sec) {
5904 sec_idx = seg->sec_idxs[sec_num];
5907 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5908 if (str_is_empty(sec_name)) {
5913 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5915 for_each_btf_ext_rec(seg, sec, i, rec) {
5916 if (rec->insn_off % BPF_INSN_SZ)
5918 insn_idx = rec->insn_off / BPF_INSN_SZ;
5919 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5921 /* When __weak subprog is "overridden" by another instance
5922 * of the subprog from a different object file, linker still
5923 * appends all the .BTF.ext info that used to belong to that
5924 * eliminated subprogram.
5925 * This is similar to what x86-64 linker does for relocations.
5926 * So just ignore such relocations just like we ignore
5927 * subprog instructions when discovering subprograms.
5929 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5930 sec_name, i, insn_idx);
5933 /* no need to apply CO-RE relocation if the program is
5934 * not going to be loaded
5936 if (!prog->autoload)
5939 /* adjust insn_idx from section frame of reference to the local
5940 * program's frame of reference; (sub-)program code is not yet
5941 * relocated, so it's enough to just subtract in-section offset
5943 insn_idx = insn_idx - prog->sec_insn_off;
5944 if (insn_idx >= prog->insns_cnt)
5946 insn = &prog->insns[insn_idx];
5948 err = record_relo_core(prog, rec, insn_idx);
5950 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5951 prog->name, i, err);
5955 if (prog->obj->gen_loader)
5958 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5960 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5961 prog->name, i, err);
5965 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5967 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5968 prog->name, i, insn_idx, err);
5975 /* obj->btf_vmlinux and module BTFs are freed after object load */
5976 btf__free(obj->btf_vmlinux_override);
5977 obj->btf_vmlinux_override = NULL;
5979 if (!IS_ERR_OR_NULL(cand_cache)) {
5980 hashmap__for_each_entry(cand_cache, entry, i) {
5981 bpf_core_free_cands(entry->pvalue);
5983 hashmap__free(cand_cache);
5988 /* base map load ldimm64 special constant, used also for log fixup logic */
5989 #define POISON_LDIMM64_MAP_BASE 2001000000
5990 #define POISON_LDIMM64_MAP_PFX "200100"
5992 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5993 int insn_idx, struct bpf_insn *insn,
5994 int map_idx, const struct bpf_map *map)
5998 pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5999 prog->name, relo_idx, insn_idx, map_idx, map->name);
6001 /* we turn single ldimm64 into two identical invalid calls */
6002 for (i = 0; i < 2; i++) {
6003 insn->code = BPF_JMP | BPF_CALL;
6007 /* if this instruction is reachable (not a dead code),
6008 * verifier will complain with something like:
6009 * invalid func unknown#2001000123
6010 * where lower 123 is map index into obj->maps[] array
6012 insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6018 /* unresolved kfunc call special constant, used also for log fixup logic */
6019 #define POISON_CALL_KFUNC_BASE 2002000000
6020 #define POISON_CALL_KFUNC_PFX "2002"
6022 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6023 int insn_idx, struct bpf_insn *insn,
6024 int ext_idx, const struct extern_desc *ext)
6026 pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6027 prog->name, relo_idx, insn_idx, ext->name);
6029 /* we turn kfunc call into invalid helper call with identifiable constant */
6030 insn->code = BPF_JMP | BPF_CALL;
6034 /* if this instruction is reachable (not a dead code),
6035 * verifier will complain with something like:
6036 * invalid func unknown#2001000123
6037 * where lower 123 is extern index into obj->externs[] array
6039 insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6042 /* Relocate data references within program code:
6044 * - global variable references;
6045 * - extern references.
6048 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6052 for (i = 0; i < prog->nr_reloc; i++) {
6053 struct reloc_desc *relo = &prog->reloc_desc[i];
6054 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6055 const struct bpf_map *map;
6056 struct extern_desc *ext;
6058 switch (relo->type) {
6060 map = &obj->maps[relo->map_idx];
6061 if (obj->gen_loader) {
6062 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6063 insn[0].imm = relo->map_idx;
6064 } else if (map->autocreate) {
6065 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6066 insn[0].imm = map->fd;
6068 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6069 relo->map_idx, map);
6073 map = &obj->maps[relo->map_idx];
6074 insn[1].imm = insn[0].imm + relo->sym_off;
6075 if (obj->gen_loader) {
6076 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6077 insn[0].imm = relo->map_idx;
6078 } else if (map->autocreate) {
6079 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6080 insn[0].imm = map->fd;
6082 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6083 relo->map_idx, map);
6086 case RELO_EXTERN_LD64:
6087 ext = &obj->externs[relo->ext_idx];
6088 if (ext->type == EXT_KCFG) {
6089 if (obj->gen_loader) {
6090 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6091 insn[0].imm = obj->kconfig_map_idx;
6093 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6094 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6096 insn[1].imm = ext->kcfg.data_off;
6097 } else /* EXT_KSYM */ {
6098 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6099 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6100 insn[0].imm = ext->ksym.kernel_btf_id;
6101 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6102 } else { /* typeless ksyms or unresolved typed ksyms */
6103 insn[0].imm = (__u32)ext->ksym.addr;
6104 insn[1].imm = ext->ksym.addr >> 32;
6108 case RELO_EXTERN_CALL:
6109 ext = &obj->externs[relo->ext_idx];
6110 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6112 insn[0].imm = ext->ksym.kernel_btf_id;
6113 insn[0].off = ext->ksym.btf_fd_idx;
6114 } else { /* unresolved weak kfunc call */
6115 poison_kfunc_call(prog, i, relo->insn_idx, insn,
6116 relo->ext_idx, ext);
6119 case RELO_SUBPROG_ADDR:
6120 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6121 pr_warn("prog '%s': relo #%d: bad insn\n",
6125 /* handled already */
6128 /* handled already */
6131 /* will be handled by bpf_program_record_relos() */
6134 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6135 prog->name, i, relo->type);
6143 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6144 const struct bpf_program *prog,
6145 const struct btf_ext_info *ext_info,
6146 void **prog_info, __u32 *prog_rec_cnt,
6149 void *copy_start = NULL, *copy_end = NULL;
6150 void *rec, *rec_end, *new_prog_info;
6151 const struct btf_ext_info_sec *sec;
6152 size_t old_sz, new_sz;
6153 int i, sec_num, sec_idx, off_adj;
6156 for_each_btf_ext_sec(ext_info, sec) {
6157 sec_idx = ext_info->sec_idxs[sec_num];
6159 if (prog->sec_idx != sec_idx)
6162 for_each_btf_ext_rec(ext_info, sec, i, rec) {
6163 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6165 if (insn_off < prog->sec_insn_off)
6167 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6172 copy_end = rec + ext_info->rec_size;
6178 /* append func/line info of a given (sub-)program to the main
6179 * program func/line info
6181 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6182 new_sz = old_sz + (copy_end - copy_start);
6183 new_prog_info = realloc(*prog_info, new_sz);
6186 *prog_info = new_prog_info;
6187 *prog_rec_cnt = new_sz / ext_info->rec_size;
6188 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6190 /* Kernel instruction offsets are in units of 8-byte
6191 * instructions, while .BTF.ext instruction offsets generated
6192 * by Clang are in units of bytes. So convert Clang offsets
6193 * into kernel offsets and adjust offset according to program
6194 * relocated position.
6196 off_adj = prog->sub_insn_off - prog->sec_insn_off;
6197 rec = new_prog_info + old_sz;
6198 rec_end = new_prog_info + new_sz;
6199 for (; rec < rec_end; rec += ext_info->rec_size) {
6200 __u32 *insn_off = rec;
6202 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6204 *prog_rec_sz = ext_info->rec_size;
6212 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6213 struct bpf_program *main_prog,
6214 const struct bpf_program *prog)
6218 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6219 * supprot func/line info
6221 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6224 /* only attempt func info relocation if main program's func_info
6225 * relocation was successful
6227 if (main_prog != prog && !main_prog->func_info)
6230 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6231 &main_prog->func_info,
6232 &main_prog->func_info_cnt,
6233 &main_prog->func_info_rec_size);
6235 if (err != -ENOENT) {
6236 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6240 if (main_prog->func_info) {
6242 * Some info has already been found but has problem
6243 * in the last btf_ext reloc. Must have to error out.
6245 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6248 /* Have problem loading the very first info. Ignore the rest. */
6249 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6254 /* don't relocate line info if main program's relocation failed */
6255 if (main_prog != prog && !main_prog->line_info)
6258 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6259 &main_prog->line_info,
6260 &main_prog->line_info_cnt,
6261 &main_prog->line_info_rec_size);
6263 if (err != -ENOENT) {
6264 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6268 if (main_prog->line_info) {
6270 * Some info has already been found but has problem
6271 * in the last btf_ext reloc. Must have to error out.
6273 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6276 /* Have problem loading the very first info. Ignore the rest. */
6277 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6283 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6285 size_t insn_idx = *(const size_t *)key;
6286 const struct reloc_desc *relo = elem;
6288 if (insn_idx == relo->insn_idx)
6290 return insn_idx < relo->insn_idx ? -1 : 1;
6293 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6295 if (!prog->nr_reloc)
6297 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6298 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6301 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6303 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6304 struct reloc_desc *relos;
6307 if (main_prog == subprog)
6309 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6310 /* if new count is zero, reallocarray can return a valid NULL result;
6311 * in this case the previous pointer will be freed, so we *have to*
6312 * reassign old pointer to the new value (even if it's NULL)
6314 if (!relos && new_cnt)
6316 if (subprog->nr_reloc)
6317 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6318 sizeof(*relos) * subprog->nr_reloc);
6320 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6321 relos[i].insn_idx += subprog->sub_insn_off;
6322 /* After insn_idx adjustment the 'relos' array is still sorted
6323 * by insn_idx and doesn't break bsearch.
6325 main_prog->reloc_desc = relos;
6326 main_prog->nr_reloc = new_cnt;
6331 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6332 struct bpf_program *subprog)
6334 struct bpf_insn *insns;
6338 subprog->sub_insn_off = main_prog->insns_cnt;
6340 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6341 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6343 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6346 main_prog->insns = insns;
6347 main_prog->insns_cnt = new_cnt;
6349 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6350 subprog->insns_cnt * sizeof(*insns));
6352 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6353 main_prog->name, subprog->insns_cnt, subprog->name);
6355 /* The subprog insns are now appended. Append its relos too. */
6356 err = append_subprog_relos(main_prog, subprog);
6363 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6364 struct bpf_program *prog)
6366 size_t sub_insn_idx, insn_idx;
6367 struct bpf_program *subprog;
6368 struct reloc_desc *relo;
6369 struct bpf_insn *insn;
6372 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6376 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6377 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6378 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6381 relo = find_prog_insn_relo(prog, insn_idx);
6382 if (relo && relo->type == RELO_EXTERN_CALL)
6383 /* kfunc relocations will be handled later
6384 * in bpf_object__relocate_data()
6387 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6388 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6389 prog->name, insn_idx, relo->type);
6390 return -LIBBPF_ERRNO__RELOC;
6393 /* sub-program instruction index is a combination of
6394 * an offset of a symbol pointed to by relocation and
6395 * call instruction's imm field; for global functions,
6396 * call always has imm = -1, but for static functions
6397 * relocation is against STT_SECTION and insn->imm
6398 * points to a start of a static function
6400 * for subprog addr relocation, the relo->sym_off + insn->imm is
6401 * the byte offset in the corresponding section.
6403 if (relo->type == RELO_CALL)
6404 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6406 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6407 } else if (insn_is_pseudo_func(insn)) {
6409 * RELO_SUBPROG_ADDR relo is always emitted even if both
6410 * functions are in the same section, so it shouldn't reach here.
6412 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6413 prog->name, insn_idx);
6414 return -LIBBPF_ERRNO__RELOC;
6416 /* if subprogram call is to a static function within
6417 * the same ELF section, there won't be any relocation
6418 * emitted, but it also means there is no additional
6419 * offset necessary, insns->imm is relative to
6420 * instruction's original position within the section
6422 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6425 /* we enforce that sub-programs should be in .text section */
6426 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6428 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6430 return -LIBBPF_ERRNO__RELOC;
6433 /* if it's the first call instruction calling into this
6434 * subprogram (meaning this subprog hasn't been processed
6435 * yet) within the context of current main program:
6436 * - append it at the end of main program's instructions blog;
6437 * - process is recursively, while current program is put on hold;
6438 * - if that subprogram calls some other not yet processes
6439 * subprogram, same thing will happen recursively until
6440 * there are no more unprocesses subprograms left to append
6443 if (subprog->sub_insn_off == 0) {
6444 err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6447 err = bpf_object__reloc_code(obj, main_prog, subprog);
6452 /* main_prog->insns memory could have been re-allocated, so
6453 * calculate pointer again
6455 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6456 /* calculate correct instruction position within current main
6457 * prog; each main prog can have a different set of
6458 * subprograms appended (potentially in different order as
6459 * well), so position of any subprog can be different for
6460 * different main programs
6462 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6464 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6465 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6472 * Relocate sub-program calls.
6474 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6475 * main prog) is processed separately. For each subprog (non-entry functions,
6476 * that can be called from either entry progs or other subprogs) gets their
6477 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6478 * hasn't been yet appended and relocated within current main prog. Once its
6479 * relocated, sub_insn_off will point at the position within current main prog
6480 * where given subprog was appended. This will further be used to relocate all
6481 * the call instructions jumping into this subprog.
6483 * We start with main program and process all call instructions. If the call
6484 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6485 * is zero), subprog instructions are appended at the end of main program's
6486 * instruction array. Then main program is "put on hold" while we recursively
6487 * process newly appended subprogram. If that subprogram calls into another
6488 * subprogram that hasn't been appended, new subprogram is appended again to
6489 * the *main* prog's instructions (subprog's instructions are always left
6490 * untouched, as they need to be in unmodified state for subsequent main progs
6491 * and subprog instructions are always sent only as part of a main prog) and
6492 * the process continues recursively. Once all the subprogs called from a main
6493 * prog or any of its subprogs are appended (and relocated), all their
6494 * positions within finalized instructions array are known, so it's easy to
6495 * rewrite call instructions with correct relative offsets, corresponding to
6496 * desired target subprog.
6498 * Its important to realize that some subprogs might not be called from some
6499 * main prog and any of its called/used subprogs. Those will keep their
6500 * subprog->sub_insn_off as zero at all times and won't be appended to current
6501 * main prog and won't be relocated within the context of current main prog.
6502 * They might still be used from other main progs later.
6504 * Visually this process can be shown as below. Suppose we have two main
6505 * programs mainA and mainB and BPF object contains three subprogs: subA,
6506 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6507 * subC both call subB:
6509 * +--------+ +-------+
6511 * +--+---+ +--+-+-+ +---+--+
6512 * | subA | | subB | | subC |
6513 * +--+---+ +------+ +---+--+
6516 * +---+-------+ +------+----+
6517 * | mainA | | mainB |
6518 * +-----------+ +-----------+
6520 * We'll start relocating mainA, will find subA, append it and start
6521 * processing sub A recursively:
6523 * +-----------+------+
6525 * +-----------+------+
6527 * At this point we notice that subB is used from subA, so we append it and
6528 * relocate (there are no further subcalls from subB):
6530 * +-----------+------+------+
6531 * | mainA | subA | subB |
6532 * +-----------+------+------+
6534 * At this point, we relocate subA calls, then go one level up and finish with
6535 * relocatin mainA calls. mainA is done.
6537 * For mainB process is similar but results in different order. We start with
6538 * mainB and skip subA and subB, as mainB never calls them (at least
6539 * directly), but we see subC is needed, so we append and start processing it:
6541 * +-----------+------+
6543 * +-----------+------+
6544 * Now we see subC needs subB, so we go back to it, append and relocate it:
6546 * +-----------+------+------+
6547 * | mainB | subC | subB |
6548 * +-----------+------+------+
6550 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6553 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6555 struct bpf_program *subprog;
6558 /* mark all subprogs as not relocated (yet) within the context of
6559 * current main program
6561 for (i = 0; i < obj->nr_programs; i++) {
6562 subprog = &obj->programs[i];
6563 if (!prog_is_subprog(obj, subprog))
6566 subprog->sub_insn_off = 0;
6569 err = bpf_object__reloc_code(obj, prog, prog);
6577 bpf_object__free_relocs(struct bpf_object *obj)
6579 struct bpf_program *prog;
6582 /* free up relocation descriptors */
6583 for (i = 0; i < obj->nr_programs; i++) {
6584 prog = &obj->programs[i];
6585 zfree(&prog->reloc_desc);
6590 static int cmp_relocs(const void *_a, const void *_b)
6592 const struct reloc_desc *a = _a;
6593 const struct reloc_desc *b = _b;
6595 if (a->insn_idx != b->insn_idx)
6596 return a->insn_idx < b->insn_idx ? -1 : 1;
6598 /* no two relocations should have the same insn_idx, but ... */
6599 if (a->type != b->type)
6600 return a->type < b->type ? -1 : 1;
6605 static void bpf_object__sort_relos(struct bpf_object *obj)
6609 for (i = 0; i < obj->nr_programs; i++) {
6610 struct bpf_program *p = &obj->programs[i];
6615 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6620 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6622 struct bpf_program *prog;
6627 err = bpf_object__relocate_core(obj, targ_btf_path);
6629 pr_warn("failed to perform CO-RE relocations: %d\n",
6633 bpf_object__sort_relos(obj);
6636 /* Before relocating calls pre-process relocations and mark
6637 * few ld_imm64 instructions that points to subprogs.
6638 * Otherwise bpf_object__reloc_code() later would have to consider
6639 * all ld_imm64 insns as relocation candidates. That would
6640 * reduce relocation speed, since amount of find_prog_insn_relo()
6641 * would increase and most of them will fail to find a relo.
6643 for (i = 0; i < obj->nr_programs; i++) {
6644 prog = &obj->programs[i];
6645 for (j = 0; j < prog->nr_reloc; j++) {
6646 struct reloc_desc *relo = &prog->reloc_desc[j];
6647 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6649 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6650 if (relo->type == RELO_SUBPROG_ADDR)
6651 insn[0].src_reg = BPF_PSEUDO_FUNC;
6655 /* relocate subprogram calls and append used subprograms to main
6656 * programs; each copy of subprogram code needs to be relocated
6657 * differently for each main program, because its code location might
6659 * Append subprog relos to main programs to allow data relos to be
6660 * processed after text is completely relocated.
6662 for (i = 0; i < obj->nr_programs; i++) {
6663 prog = &obj->programs[i];
6664 /* sub-program's sub-calls are relocated within the context of
6665 * its main program only
6667 if (prog_is_subprog(obj, prog))
6669 if (!prog->autoload)
6672 err = bpf_object__relocate_calls(obj, prog);
6674 pr_warn("prog '%s': failed to relocate calls: %d\n",
6679 /* Now, also append exception callback if it has not been done already. */
6680 if (prog->exception_cb_idx >= 0) {
6681 struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6683 /* Calling exception callback directly is disallowed, which the
6684 * verifier will reject later. In case it was processed already,
6685 * we can skip this step, otherwise for all other valid cases we
6686 * have to append exception callback now.
6688 if (subprog->sub_insn_off == 0) {
6689 err = bpf_object__append_subprog_code(obj, prog, subprog);
6692 err = bpf_object__reloc_code(obj, prog, subprog);
6698 /* Process data relos for main programs */
6699 for (i = 0; i < obj->nr_programs; i++) {
6700 prog = &obj->programs[i];
6701 if (prog_is_subprog(obj, prog))
6703 if (!prog->autoload)
6705 err = bpf_object__relocate_data(obj, prog);
6707 pr_warn("prog '%s': failed to relocate data references: %d\n",
6716 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6717 Elf64_Shdr *shdr, Elf_Data *data);
6719 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6720 Elf64_Shdr *shdr, Elf_Data *data)
6722 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6723 int i, j, nrels, new_sz;
6724 const struct btf_var_secinfo *vi = NULL;
6725 const struct btf_type *sec, *var, *def;
6726 struct bpf_map *map = NULL, *targ_map = NULL;
6727 struct bpf_program *targ_prog = NULL;
6728 bool is_prog_array, is_map_in_map;
6729 const struct btf_member *member;
6730 const char *name, *mname, *type;
6736 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6738 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6742 nrels = shdr->sh_size / shdr->sh_entsize;
6743 for (i = 0; i < nrels; i++) {
6744 rel = elf_rel_by_idx(data, i);
6746 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6747 return -LIBBPF_ERRNO__FORMAT;
6750 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6752 pr_warn(".maps relo #%d: symbol %zx not found\n",
6753 i, (size_t)ELF64_R_SYM(rel->r_info));
6754 return -LIBBPF_ERRNO__FORMAT;
6756 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6758 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6759 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6760 (size_t)rel->r_offset, sym->st_name, name);
6762 for (j = 0; j < obj->nr_maps; j++) {
6763 map = &obj->maps[j];
6764 if (map->sec_idx != obj->efile.btf_maps_shndx)
6767 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6768 if (vi->offset <= rel->r_offset &&
6769 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6772 if (j == obj->nr_maps) {
6773 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6774 i, name, (size_t)rel->r_offset);
6778 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6779 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6780 type = is_map_in_map ? "map" : "prog";
6781 if (is_map_in_map) {
6782 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6783 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6785 return -LIBBPF_ERRNO__RELOC;
6787 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6788 map->def.key_size != sizeof(int)) {
6789 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6790 i, map->name, sizeof(int));
6793 targ_map = bpf_object__find_map_by_name(obj, name);
6795 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6799 } else if (is_prog_array) {
6800 targ_prog = bpf_object__find_program_by_name(obj, name);
6802 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6806 if (targ_prog->sec_idx != sym->st_shndx ||
6807 targ_prog->sec_insn_off * 8 != sym->st_value ||
6808 prog_is_subprog(obj, targ_prog)) {
6809 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6811 return -LIBBPF_ERRNO__RELOC;
6817 var = btf__type_by_id(obj->btf, vi->type);
6818 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6819 if (btf_vlen(def) == 0)
6821 member = btf_members(def) + btf_vlen(def) - 1;
6822 mname = btf__name_by_offset(obj->btf, member->name_off);
6823 if (strcmp(mname, "values"))
6826 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6827 if (rel->r_offset - vi->offset < moff)
6830 moff = rel->r_offset - vi->offset - moff;
6831 /* here we use BPF pointer size, which is always 64 bit, as we
6832 * are parsing ELF that was built for BPF target
6834 if (moff % bpf_ptr_sz)
6837 if (moff >= map->init_slots_sz) {
6839 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6842 map->init_slots = tmp;
6843 memset(map->init_slots + map->init_slots_sz, 0,
6844 (new_sz - map->init_slots_sz) * host_ptr_sz);
6845 map->init_slots_sz = new_sz;
6847 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6849 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6850 i, map->name, moff, type, name);
6856 static int bpf_object__collect_relos(struct bpf_object *obj)
6860 for (i = 0; i < obj->efile.sec_cnt; i++) {
6861 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6866 if (sec_desc->sec_type != SEC_RELO)
6869 shdr = sec_desc->shdr;
6870 data = sec_desc->data;
6871 idx = shdr->sh_info;
6873 if (shdr->sh_type != SHT_REL) {
6874 pr_warn("internal error at %d\n", __LINE__);
6875 return -LIBBPF_ERRNO__INTERNAL;
6878 if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6879 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6880 else if (idx == obj->efile.btf_maps_shndx)
6881 err = bpf_object__collect_map_relos(obj, shdr, data);
6883 err = bpf_object__collect_prog_relos(obj, shdr, data);
6888 bpf_object__sort_relos(obj);
6892 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6894 if (BPF_CLASS(insn->code) == BPF_JMP &&
6895 BPF_OP(insn->code) == BPF_CALL &&
6896 BPF_SRC(insn->code) == BPF_K &&
6897 insn->src_reg == 0 &&
6898 insn->dst_reg == 0) {
6899 *func_id = insn->imm;
6905 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6907 struct bpf_insn *insn = prog->insns;
6908 enum bpf_func_id func_id;
6911 if (obj->gen_loader)
6914 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6915 if (!insn_is_helper_call(insn, &func_id))
6918 /* on kernels that don't yet support
6919 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6920 * to bpf_probe_read() which works well for old kernels
6923 case BPF_FUNC_probe_read_kernel:
6924 case BPF_FUNC_probe_read_user:
6925 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6926 insn->imm = BPF_FUNC_probe_read;
6928 case BPF_FUNC_probe_read_kernel_str:
6929 case BPF_FUNC_probe_read_user_str:
6930 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6931 insn->imm = BPF_FUNC_probe_read_str;
6940 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6941 int *btf_obj_fd, int *btf_type_id);
6943 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6944 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6945 struct bpf_prog_load_opts *opts, long cookie)
6947 enum sec_def_flags def = cookie;
6949 /* old kernels might not support specifying expected_attach_type */
6950 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6951 opts->expected_attach_type = 0;
6953 if (def & SEC_SLEEPABLE)
6954 opts->prog_flags |= BPF_F_SLEEPABLE;
6956 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6957 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6959 /* special check for usdt to use uprobe_multi link */
6960 if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6961 prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6963 if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6964 int btf_obj_fd = 0, btf_type_id = 0, err;
6965 const char *attach_name;
6967 attach_name = strchr(prog->sec_name, '/');
6969 /* if BPF program is annotated with just SEC("fentry")
6970 * (or similar) without declaratively specifying
6971 * target, then it is expected that target will be
6972 * specified with bpf_program__set_attach_target() at
6973 * runtime before BPF object load step. If not, then
6974 * there is nothing to load into the kernel as BPF
6975 * verifier won't be able to validate BPF program
6976 * correctness anyways.
6978 pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6982 attach_name++; /* skip over / */
6984 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6988 /* cache resolved BTF FD and BTF type ID in the prog */
6989 prog->attach_btf_obj_fd = btf_obj_fd;
6990 prog->attach_btf_id = btf_type_id;
6992 /* but by now libbpf common logic is not utilizing
6993 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6994 * this callback is called after opts were populated by
6995 * libbpf, so this callback has to update opts explicitly here
6997 opts->attach_btf_obj_fd = btf_obj_fd;
6998 opts->attach_btf_id = btf_type_id;
7003 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7005 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7006 struct bpf_insn *insns, int insns_cnt,
7007 const char *license, __u32 kern_version, int *prog_fd)
7009 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7010 const char *prog_name = NULL;
7011 char *cp, errmsg[STRERR_BUFSIZE];
7012 size_t log_buf_size = 0;
7013 char *log_buf = NULL, *tmp;
7014 int btf_fd, ret, err;
7015 bool own_log_buf = true;
7016 __u32 log_level = prog->log_level;
7018 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7020 * The program type must be set. Most likely we couldn't find a proper
7021 * section definition at load time, and thus we didn't infer the type.
7023 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7024 prog->name, prog->sec_name);
7028 if (!insns || !insns_cnt)
7031 if (kernel_supports(obj, FEAT_PROG_NAME))
7032 prog_name = prog->name;
7033 load_attr.attach_prog_fd = prog->attach_prog_fd;
7034 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7035 load_attr.attach_btf_id = prog->attach_btf_id;
7036 load_attr.kern_version = kern_version;
7037 load_attr.prog_ifindex = prog->prog_ifindex;
7039 /* specify func_info/line_info only if kernel supports them */
7040 btf_fd = bpf_object__btf_fd(obj);
7041 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7042 load_attr.prog_btf_fd = btf_fd;
7043 load_attr.func_info = prog->func_info;
7044 load_attr.func_info_rec_size = prog->func_info_rec_size;
7045 load_attr.func_info_cnt = prog->func_info_cnt;
7046 load_attr.line_info = prog->line_info;
7047 load_attr.line_info_rec_size = prog->line_info_rec_size;
7048 load_attr.line_info_cnt = prog->line_info_cnt;
7050 load_attr.log_level = log_level;
7051 load_attr.prog_flags = prog->prog_flags;
7052 load_attr.fd_array = obj->fd_array;
7054 /* adjust load_attr if sec_def provides custom preload callback */
7055 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7056 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7058 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7062 insns = prog->insns;
7063 insns_cnt = prog->insns_cnt;
7066 /* allow prog_prepare_load_fn to change expected_attach_type */
7067 load_attr.expected_attach_type = prog->expected_attach_type;
7069 if (obj->gen_loader) {
7070 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7071 license, insns, insns_cnt, &load_attr,
7072 prog - obj->programs);
7078 /* if log_level is zero, we don't request logs initially even if
7079 * custom log_buf is specified; if the program load fails, then we'll
7080 * bump log_level to 1 and use either custom log_buf or we'll allocate
7081 * our own and retry the load to get details on what failed
7084 if (prog->log_buf) {
7085 log_buf = prog->log_buf;
7086 log_buf_size = prog->log_size;
7087 own_log_buf = false;
7088 } else if (obj->log_buf) {
7089 log_buf = obj->log_buf;
7090 log_buf_size = obj->log_size;
7091 own_log_buf = false;
7093 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7094 tmp = realloc(log_buf, log_buf_size);
7105 load_attr.log_buf = log_buf;
7106 load_attr.log_size = log_buf_size;
7107 load_attr.log_level = log_level;
7109 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7111 if (log_level && own_log_buf) {
7112 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7113 prog->name, log_buf);
7116 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7117 struct bpf_map *map;
7120 for (i = 0; i < obj->nr_maps; i++) {
7121 map = &prog->obj->maps[i];
7122 if (map->libbpf_type != LIBBPF_MAP_RODATA)
7125 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7126 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7127 pr_warn("prog '%s': failed to bind map '%s': %s\n",
7128 prog->name, map->real_name, cp);
7129 /* Don't fail hard if can't bind rodata. */
7139 if (log_level == 0) {
7143 /* On ENOSPC, increase log buffer size and retry, unless custom
7144 * log_buf is specified.
7145 * Be careful to not overflow u32, though. Kernel's log buf size limit
7146 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7147 * multiply by 2 unless we are sure we'll fit within 32 bits.
7148 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7150 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7155 /* post-process verifier log to improve error descriptions */
7156 fixup_verifier_log(prog, log_buf, log_buf_size);
7158 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7159 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7162 if (own_log_buf && log_buf && log_buf[0] != '\0') {
7163 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7164 prog->name, log_buf);
7173 static char *find_prev_line(char *buf, char *cur)
7177 if (cur == buf) /* end of a log buf */
7181 while (p - 1 >= buf && *(p - 1) != '\n')
7187 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7188 char *orig, size_t orig_sz, const char *patch)
7190 /* size of the remaining log content to the right from the to-be-replaced part */
7191 size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7192 size_t patch_sz = strlen(patch);
7194 if (patch_sz != orig_sz) {
7195 /* If patch line(s) are longer than original piece of verifier log,
7196 * shift log contents by (patch_sz - orig_sz) bytes to the right
7197 * starting from after to-be-replaced part of the log.
7199 * If patch line(s) are shorter than original piece of verifier log,
7200 * shift log contents by (orig_sz - patch_sz) bytes to the left
7201 * starting from after to-be-replaced part of the log
7203 * We need to be careful about not overflowing available
7204 * buf_sz capacity. If that's the case, we'll truncate the end
7205 * of the original log, as necessary.
7207 if (patch_sz > orig_sz) {
7208 if (orig + patch_sz >= buf + buf_sz) {
7209 /* patch is big enough to cover remaining space completely */
7210 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7212 } else if (patch_sz - orig_sz > buf_sz - log_sz) {
7213 /* patch causes part of remaining log to be truncated */
7214 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7217 /* shift remaining log to the right by calculated amount */
7218 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7221 memcpy(orig, patch, patch_sz);
7224 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7225 char *buf, size_t buf_sz, size_t log_sz,
7226 char *line1, char *line2, char *line3)
7228 /* Expected log for failed and not properly guarded CO-RE relocation:
7229 * line1 -> 123: (85) call unknown#195896080
7230 * line2 -> invalid func unknown#195896080
7231 * line3 -> <anything else or end of buffer>
7233 * "123" is the index of the instruction that was poisoned. We extract
7234 * instruction index to find corresponding CO-RE relocation and
7235 * replace this part of the log with more relevant information about
7236 * failed CO-RE relocation.
7238 const struct bpf_core_relo *relo;
7239 struct bpf_core_spec spec;
7240 char patch[512], spec_buf[256];
7241 int insn_idx, err, spec_len;
7243 if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7246 relo = find_relo_core(prog, insn_idx);
7250 err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7254 spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7255 snprintf(patch, sizeof(patch),
7256 "%d: <invalid CO-RE relocation>\n"
7257 "failed to resolve CO-RE relocation %s%s\n",
7258 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7260 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7263 static void fixup_log_missing_map_load(struct bpf_program *prog,
7264 char *buf, size_t buf_sz, size_t log_sz,
7265 char *line1, char *line2, char *line3)
7267 /* Expected log for failed and not properly guarded map reference:
7268 * line1 -> 123: (85) call unknown#2001000345
7269 * line2 -> invalid func unknown#2001000345
7270 * line3 -> <anything else or end of buffer>
7272 * "123" is the index of the instruction that was poisoned.
7273 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7275 struct bpf_object *obj = prog->obj;
7276 const struct bpf_map *map;
7277 int insn_idx, map_idx;
7280 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7283 map_idx -= POISON_LDIMM64_MAP_BASE;
7284 if (map_idx < 0 || map_idx >= obj->nr_maps)
7286 map = &obj->maps[map_idx];
7288 snprintf(patch, sizeof(patch),
7289 "%d: <invalid BPF map reference>\n"
7290 "BPF map '%s' is referenced but wasn't created\n",
7291 insn_idx, map->name);
7293 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7296 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7297 char *buf, size_t buf_sz, size_t log_sz,
7298 char *line1, char *line2, char *line3)
7300 /* Expected log for failed and not properly guarded kfunc call:
7301 * line1 -> 123: (85) call unknown#2002000345
7302 * line2 -> invalid func unknown#2002000345
7303 * line3 -> <anything else or end of buffer>
7305 * "123" is the index of the instruction that was poisoned.
7306 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7308 struct bpf_object *obj = prog->obj;
7309 const struct extern_desc *ext;
7310 int insn_idx, ext_idx;
7313 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7316 ext_idx -= POISON_CALL_KFUNC_BASE;
7317 if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7319 ext = &obj->externs[ext_idx];
7321 snprintf(patch, sizeof(patch),
7322 "%d: <invalid kfunc call>\n"
7323 "kfunc '%s' is referenced but wasn't resolved\n",
7324 insn_idx, ext->name);
7326 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7329 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7331 /* look for familiar error patterns in last N lines of the log */
7332 const size_t max_last_line_cnt = 10;
7333 char *prev_line, *cur_line, *next_line;
7340 log_sz = strlen(buf) + 1;
7341 next_line = buf + log_sz - 1;
7343 for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7344 cur_line = find_prev_line(buf, next_line);
7348 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7349 prev_line = find_prev_line(buf, cur_line);
7353 /* failed CO-RE relocation case */
7354 fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7355 prev_line, cur_line, next_line);
7357 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7358 prev_line = find_prev_line(buf, cur_line);
7362 /* reference to uncreated BPF map */
7363 fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7364 prev_line, cur_line, next_line);
7366 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7367 prev_line = find_prev_line(buf, cur_line);
7371 /* reference to unresolved kfunc */
7372 fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7373 prev_line, cur_line, next_line);
7379 static int bpf_program_record_relos(struct bpf_program *prog)
7381 struct bpf_object *obj = prog->obj;
7384 for (i = 0; i < prog->nr_reloc; i++) {
7385 struct reloc_desc *relo = &prog->reloc_desc[i];
7386 struct extern_desc *ext = &obj->externs[relo->ext_idx];
7389 switch (relo->type) {
7390 case RELO_EXTERN_LD64:
7391 if (ext->type != EXT_KSYM)
7393 kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7394 BTF_KIND_VAR : BTF_KIND_FUNC;
7395 bpf_gen__record_extern(obj->gen_loader, ext->name,
7396 ext->is_weak, !ext->ksym.type_id,
7397 true, kind, relo->insn_idx);
7399 case RELO_EXTERN_CALL:
7400 bpf_gen__record_extern(obj->gen_loader, ext->name,
7401 ext->is_weak, false, false, BTF_KIND_FUNC,
7405 struct bpf_core_relo cr = {
7406 .insn_off = relo->insn_idx * 8,
7407 .type_id = relo->core_relo->type_id,
7408 .access_str_off = relo->core_relo->access_str_off,
7409 .kind = relo->core_relo->kind,
7412 bpf_gen__record_relo_core(obj->gen_loader, &cr);
7423 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7425 struct bpf_program *prog;
7429 for (i = 0; i < obj->nr_programs; i++) {
7430 prog = &obj->programs[i];
7431 err = bpf_object__sanitize_prog(obj, prog);
7436 for (i = 0; i < obj->nr_programs; i++) {
7437 prog = &obj->programs[i];
7438 if (prog_is_subprog(obj, prog))
7440 if (!prog->autoload) {
7441 pr_debug("prog '%s': skipped loading\n", prog->name);
7444 prog->log_level |= log_level;
7446 if (obj->gen_loader)
7447 bpf_program_record_relos(prog);
7449 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7450 obj->license, obj->kern_version, &prog->fd);
7452 pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7457 bpf_object__free_relocs(obj);
7461 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7463 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7465 struct bpf_program *prog;
7468 bpf_object__for_each_program(prog, obj) {
7469 prog->sec_def = find_sec_def(prog->sec_name);
7470 if (!prog->sec_def) {
7471 /* couldn't guess, but user might manually specify */
7472 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7473 prog->name, prog->sec_name);
7477 prog->type = prog->sec_def->prog_type;
7478 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7480 /* sec_def can have custom callback which should be called
7481 * after bpf_program is initialized to adjust its properties
7483 if (prog->sec_def->prog_setup_fn) {
7484 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7486 pr_warn("prog '%s': failed to initialize: %d\n",
7496 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7497 const struct bpf_object_open_opts *opts)
7499 const char *obj_name, *kconfig, *btf_tmp_path;
7500 struct bpf_object *obj;
7507 if (elf_version(EV_CURRENT) == EV_NONE) {
7508 pr_warn("failed to init libelf for %s\n",
7509 path ? : "(mem buf)");
7510 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7513 if (!OPTS_VALID(opts, bpf_object_open_opts))
7514 return ERR_PTR(-EINVAL);
7516 obj_name = OPTS_GET(opts, object_name, NULL);
7519 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7520 (unsigned long)obj_buf,
7521 (unsigned long)obj_buf_sz);
7522 obj_name = tmp_name;
7525 pr_debug("loading object '%s' from buffer\n", obj_name);
7528 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7529 log_size = OPTS_GET(opts, kernel_log_size, 0);
7530 log_level = OPTS_GET(opts, kernel_log_level, 0);
7531 if (log_size > UINT_MAX)
7532 return ERR_PTR(-EINVAL);
7533 if (log_size && !log_buf)
7534 return ERR_PTR(-EINVAL);
7536 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7540 obj->log_buf = log_buf;
7541 obj->log_size = log_size;
7542 obj->log_level = log_level;
7544 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7546 if (strlen(btf_tmp_path) >= PATH_MAX) {
7547 err = -ENAMETOOLONG;
7550 obj->btf_custom_path = strdup(btf_tmp_path);
7551 if (!obj->btf_custom_path) {
7557 kconfig = OPTS_GET(opts, kconfig, NULL);
7559 obj->kconfig = strdup(kconfig);
7560 if (!obj->kconfig) {
7566 err = bpf_object__elf_init(obj);
7567 err = err ? : bpf_object__check_endianness(obj);
7568 err = err ? : bpf_object__elf_collect(obj);
7569 err = err ? : bpf_object__collect_externs(obj);
7570 err = err ? : bpf_object_fixup_btf(obj);
7571 err = err ? : bpf_object__init_maps(obj, opts);
7572 err = err ? : bpf_object_init_progs(obj, opts);
7573 err = err ? : bpf_object__collect_relos(obj);
7577 bpf_object__elf_finish(obj);
7581 bpf_object__close(obj);
7582 return ERR_PTR(err);
7586 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7589 return libbpf_err_ptr(-EINVAL);
7591 pr_debug("loading %s\n", path);
7593 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7596 struct bpf_object *bpf_object__open(const char *path)
7598 return bpf_object__open_file(path, NULL);
7602 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7603 const struct bpf_object_open_opts *opts)
7605 if (!obj_buf || obj_buf_sz == 0)
7606 return libbpf_err_ptr(-EINVAL);
7608 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7611 static int bpf_object_unload(struct bpf_object *obj)
7616 return libbpf_err(-EINVAL);
7618 for (i = 0; i < obj->nr_maps; i++) {
7619 zclose(obj->maps[i].fd);
7620 if (obj->maps[i].st_ops)
7621 zfree(&obj->maps[i].st_ops->kern_vdata);
7624 for (i = 0; i < obj->nr_programs; i++)
7625 bpf_program__unload(&obj->programs[i]);
7630 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7634 bpf_object__for_each_map(m, obj) {
7635 if (!bpf_map__is_internal(m))
7637 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7638 m->def.map_flags &= ~BPF_F_MMAPABLE;
7644 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7646 char sym_type, sym_name[500];
7647 unsigned long long sym_addr;
7651 f = fopen("/proc/kallsyms", "re");
7654 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7659 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7660 &sym_addr, &sym_type, sym_name);
7661 if (ret == EOF && feof(f))
7664 pr_warn("failed to read kallsyms entry: %d\n", ret);
7669 err = cb(sym_addr, sym_type, sym_name, ctx);
7678 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7679 const char *sym_name, void *ctx)
7681 struct bpf_object *obj = ctx;
7682 const struct btf_type *t;
7683 struct extern_desc *ext;
7685 ext = find_extern_by_name(obj, sym_name);
7686 if (!ext || ext->type != EXT_KSYM)
7689 t = btf__type_by_id(obj->btf, ext->btf_id);
7693 if (ext->is_set && ext->ksym.addr != sym_addr) {
7694 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7695 sym_name, ext->ksym.addr, sym_addr);
7700 ext->ksym.addr = sym_addr;
7701 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7706 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7708 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7711 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7712 __u16 kind, struct btf **res_btf,
7713 struct module_btf **res_mod_btf)
7715 struct module_btf *mod_btf;
7719 btf = obj->btf_vmlinux;
7721 id = btf__find_by_name_kind(btf, ksym_name, kind);
7723 if (id == -ENOENT) {
7724 err = load_module_btfs(obj);
7728 for (i = 0; i < obj->btf_module_cnt; i++) {
7729 /* we assume module_btf's BTF FD is always >0 */
7730 mod_btf = &obj->btf_modules[i];
7732 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7741 *res_mod_btf = mod_btf;
7745 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7746 struct extern_desc *ext)
7748 const struct btf_type *targ_var, *targ_type;
7749 __u32 targ_type_id, local_type_id;
7750 struct module_btf *mod_btf = NULL;
7751 const char *targ_var_name;
7752 struct btf *btf = NULL;
7755 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7757 if (id == -ESRCH && ext->is_weak)
7759 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7764 /* find local type_id */
7765 local_type_id = ext->ksym.type_id;
7767 /* find target type_id */
7768 targ_var = btf__type_by_id(btf, id);
7769 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7770 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7772 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7775 const struct btf_type *local_type;
7776 const char *targ_name, *local_name;
7778 local_type = btf__type_by_id(obj->btf, local_type_id);
7779 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7780 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7782 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7783 ext->name, local_type_id,
7784 btf_kind_str(local_type), local_name, targ_type_id,
7785 btf_kind_str(targ_type), targ_name);
7790 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7791 ext->ksym.kernel_btf_id = id;
7792 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7793 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7798 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7799 struct extern_desc *ext)
7801 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7802 struct module_btf *mod_btf = NULL;
7803 const struct btf_type *kern_func;
7804 struct btf *kern_btf = NULL;
7807 local_func_proto_id = ext->ksym.type_id;
7809 kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7812 if (kfunc_id == -ESRCH && ext->is_weak)
7814 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7819 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7820 kfunc_proto_id = kern_func->type;
7822 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7823 kern_btf, kfunc_proto_id);
7828 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7829 ext->name, local_func_proto_id,
7830 mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7834 /* set index for module BTF fd in fd_array, if unset */
7835 if (mod_btf && !mod_btf->fd_array_idx) {
7836 /* insn->off is s16 */
7837 if (obj->fd_array_cnt == INT16_MAX) {
7838 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7839 ext->name, mod_btf->fd_array_idx);
7842 /* Cannot use index 0 for module BTF fd */
7843 if (!obj->fd_array_cnt)
7844 obj->fd_array_cnt = 1;
7846 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7847 obj->fd_array_cnt + 1);
7850 mod_btf->fd_array_idx = obj->fd_array_cnt;
7851 /* we assume module BTF FD is always >0 */
7852 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7856 ext->ksym.kernel_btf_id = kfunc_id;
7857 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7858 /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7859 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7860 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7861 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7863 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7864 pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7865 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7870 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7872 const struct btf_type *t;
7873 struct extern_desc *ext;
7876 for (i = 0; i < obj->nr_extern; i++) {
7877 ext = &obj->externs[i];
7878 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7881 if (obj->gen_loader) {
7883 ext->ksym.kernel_btf_obj_fd = 0;
7884 ext->ksym.kernel_btf_id = 0;
7887 t = btf__type_by_id(obj->btf, ext->btf_id);
7889 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7891 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7898 static int bpf_object__resolve_externs(struct bpf_object *obj,
7899 const char *extra_kconfig)
7901 bool need_config = false, need_kallsyms = false;
7902 bool need_vmlinux_btf = false;
7903 struct extern_desc *ext;
7904 void *kcfg_data = NULL;
7907 if (obj->nr_extern == 0)
7910 if (obj->kconfig_map_idx >= 0)
7911 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7913 for (i = 0; i < obj->nr_extern; i++) {
7914 ext = &obj->externs[i];
7916 if (ext->type == EXT_KSYM) {
7917 if (ext->ksym.type_id)
7918 need_vmlinux_btf = true;
7920 need_kallsyms = true;
7922 } else if (ext->type == EXT_KCFG) {
7923 void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7926 /* Kconfig externs need actual /proc/config.gz */
7927 if (str_has_pfx(ext->name, "CONFIG_")) {
7932 /* Virtual kcfg externs are customly handled by libbpf */
7933 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7934 value = get_kernel_version();
7936 pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7939 } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7940 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7941 } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7942 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7943 } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7944 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7945 * __kconfig externs, where LINUX_ ones are virtual and filled out
7946 * customly by libbpf (their values don't come from Kconfig).
7947 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7948 * __weak, it defaults to zero value, just like for CONFIG_xxx
7951 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7955 err = set_kcfg_value_num(ext, ext_ptr, value);
7958 pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7959 ext->name, (long long)value);
7961 pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7965 if (need_config && extra_kconfig) {
7966 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7969 need_config = false;
7970 for (i = 0; i < obj->nr_extern; i++) {
7971 ext = &obj->externs[i];
7972 if (ext->type == EXT_KCFG && !ext->is_set) {
7979 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7983 if (need_kallsyms) {
7984 err = bpf_object__read_kallsyms_file(obj);
7988 if (need_vmlinux_btf) {
7989 err = bpf_object__resolve_ksyms_btf_id(obj);
7993 for (i = 0; i < obj->nr_extern; i++) {
7994 ext = &obj->externs[i];
7996 if (!ext->is_set && !ext->is_weak) {
7997 pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7999 } else if (!ext->is_set) {
8000 pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8008 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8010 struct bpf_struct_ops *st_ops;
8013 st_ops = map->st_ops;
8014 for (i = 0; i < btf_vlen(st_ops->type); i++) {
8015 struct bpf_program *prog = st_ops->progs[i];
8022 prog_fd = bpf_program__fd(prog);
8023 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8024 *(unsigned long *)kern_data = prog_fd;
8028 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8032 for (i = 0; i < obj->nr_maps; i++)
8033 if (bpf_map__is_struct_ops(&obj->maps[i]))
8034 bpf_map_prepare_vdata(&obj->maps[i]);
8039 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8044 return libbpf_err(-EINVAL);
8047 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8048 return libbpf_err(-EINVAL);
8051 if (obj->gen_loader)
8052 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8054 err = bpf_object__probe_loading(obj);
8055 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8056 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8057 err = err ? : bpf_object__sanitize_and_load_btf(obj);
8058 err = err ? : bpf_object__sanitize_maps(obj);
8059 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8060 err = err ? : bpf_object__create_maps(obj);
8061 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8062 err = err ? : bpf_object__load_progs(obj, extra_log_level);
8063 err = err ? : bpf_object_init_prog_arrays(obj);
8064 err = err ? : bpf_object_prepare_struct_ops(obj);
8066 if (obj->gen_loader) {
8069 btf__set_fd(obj->btf, -1);
8070 for (i = 0; i < obj->nr_maps; i++)
8071 obj->maps[i].fd = -1;
8073 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8076 /* clean up fd_array */
8077 zfree(&obj->fd_array);
8079 /* clean up module BTFs */
8080 for (i = 0; i < obj->btf_module_cnt; i++) {
8081 close(obj->btf_modules[i].fd);
8082 btf__free(obj->btf_modules[i].btf);
8083 free(obj->btf_modules[i].name);
8085 free(obj->btf_modules);
8087 /* clean up vmlinux BTF */
8088 btf__free(obj->btf_vmlinux);
8089 obj->btf_vmlinux = NULL;
8091 obj->loaded = true; /* doesn't matter if successfully or not */
8098 /* unpin any maps that were auto-pinned during load */
8099 for (i = 0; i < obj->nr_maps; i++)
8100 if (obj->maps[i].pinned && !obj->maps[i].reused)
8101 bpf_map__unpin(&obj->maps[i], NULL);
8103 bpf_object_unload(obj);
8104 pr_warn("failed to load object '%s'\n", obj->path);
8105 return libbpf_err(err);
8108 int bpf_object__load(struct bpf_object *obj)
8110 return bpf_object_load(obj, 0, NULL);
8113 static int make_parent_dir(const char *path)
8115 char *cp, errmsg[STRERR_BUFSIZE];
8119 dname = strdup(path);
8123 dir = dirname(dname);
8124 if (mkdir(dir, 0700) && errno != EEXIST)
8129 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8130 pr_warn("failed to mkdir %s: %s\n", path, cp);
8135 static int check_path(const char *path)
8137 char *cp, errmsg[STRERR_BUFSIZE];
8138 struct statfs st_fs;
8145 dname = strdup(path);
8149 dir = dirname(dname);
8150 if (statfs(dir, &st_fs)) {
8151 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8152 pr_warn("failed to statfs %s: %s\n", dir, cp);
8157 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8158 pr_warn("specified path %s is not on BPF FS\n", path);
8165 int bpf_program__pin(struct bpf_program *prog, const char *path)
8167 char *cp, errmsg[STRERR_BUFSIZE];
8171 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8172 return libbpf_err(-EINVAL);
8175 err = make_parent_dir(path);
8177 return libbpf_err(err);
8179 err = check_path(path);
8181 return libbpf_err(err);
8183 if (bpf_obj_pin(prog->fd, path)) {
8185 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8186 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8187 return libbpf_err(err);
8190 pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8194 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8199 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8200 return libbpf_err(-EINVAL);
8203 err = check_path(path);
8205 return libbpf_err(err);
8209 return libbpf_err(-errno);
8211 pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8215 int bpf_map__pin(struct bpf_map *map, const char *path)
8217 char *cp, errmsg[STRERR_BUFSIZE];
8221 pr_warn("invalid map pointer\n");
8222 return libbpf_err(-EINVAL);
8225 if (map->pin_path) {
8226 if (path && strcmp(path, map->pin_path)) {
8227 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8228 bpf_map__name(map), map->pin_path, path);
8229 return libbpf_err(-EINVAL);
8230 } else if (map->pinned) {
8231 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8232 bpf_map__name(map), map->pin_path);
8237 pr_warn("missing a path to pin map '%s' at\n",
8238 bpf_map__name(map));
8239 return libbpf_err(-EINVAL);
8240 } else if (map->pinned) {
8241 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8242 return libbpf_err(-EEXIST);
8245 map->pin_path = strdup(path);
8246 if (!map->pin_path) {
8252 err = make_parent_dir(map->pin_path);
8254 return libbpf_err(err);
8256 err = check_path(map->pin_path);
8258 return libbpf_err(err);
8260 if (bpf_obj_pin(map->fd, map->pin_path)) {
8266 pr_debug("pinned map '%s'\n", map->pin_path);
8271 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8272 pr_warn("failed to pin map: %s\n", cp);
8273 return libbpf_err(err);
8276 int bpf_map__unpin(struct bpf_map *map, const char *path)
8281 pr_warn("invalid map pointer\n");
8282 return libbpf_err(-EINVAL);
8285 if (map->pin_path) {
8286 if (path && strcmp(path, map->pin_path)) {
8287 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8288 bpf_map__name(map), map->pin_path, path);
8289 return libbpf_err(-EINVAL);
8291 path = map->pin_path;
8293 pr_warn("no path to unpin map '%s' from\n",
8294 bpf_map__name(map));
8295 return libbpf_err(-EINVAL);
8298 err = check_path(path);
8300 return libbpf_err(err);
8304 return libbpf_err(-errno);
8306 map->pinned = false;
8307 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8312 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8319 return libbpf_err(-errno);
8322 free(map->pin_path);
8323 map->pin_path = new;
8327 __alias(bpf_map__pin_path)
8328 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8330 const char *bpf_map__pin_path(const struct bpf_map *map)
8332 return map->pin_path;
8335 bool bpf_map__is_pinned(const struct bpf_map *map)
8340 static void sanitize_pin_path(char *s)
8342 /* bpffs disallows periods in path names */
8350 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8352 struct bpf_map *map;
8356 return libbpf_err(-ENOENT);
8359 pr_warn("object not yet loaded; load it first\n");
8360 return libbpf_err(-ENOENT);
8363 bpf_object__for_each_map(map, obj) {
8364 char *pin_path = NULL;
8367 if (!map->autocreate)
8371 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8373 goto err_unpin_maps;
8374 sanitize_pin_path(buf);
8376 } else if (!map->pin_path) {
8380 err = bpf_map__pin(map, pin_path);
8382 goto err_unpin_maps;
8388 while ((map = bpf_object__prev_map(obj, map))) {
8392 bpf_map__unpin(map, NULL);
8395 return libbpf_err(err);
8398 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8400 struct bpf_map *map;
8404 return libbpf_err(-ENOENT);
8406 bpf_object__for_each_map(map, obj) {
8407 char *pin_path = NULL;
8411 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8413 return libbpf_err(err);
8414 sanitize_pin_path(buf);
8416 } else if (!map->pin_path) {
8420 err = bpf_map__unpin(map, pin_path);
8422 return libbpf_err(err);
8428 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8430 struct bpf_program *prog;
8435 return libbpf_err(-ENOENT);
8438 pr_warn("object not yet loaded; load it first\n");
8439 return libbpf_err(-ENOENT);
8442 bpf_object__for_each_program(prog, obj) {
8443 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8445 goto err_unpin_programs;
8447 err = bpf_program__pin(prog, buf);
8449 goto err_unpin_programs;
8455 while ((prog = bpf_object__prev_program(obj, prog))) {
8456 if (pathname_concat(buf, sizeof(buf), path, prog->name))
8459 bpf_program__unpin(prog, buf);
8462 return libbpf_err(err);
8465 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8467 struct bpf_program *prog;
8471 return libbpf_err(-ENOENT);
8473 bpf_object__for_each_program(prog, obj) {
8476 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8478 return libbpf_err(err);
8480 err = bpf_program__unpin(prog, buf);
8482 return libbpf_err(err);
8488 int bpf_object__pin(struct bpf_object *obj, const char *path)
8492 err = bpf_object__pin_maps(obj, path);
8494 return libbpf_err(err);
8496 err = bpf_object__pin_programs(obj, path);
8498 bpf_object__unpin_maps(obj, path);
8499 return libbpf_err(err);
8505 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8509 err = bpf_object__unpin_programs(obj, path);
8511 return libbpf_err(err);
8513 err = bpf_object__unpin_maps(obj, path);
8515 return libbpf_err(err);
8520 static void bpf_map__destroy(struct bpf_map *map)
8522 if (map->inner_map) {
8523 bpf_map__destroy(map->inner_map);
8524 zfree(&map->inner_map);
8527 zfree(&map->init_slots);
8528 map->init_slots_sz = 0;
8533 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8534 munmap(map->mmaped, mmap_sz);
8539 zfree(&map->st_ops->data);
8540 zfree(&map->st_ops->progs);
8541 zfree(&map->st_ops->kern_func_off);
8542 zfree(&map->st_ops);
8546 zfree(&map->real_name);
8547 zfree(&map->pin_path);
8553 void bpf_object__close(struct bpf_object *obj)
8557 if (IS_ERR_OR_NULL(obj))
8560 usdt_manager_free(obj->usdt_man);
8561 obj->usdt_man = NULL;
8563 bpf_gen__free(obj->gen_loader);
8564 bpf_object__elf_finish(obj);
8565 bpf_object_unload(obj);
8566 btf__free(obj->btf);
8567 btf__free(obj->btf_vmlinux);
8568 btf_ext__free(obj->btf_ext);
8570 for (i = 0; i < obj->nr_maps; i++)
8571 bpf_map__destroy(&obj->maps[i]);
8573 zfree(&obj->btf_custom_path);
8574 zfree(&obj->kconfig);
8576 for (i = 0; i < obj->nr_extern; i++)
8577 zfree(&obj->externs[i].essent_name);
8579 zfree(&obj->externs);
8585 if (obj->programs && obj->nr_programs) {
8586 for (i = 0; i < obj->nr_programs; i++)
8587 bpf_program__exit(&obj->programs[i]);
8589 zfree(&obj->programs);
8594 const char *bpf_object__name(const struct bpf_object *obj)
8596 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8599 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8601 return obj ? obj->kern_version : 0;
8604 struct btf *bpf_object__btf(const struct bpf_object *obj)
8606 return obj ? obj->btf : NULL;
8609 int bpf_object__btf_fd(const struct bpf_object *obj)
8611 return obj->btf ? btf__fd(obj->btf) : -1;
8614 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8617 return libbpf_err(-EINVAL);
8619 obj->kern_version = kern_version;
8624 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8626 struct bpf_gen *gen;
8630 if (!OPTS_VALID(opts, gen_loader_opts))
8632 gen = calloc(sizeof(*gen), 1);
8636 obj->gen_loader = gen;
8640 static struct bpf_program *
8641 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8644 size_t nr_programs = obj->nr_programs;
8651 /* Iter from the beginning */
8652 return forward ? &obj->programs[0] :
8653 &obj->programs[nr_programs - 1];
8655 if (p->obj != obj) {
8656 pr_warn("error: program handler doesn't match object\n");
8657 return errno = EINVAL, NULL;
8660 idx = (p - obj->programs) + (forward ? 1 : -1);
8661 if (idx >= obj->nr_programs || idx < 0)
8663 return &obj->programs[idx];
8666 struct bpf_program *
8667 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8669 struct bpf_program *prog = prev;
8672 prog = __bpf_program__iter(prog, obj, true);
8673 } while (prog && prog_is_subprog(obj, prog));
8678 struct bpf_program *
8679 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8681 struct bpf_program *prog = next;
8684 prog = __bpf_program__iter(prog, obj, false);
8685 } while (prog && prog_is_subprog(obj, prog));
8690 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8692 prog->prog_ifindex = ifindex;
8695 const char *bpf_program__name(const struct bpf_program *prog)
8700 const char *bpf_program__section_name(const struct bpf_program *prog)
8702 return prog->sec_name;
8705 bool bpf_program__autoload(const struct bpf_program *prog)
8707 return prog->autoload;
8710 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8712 if (prog->obj->loaded)
8713 return libbpf_err(-EINVAL);
8715 prog->autoload = autoload;
8719 bool bpf_program__autoattach(const struct bpf_program *prog)
8721 return prog->autoattach;
8724 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8726 prog->autoattach = autoattach;
8729 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8734 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8736 return prog->insns_cnt;
8739 int bpf_program__set_insns(struct bpf_program *prog,
8740 struct bpf_insn *new_insns, size_t new_insn_cnt)
8742 struct bpf_insn *insns;
8744 if (prog->obj->loaded)
8747 insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8748 /* NULL is a valid return from reallocarray if the new count is zero */
8749 if (!insns && new_insn_cnt) {
8750 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8753 memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8755 prog->insns = insns;
8756 prog->insns_cnt = new_insn_cnt;
8760 int bpf_program__fd(const struct bpf_program *prog)
8763 return libbpf_err(-EINVAL);
8766 return libbpf_err(-ENOENT);
8771 __alias(bpf_program__type)
8772 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8774 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8779 static size_t custom_sec_def_cnt;
8780 static struct bpf_sec_def *custom_sec_defs;
8781 static struct bpf_sec_def custom_fallback_def;
8782 static bool has_custom_fallback_def;
8783 static int last_custom_sec_def_handler_id;
8785 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8787 if (prog->obj->loaded)
8788 return libbpf_err(-EBUSY);
8790 /* if type is not changed, do nothing */
8791 if (prog->type == type)
8796 /* If a program type was changed, we need to reset associated SEC()
8797 * handler, as it will be invalid now. The only exception is a generic
8798 * fallback handler, which by definition is program type-agnostic and
8799 * is a catch-all custom handler, optionally set by the application,
8800 * so should be able to handle any type of BPF program.
8802 if (prog->sec_def != &custom_fallback_def)
8803 prog->sec_def = NULL;
8807 __alias(bpf_program__expected_attach_type)
8808 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8810 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8812 return prog->expected_attach_type;
8815 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8816 enum bpf_attach_type type)
8818 if (prog->obj->loaded)
8819 return libbpf_err(-EBUSY);
8821 prog->expected_attach_type = type;
8825 __u32 bpf_program__flags(const struct bpf_program *prog)
8827 return prog->prog_flags;
8830 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8832 if (prog->obj->loaded)
8833 return libbpf_err(-EBUSY);
8835 prog->prog_flags = flags;
8839 __u32 bpf_program__log_level(const struct bpf_program *prog)
8841 return prog->log_level;
8844 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8846 if (prog->obj->loaded)
8847 return libbpf_err(-EBUSY);
8849 prog->log_level = log_level;
8853 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8855 *log_size = prog->log_size;
8856 return prog->log_buf;
8859 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8861 if (log_size && !log_buf)
8863 if (prog->log_size > UINT_MAX)
8865 if (prog->obj->loaded)
8868 prog->log_buf = log_buf;
8869 prog->log_size = log_size;
8873 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8874 .sec = (char *)sec_pfx, \
8875 .prog_type = BPF_PROG_TYPE_##ptype, \
8876 .expected_attach_type = atype, \
8877 .cookie = (long)(flags), \
8878 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
8882 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8883 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8884 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8885 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8886 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8887 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8888 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8889 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8890 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8891 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8892 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8894 static const struct bpf_sec_def section_defs[] = {
8895 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8896 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8897 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8898 SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8899 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8900 SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8901 SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8902 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8903 SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8904 SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8905 SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8906 SEC_DEF("uprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8907 SEC_DEF("uretprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8908 SEC_DEF("uprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8909 SEC_DEF("uretprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8910 SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8911 SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8912 SEC_DEF("usdt+", KPROBE, 0, SEC_USDT, attach_usdt),
8913 SEC_DEF("usdt.s+", KPROBE, 0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8914 SEC_DEF("tc/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8915 SEC_DEF("tc/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE), /* alias for tcx */
8916 SEC_DEF("tcx/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8917 SEC_DEF("tcx/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8918 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8919 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8920 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8921 SEC_DEF("netkit/primary", SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
8922 SEC_DEF("netkit/peer", SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
8923 SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8924 SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8925 SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8926 SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8927 SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8928 SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8929 SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8930 SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8931 SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8932 SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8933 SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8934 SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8935 SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8936 SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8937 SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8938 SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8939 SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8940 SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8941 SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8942 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8943 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8944 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8945 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8946 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8947 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
8948 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8949 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8950 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8951 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8952 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8953 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8954 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8955 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8956 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8957 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8958 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8959 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8960 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8961 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8962 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8963 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8964 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8965 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8966 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8967 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8968 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8969 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8970 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8971 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8972 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8973 SEC_DEF("cgroup/connect_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
8974 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8975 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8976 SEC_DEF("cgroup/sendmsg_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
8977 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8978 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8979 SEC_DEF("cgroup/recvmsg_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
8980 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8981 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8982 SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
8983 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8984 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8985 SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
8986 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8987 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8988 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8989 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8990 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8991 SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
8992 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8993 SEC_DEF("netfilter", NETFILTER, BPF_NETFILTER, SEC_NONE),
8996 int libbpf_register_prog_handler(const char *sec,
8997 enum bpf_prog_type prog_type,
8998 enum bpf_attach_type exp_attach_type,
8999 const struct libbpf_prog_handler_opts *opts)
9001 struct bpf_sec_def *sec_def;
9003 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9004 return libbpf_err(-EINVAL);
9006 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9007 return libbpf_err(-E2BIG);
9010 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9013 return libbpf_err(-ENOMEM);
9015 custom_sec_defs = sec_def;
9016 sec_def = &custom_sec_defs[custom_sec_def_cnt];
9018 if (has_custom_fallback_def)
9019 return libbpf_err(-EBUSY);
9021 sec_def = &custom_fallback_def;
9024 sec_def->sec = sec ? strdup(sec) : NULL;
9025 if (sec && !sec_def->sec)
9026 return libbpf_err(-ENOMEM);
9028 sec_def->prog_type = prog_type;
9029 sec_def->expected_attach_type = exp_attach_type;
9030 sec_def->cookie = OPTS_GET(opts, cookie, 0);
9032 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9033 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9034 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9036 sec_def->handler_id = ++last_custom_sec_def_handler_id;
9039 custom_sec_def_cnt++;
9041 has_custom_fallback_def = true;
9043 return sec_def->handler_id;
9046 int libbpf_unregister_prog_handler(int handler_id)
9048 struct bpf_sec_def *sec_defs;
9051 if (handler_id <= 0)
9052 return libbpf_err(-EINVAL);
9054 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9055 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9056 has_custom_fallback_def = false;
9060 for (i = 0; i < custom_sec_def_cnt; i++) {
9061 if (custom_sec_defs[i].handler_id == handler_id)
9065 if (i == custom_sec_def_cnt)
9066 return libbpf_err(-ENOENT);
9068 free(custom_sec_defs[i].sec);
9069 for (i = i + 1; i < custom_sec_def_cnt; i++)
9070 custom_sec_defs[i - 1] = custom_sec_defs[i];
9071 custom_sec_def_cnt--;
9073 /* try to shrink the array, but it's ok if we couldn't */
9074 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9075 /* if new count is zero, reallocarray can return a valid NULL result;
9076 * in this case the previous pointer will be freed, so we *have to*
9077 * reassign old pointer to the new value (even if it's NULL)
9079 if (sec_defs || custom_sec_def_cnt == 0)
9080 custom_sec_defs = sec_defs;
9085 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9087 size_t len = strlen(sec_def->sec);
9089 /* "type/" always has to have proper SEC("type/extras") form */
9090 if (sec_def->sec[len - 1] == '/') {
9091 if (str_has_pfx(sec_name, sec_def->sec))
9096 /* "type+" means it can be either exact SEC("type") or
9097 * well-formed SEC("type/extras") with proper '/' separator
9099 if (sec_def->sec[len - 1] == '+') {
9101 /* not even a prefix */
9102 if (strncmp(sec_name, sec_def->sec, len) != 0)
9104 /* exact match or has '/' separator */
9105 if (sec_name[len] == '\0' || sec_name[len] == '/')
9110 return strcmp(sec_name, sec_def->sec) == 0;
9113 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9115 const struct bpf_sec_def *sec_def;
9118 n = custom_sec_def_cnt;
9119 for (i = 0; i < n; i++) {
9120 sec_def = &custom_sec_defs[i];
9121 if (sec_def_matches(sec_def, sec_name))
9125 n = ARRAY_SIZE(section_defs);
9126 for (i = 0; i < n; i++) {
9127 sec_def = §ion_defs[i];
9128 if (sec_def_matches(sec_def, sec_name))
9132 if (has_custom_fallback_def)
9133 return &custom_fallback_def;
9138 #define MAX_TYPE_NAME_SIZE 32
9140 static char *libbpf_get_type_names(bool attach_type)
9142 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9150 /* Forge string buf with all available names */
9151 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9152 const struct bpf_sec_def *sec_def = §ion_defs[i];
9155 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9158 if (!(sec_def->cookie & SEC_ATTACHABLE))
9162 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9167 strcat(buf, section_defs[i].sec);
9173 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9174 enum bpf_attach_type *expected_attach_type)
9176 const struct bpf_sec_def *sec_def;
9180 return libbpf_err(-EINVAL);
9182 sec_def = find_sec_def(name);
9184 *prog_type = sec_def->prog_type;
9185 *expected_attach_type = sec_def->expected_attach_type;
9189 pr_debug("failed to guess program type from ELF section '%s'\n", name);
9190 type_names = libbpf_get_type_names(false);
9191 if (type_names != NULL) {
9192 pr_debug("supported section(type) names are:%s\n", type_names);
9196 return libbpf_err(-ESRCH);
9199 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9201 if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9204 return attach_type_name[t];
9207 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9209 if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9212 return link_type_name[t];
9215 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9217 if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9220 return map_type_name[t];
9223 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9225 if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9228 return prog_type_name[t];
9231 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9235 struct bpf_map *map;
9238 for (i = 0; i < obj->nr_maps; i++) {
9239 map = &obj->maps[i];
9240 if (!bpf_map__is_struct_ops(map))
9242 if (map->sec_idx == sec_idx &&
9243 map->sec_offset <= offset &&
9244 offset - map->sec_offset < map->def.value_size)
9251 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9252 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9253 Elf64_Shdr *shdr, Elf_Data *data)
9255 const struct btf_member *member;
9256 struct bpf_struct_ops *st_ops;
9257 struct bpf_program *prog;
9258 unsigned int shdr_idx;
9259 const struct btf *btf;
9260 struct bpf_map *map;
9261 unsigned int moff, insn_idx;
9269 nrels = shdr->sh_size / shdr->sh_entsize;
9270 for (i = 0; i < nrels; i++) {
9271 rel = elf_rel_by_idx(data, i);
9273 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9274 return -LIBBPF_ERRNO__FORMAT;
9277 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9279 pr_warn("struct_ops reloc: symbol %zx not found\n",
9280 (size_t)ELF64_R_SYM(rel->r_info));
9281 return -LIBBPF_ERRNO__FORMAT;
9284 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9285 map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9287 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9288 (size_t)rel->r_offset);
9292 moff = rel->r_offset - map->sec_offset;
9293 shdr_idx = sym->st_shndx;
9294 st_ops = map->st_ops;
9295 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",
9297 (long long)(rel->r_info >> 32),
9298 (long long)sym->st_value,
9299 shdr_idx, (size_t)rel->r_offset,
9300 map->sec_offset, sym->st_name, name);
9302 if (shdr_idx >= SHN_LORESERVE) {
9303 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9304 map->name, (size_t)rel->r_offset, shdr_idx);
9305 return -LIBBPF_ERRNO__RELOC;
9307 if (sym->st_value % BPF_INSN_SZ) {
9308 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9309 map->name, (unsigned long long)sym->st_value);
9310 return -LIBBPF_ERRNO__FORMAT;
9312 insn_idx = sym->st_value / BPF_INSN_SZ;
9314 member = find_member_by_offset(st_ops->type, moff * 8);
9316 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9320 member_idx = member - btf_members(st_ops->type);
9321 name = btf__name_by_offset(btf, member->name_off);
9323 if (!resolve_func_ptr(btf, member->type, NULL)) {
9324 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9329 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9331 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9332 map->name, shdr_idx, name);
9336 /* prevent the use of BPF prog with invalid type */
9337 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9338 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9339 map->name, prog->name);
9343 /* if we haven't yet processed this BPF program, record proper
9344 * attach_btf_id and member_idx
9346 if (!prog->attach_btf_id) {
9347 prog->attach_btf_id = st_ops->type_id;
9348 prog->expected_attach_type = member_idx;
9351 /* struct_ops BPF prog can be re-used between multiple
9352 * .struct_ops & .struct_ops.link as long as it's the
9353 * same struct_ops struct definition and the same
9354 * function pointer field
9356 if (prog->attach_btf_id != st_ops->type_id ||
9357 prog->expected_attach_type != member_idx) {
9358 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",
9359 map->name, prog->name, prog->sec_name, prog->type,
9360 prog->attach_btf_id, prog->expected_attach_type, name);
9364 st_ops->progs[member_idx] = prog;
9370 #define BTF_TRACE_PREFIX "btf_trace_"
9371 #define BTF_LSM_PREFIX "bpf_lsm_"
9372 #define BTF_ITER_PREFIX "bpf_iter_"
9373 #define BTF_MAX_NAME_SIZE 128
9375 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9376 const char **prefix, int *kind)
9378 switch (attach_type) {
9379 case BPF_TRACE_RAW_TP:
9380 *prefix = BTF_TRACE_PREFIX;
9381 *kind = BTF_KIND_TYPEDEF;
9384 case BPF_LSM_CGROUP:
9385 *prefix = BTF_LSM_PREFIX;
9386 *kind = BTF_KIND_FUNC;
9388 case BPF_TRACE_ITER:
9389 *prefix = BTF_ITER_PREFIX;
9390 *kind = BTF_KIND_FUNC;
9394 *kind = BTF_KIND_FUNC;
9398 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9399 const char *name, __u32 kind)
9401 char btf_type_name[BTF_MAX_NAME_SIZE];
9404 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9405 "%s%s", prefix, name);
9406 /* snprintf returns the number of characters written excluding the
9407 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9408 * indicates truncation.
9410 if (ret < 0 || ret >= sizeof(btf_type_name))
9411 return -ENAMETOOLONG;
9412 return btf__find_by_name_kind(btf, btf_type_name, kind);
9415 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9416 enum bpf_attach_type attach_type)
9421 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9422 return find_btf_by_prefix_kind(btf, prefix, name, kind);
9425 int libbpf_find_vmlinux_btf_id(const char *name,
9426 enum bpf_attach_type attach_type)
9431 btf = btf__load_vmlinux_btf();
9432 err = libbpf_get_error(btf);
9434 pr_warn("vmlinux BTF is not found\n");
9435 return libbpf_err(err);
9438 err = find_attach_btf_id(btf, name, attach_type);
9440 pr_warn("%s is not found in vmlinux BTF\n", name);
9443 return libbpf_err(err);
9446 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9448 struct bpf_prog_info info;
9449 __u32 info_len = sizeof(info);
9453 memset(&info, 0, info_len);
9454 err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9456 pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9457 attach_prog_fd, err);
9463 pr_warn("The target program doesn't have BTF\n");
9466 btf = btf__load_from_kernel_by_id(info.btf_id);
9467 err = libbpf_get_error(btf);
9469 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9472 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9475 pr_warn("%s is not found in prog's BTF\n", name);
9482 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9483 enum bpf_attach_type attach_type,
9484 int *btf_obj_fd, int *btf_type_id)
9488 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9490 *btf_obj_fd = 0; /* vmlinux BTF */
9497 ret = load_module_btfs(obj);
9501 for (i = 0; i < obj->btf_module_cnt; i++) {
9502 const struct module_btf *mod = &obj->btf_modules[i];
9504 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9506 *btf_obj_fd = mod->fd;
9519 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9520 int *btf_obj_fd, int *btf_type_id)
9522 enum bpf_attach_type attach_type = prog->expected_attach_type;
9523 __u32 attach_prog_fd = prog->attach_prog_fd;
9526 /* BPF program's BTF ID */
9527 if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9528 if (!attach_prog_fd) {
9529 pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9532 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9534 pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9535 prog->name, attach_prog_fd, attach_name, err);
9543 /* kernel/module BTF ID */
9544 if (prog->obj->gen_loader) {
9545 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9549 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9552 pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9553 prog->name, attach_name, err);
9559 int libbpf_attach_type_by_name(const char *name,
9560 enum bpf_attach_type *attach_type)
9563 const struct bpf_sec_def *sec_def;
9566 return libbpf_err(-EINVAL);
9568 sec_def = find_sec_def(name);
9570 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9571 type_names = libbpf_get_type_names(true);
9572 if (type_names != NULL) {
9573 pr_debug("attachable section(type) names are:%s\n", type_names);
9577 return libbpf_err(-EINVAL);
9580 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9581 return libbpf_err(-EINVAL);
9582 if (!(sec_def->cookie & SEC_ATTACHABLE))
9583 return libbpf_err(-EINVAL);
9585 *attach_type = sec_def->expected_attach_type;
9589 int bpf_map__fd(const struct bpf_map *map)
9591 return map ? map->fd : libbpf_err(-EINVAL);
9594 static bool map_uses_real_name(const struct bpf_map *map)
9596 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9597 * their user-visible name differs from kernel-visible name. Users see
9598 * such map's corresponding ELF section name as a map name.
9599 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9600 * maps to know which name has to be returned to the user.
9602 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9604 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9609 const char *bpf_map__name(const struct bpf_map *map)
9614 if (map_uses_real_name(map))
9615 return map->real_name;
9620 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9622 return map->def.type;
9625 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9628 return libbpf_err(-EBUSY);
9629 map->def.type = type;
9633 __u32 bpf_map__map_flags(const struct bpf_map *map)
9635 return map->def.map_flags;
9638 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9641 return libbpf_err(-EBUSY);
9642 map->def.map_flags = flags;
9646 __u64 bpf_map__map_extra(const struct bpf_map *map)
9648 return map->map_extra;
9651 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9654 return libbpf_err(-EBUSY);
9655 map->map_extra = map_extra;
9659 __u32 bpf_map__numa_node(const struct bpf_map *map)
9661 return map->numa_node;
9664 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9667 return libbpf_err(-EBUSY);
9668 map->numa_node = numa_node;
9672 __u32 bpf_map__key_size(const struct bpf_map *map)
9674 return map->def.key_size;
9677 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9680 return libbpf_err(-EBUSY);
9681 map->def.key_size = size;
9685 __u32 bpf_map__value_size(const struct bpf_map *map)
9687 return map->def.value_size;
9690 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9693 struct btf_type *datasec_type, *var_type;
9694 struct btf_var_secinfo *var;
9695 const struct btf_type *array_type;
9696 const struct btf_array *array;
9697 int vlen, element_sz, new_array_id;
9700 /* check btf existence */
9701 btf = bpf_object__btf(map->obj);
9705 /* verify map is datasec */
9706 datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9707 if (!btf_is_datasec(datasec_type)) {
9708 pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9709 bpf_map__name(map));
9713 /* verify datasec has at least one var */
9714 vlen = btf_vlen(datasec_type);
9716 pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9717 bpf_map__name(map));
9721 /* verify last var in the datasec is an array */
9722 var = &btf_var_secinfos(datasec_type)[vlen - 1];
9723 var_type = btf_type_by_id(btf, var->type);
9724 array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9725 if (!btf_is_array(array_type)) {
9726 pr_warn("map '%s': cannot be resized, last var must be an array\n",
9727 bpf_map__name(map));
9731 /* verify request size aligns with array */
9732 array = btf_array(array_type);
9733 element_sz = btf__resolve_size(btf, array->type);
9734 if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9735 pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9736 bpf_map__name(map), element_sz, size);
9740 /* create a new array based on the existing array, but with new length */
9741 nr_elements = (size - var->offset) / element_sz;
9742 new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9743 if (new_array_id < 0)
9744 return new_array_id;
9746 /* adding a new btf type invalidates existing pointers to btf objects,
9747 * so refresh pointers before proceeding
9749 datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9750 var = &btf_var_secinfos(datasec_type)[vlen - 1];
9751 var_type = btf_type_by_id(btf, var->type);
9753 /* finally update btf info */
9754 datasec_type->size = size;
9755 var->size = size - var->offset;
9756 var_type->type = new_array_id;
9761 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9764 return libbpf_err(-EBUSY);
9768 size_t mmap_old_sz, mmap_new_sz;
9770 mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9771 mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9772 err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9774 pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9775 bpf_map__name(map), err);
9778 err = map_btf_datasec_resize(map, size);
9779 if (err && err != -ENOENT) {
9780 pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9781 bpf_map__name(map), err);
9782 map->btf_value_type_id = 0;
9783 map->btf_key_type_id = 0;
9787 map->def.value_size = size;
9791 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9793 return map ? map->btf_key_type_id : 0;
9796 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9798 return map ? map->btf_value_type_id : 0;
9801 int bpf_map__set_initial_value(struct bpf_map *map,
9802 const void *data, size_t size)
9804 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9805 size != map->def.value_size || map->fd >= 0)
9806 return libbpf_err(-EINVAL);
9808 memcpy(map->mmaped, data, size);
9812 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9816 *psize = map->def.value_size;
9820 bool bpf_map__is_internal(const struct bpf_map *map)
9822 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9825 __u32 bpf_map__ifindex(const struct bpf_map *map)
9827 return map->map_ifindex;
9830 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9833 return libbpf_err(-EBUSY);
9834 map->map_ifindex = ifindex;
9838 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9840 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9841 pr_warn("error: unsupported map type\n");
9842 return libbpf_err(-EINVAL);
9844 if (map->inner_map_fd != -1) {
9845 pr_warn("error: inner_map_fd already specified\n");
9846 return libbpf_err(-EINVAL);
9848 if (map->inner_map) {
9849 bpf_map__destroy(map->inner_map);
9850 zfree(&map->inner_map);
9852 map->inner_map_fd = fd;
9856 static struct bpf_map *
9857 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9860 struct bpf_map *s, *e;
9862 if (!obj || !obj->maps)
9863 return errno = EINVAL, NULL;
9866 e = obj->maps + obj->nr_maps;
9868 if ((m < s) || (m >= e)) {
9869 pr_warn("error in %s: map handler doesn't belong to object\n",
9871 return errno = EINVAL, NULL;
9874 idx = (m - obj->maps) + i;
9875 if (idx >= obj->nr_maps || idx < 0)
9877 return &obj->maps[idx];
9881 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9886 return __bpf_map__iter(prev, obj, 1);
9890 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9895 return obj->maps + obj->nr_maps - 1;
9898 return __bpf_map__iter(next, obj, -1);
9902 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9904 struct bpf_map *pos;
9906 bpf_object__for_each_map(pos, obj) {
9907 /* if it's a special internal map name (which always starts
9908 * with dot) then check if that special name matches the
9909 * real map name (ELF section name)
9911 if (name[0] == '.') {
9912 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9916 /* otherwise map name has to be an exact match */
9917 if (map_uses_real_name(pos)) {
9918 if (strcmp(pos->real_name, name) == 0)
9922 if (strcmp(pos->name, name) == 0)
9925 return errno = ENOENT, NULL;
9929 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9931 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9934 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9935 size_t value_sz, bool check_value_sz)
9940 if (map->def.key_size != key_sz) {
9941 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9942 map->name, key_sz, map->def.key_size);
9946 if (!check_value_sz)
9949 switch (map->def.type) {
9950 case BPF_MAP_TYPE_PERCPU_ARRAY:
9951 case BPF_MAP_TYPE_PERCPU_HASH:
9952 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9953 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9954 int num_cpu = libbpf_num_possible_cpus();
9955 size_t elem_sz = roundup(map->def.value_size, 8);
9957 if (value_sz != num_cpu * elem_sz) {
9958 pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9959 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9965 if (map->def.value_size != value_sz) {
9966 pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9967 map->name, value_sz, map->def.value_size);
9975 int bpf_map__lookup_elem(const struct bpf_map *map,
9976 const void *key, size_t key_sz,
9977 void *value, size_t value_sz, __u64 flags)
9981 err = validate_map_op(map, key_sz, value_sz, true);
9983 return libbpf_err(err);
9985 return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9988 int bpf_map__update_elem(const struct bpf_map *map,
9989 const void *key, size_t key_sz,
9990 const void *value, size_t value_sz, __u64 flags)
9994 err = validate_map_op(map, key_sz, value_sz, true);
9996 return libbpf_err(err);
9998 return bpf_map_update_elem(map->fd, key, value, flags);
10001 int bpf_map__delete_elem(const struct bpf_map *map,
10002 const void *key, size_t key_sz, __u64 flags)
10006 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10008 return libbpf_err(err);
10010 return bpf_map_delete_elem_flags(map->fd, key, flags);
10013 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10014 const void *key, size_t key_sz,
10015 void *value, size_t value_sz, __u64 flags)
10019 err = validate_map_op(map, key_sz, value_sz, true);
10021 return libbpf_err(err);
10023 return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10026 int bpf_map__get_next_key(const struct bpf_map *map,
10027 const void *cur_key, void *next_key, size_t key_sz)
10031 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10033 return libbpf_err(err);
10035 return bpf_map_get_next_key(map->fd, cur_key, next_key);
10038 long libbpf_get_error(const void *ptr)
10040 if (!IS_ERR_OR_NULL(ptr))
10044 errno = -PTR_ERR(ptr);
10046 /* If ptr == NULL, then errno should be already set by the failing
10047 * API, because libbpf never returns NULL on success and it now always
10048 * sets errno on error. So no extra errno handling for ptr == NULL
10054 /* Replace link's underlying BPF program with the new one */
10055 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10059 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10060 return libbpf_err_errno(ret);
10063 /* Release "ownership" of underlying BPF resource (typically, BPF program
10064 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10065 * link, when destructed through bpf_link__destroy() call won't attempt to
10066 * detach/unregisted that BPF resource. This is useful in situations where,
10067 * say, attached BPF program has to outlive userspace program that attached it
10068 * in the system. Depending on type of BPF program, though, there might be
10069 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10070 * exit of userspace program doesn't trigger automatic detachment and clean up
10071 * inside the kernel.
10073 void bpf_link__disconnect(struct bpf_link *link)
10075 link->disconnected = true;
10078 int bpf_link__destroy(struct bpf_link *link)
10082 if (IS_ERR_OR_NULL(link))
10085 if (!link->disconnected && link->detach)
10086 err = link->detach(link);
10087 if (link->pin_path)
10088 free(link->pin_path);
10090 link->dealloc(link);
10094 return libbpf_err(err);
10097 int bpf_link__fd(const struct bpf_link *link)
10102 const char *bpf_link__pin_path(const struct bpf_link *link)
10104 return link->pin_path;
10107 static int bpf_link__detach_fd(struct bpf_link *link)
10109 return libbpf_err_errno(close(link->fd));
10112 struct bpf_link *bpf_link__open(const char *path)
10114 struct bpf_link *link;
10117 fd = bpf_obj_get(path);
10120 pr_warn("failed to open link at %s: %d\n", path, fd);
10121 return libbpf_err_ptr(fd);
10124 link = calloc(1, sizeof(*link));
10127 return libbpf_err_ptr(-ENOMEM);
10129 link->detach = &bpf_link__detach_fd;
10132 link->pin_path = strdup(path);
10133 if (!link->pin_path) {
10134 bpf_link__destroy(link);
10135 return libbpf_err_ptr(-ENOMEM);
10141 int bpf_link__detach(struct bpf_link *link)
10143 return bpf_link_detach(link->fd) ? -errno : 0;
10146 int bpf_link__pin(struct bpf_link *link, const char *path)
10150 if (link->pin_path)
10151 return libbpf_err(-EBUSY);
10152 err = make_parent_dir(path);
10154 return libbpf_err(err);
10155 err = check_path(path);
10157 return libbpf_err(err);
10159 link->pin_path = strdup(path);
10160 if (!link->pin_path)
10161 return libbpf_err(-ENOMEM);
10163 if (bpf_obj_pin(link->fd, link->pin_path)) {
10165 zfree(&link->pin_path);
10166 return libbpf_err(err);
10169 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10173 int bpf_link__unpin(struct bpf_link *link)
10177 if (!link->pin_path)
10178 return libbpf_err(-EINVAL);
10180 err = unlink(link->pin_path);
10184 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10185 zfree(&link->pin_path);
10189 struct bpf_link_perf {
10190 struct bpf_link link;
10192 /* legacy kprobe support: keep track of probe identifier and type */
10193 char *legacy_probe_name;
10194 bool legacy_is_kprobe;
10195 bool legacy_is_retprobe;
10198 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10199 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10201 static int bpf_link_perf_detach(struct bpf_link *link)
10203 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10206 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10209 if (perf_link->perf_event_fd != link->fd)
10210 close(perf_link->perf_event_fd);
10213 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10214 if (perf_link->legacy_probe_name) {
10215 if (perf_link->legacy_is_kprobe) {
10216 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10217 perf_link->legacy_is_retprobe);
10219 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10220 perf_link->legacy_is_retprobe);
10227 static void bpf_link_perf_dealloc(struct bpf_link *link)
10229 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10231 free(perf_link->legacy_probe_name);
10235 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10236 const struct bpf_perf_event_opts *opts)
10238 char errmsg[STRERR_BUFSIZE];
10239 struct bpf_link_perf *link;
10240 int prog_fd, link_fd = -1, err;
10241 bool force_ioctl_attach;
10243 if (!OPTS_VALID(opts, bpf_perf_event_opts))
10244 return libbpf_err_ptr(-EINVAL);
10247 pr_warn("prog '%s': invalid perf event FD %d\n",
10249 return libbpf_err_ptr(-EINVAL);
10251 prog_fd = bpf_program__fd(prog);
10253 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10255 return libbpf_err_ptr(-EINVAL);
10258 link = calloc(1, sizeof(*link));
10260 return libbpf_err_ptr(-ENOMEM);
10261 link->link.detach = &bpf_link_perf_detach;
10262 link->link.dealloc = &bpf_link_perf_dealloc;
10263 link->perf_event_fd = pfd;
10265 force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10266 if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10267 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10268 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10270 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10273 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10275 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10278 link->link.fd = link_fd;
10280 if (OPTS_GET(opts, bpf_cookie, 0)) {
10281 pr_warn("prog '%s': user context value is not supported\n", prog->name);
10286 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10288 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10289 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10290 if (err == -EPROTO)
10291 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10295 link->link.fd = pfd;
10297 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10299 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10300 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10304 return &link->link;
10309 return libbpf_err_ptr(err);
10312 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10314 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10318 * this function is expected to parse integer in the range of [0, 2^31-1] from
10319 * given file using scanf format string fmt. If actual parsed value is
10320 * negative, the result might be indistinguishable from error
10322 static int parse_uint_from_file(const char *file, const char *fmt)
10324 char buf[STRERR_BUFSIZE];
10328 f = fopen(file, "re");
10331 pr_debug("failed to open '%s': %s\n", file,
10332 libbpf_strerror_r(err, buf, sizeof(buf)));
10335 err = fscanf(f, fmt, &ret);
10337 err = err == EOF ? -EIO : -errno;
10338 pr_debug("failed to parse '%s': %s\n", file,
10339 libbpf_strerror_r(err, buf, sizeof(buf)));
10347 static int determine_kprobe_perf_type(void)
10349 const char *file = "/sys/bus/event_source/devices/kprobe/type";
10351 return parse_uint_from_file(file, "%d\n");
10354 static int determine_uprobe_perf_type(void)
10356 const char *file = "/sys/bus/event_source/devices/uprobe/type";
10358 return parse_uint_from_file(file, "%d\n");
10361 static int determine_kprobe_retprobe_bit(void)
10363 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10365 return parse_uint_from_file(file, "config:%d\n");
10368 static int determine_uprobe_retprobe_bit(void)
10370 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10372 return parse_uint_from_file(file, "config:%d\n");
10375 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10376 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10378 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10379 uint64_t offset, int pid, size_t ref_ctr_off)
10381 const size_t attr_sz = sizeof(struct perf_event_attr);
10382 struct perf_event_attr attr;
10383 char errmsg[STRERR_BUFSIZE];
10386 if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10389 memset(&attr, 0, attr_sz);
10391 type = uprobe ? determine_uprobe_perf_type()
10392 : determine_kprobe_perf_type();
10394 pr_warn("failed to determine %s perf type: %s\n",
10395 uprobe ? "uprobe" : "kprobe",
10396 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10400 int bit = uprobe ? determine_uprobe_retprobe_bit()
10401 : determine_kprobe_retprobe_bit();
10404 pr_warn("failed to determine %s retprobe bit: %s\n",
10405 uprobe ? "uprobe" : "kprobe",
10406 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10409 attr.config |= 1 << bit;
10411 attr.size = attr_sz;
10413 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10414 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10415 attr.config2 = offset; /* kprobe_addr or probe_offset */
10417 /* pid filter is meaningful only for uprobes */
10418 pfd = syscall(__NR_perf_event_open, &attr,
10419 pid < 0 ? -1 : pid /* pid */,
10420 pid == -1 ? 0 : -1 /* cpu */,
10421 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10422 return pfd >= 0 ? pfd : -errno;
10425 static int append_to_file(const char *file, const char *fmt, ...)
10427 int fd, n, err = 0;
10432 n = vsnprintf(buf, sizeof(buf), fmt, ap);
10435 if (n < 0 || n >= sizeof(buf))
10438 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10442 if (write(fd, buf, n) < 0)
10449 #define DEBUGFS "/sys/kernel/debug/tracing"
10450 #define TRACEFS "/sys/kernel/tracing"
10452 static bool use_debugfs(void)
10454 static int has_debugfs = -1;
10456 if (has_debugfs < 0)
10457 has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10459 return has_debugfs == 1;
10462 static const char *tracefs_path(void)
10464 return use_debugfs() ? DEBUGFS : TRACEFS;
10467 static const char *tracefs_kprobe_events(void)
10469 return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10472 static const char *tracefs_uprobe_events(void)
10474 return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10477 static const char *tracefs_available_filter_functions(void)
10479 return use_debugfs() ? DEBUGFS"/available_filter_functions"
10480 : TRACEFS"/available_filter_functions";
10483 static const char *tracefs_available_filter_functions_addrs(void)
10485 return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10486 : TRACEFS"/available_filter_functions_addrs";
10489 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10490 const char *kfunc_name, size_t offset)
10492 static int index = 0;
10495 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10496 __sync_fetch_and_add(&index, 1));
10498 /* sanitize binary_path in the probe name */
10499 for (i = 0; buf[i]; i++) {
10500 if (!isalnum(buf[i]))
10505 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10506 const char *kfunc_name, size_t offset)
10508 return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10509 retprobe ? 'r' : 'p',
10510 retprobe ? "kretprobes" : "kprobes",
10511 probe_name, kfunc_name, offset);
10514 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10516 return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10517 retprobe ? "kretprobes" : "kprobes", probe_name);
10520 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10524 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10525 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10527 return parse_uint_from_file(file, "%d\n");
10530 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10531 const char *kfunc_name, size_t offset, int pid)
10533 const size_t attr_sz = sizeof(struct perf_event_attr);
10534 struct perf_event_attr attr;
10535 char errmsg[STRERR_BUFSIZE];
10536 int type, pfd, err;
10538 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10540 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10541 kfunc_name, offset,
10542 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10545 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10548 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10549 kfunc_name, offset,
10550 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10551 goto err_clean_legacy;
10554 memset(&attr, 0, attr_sz);
10555 attr.size = attr_sz;
10556 attr.config = type;
10557 attr.type = PERF_TYPE_TRACEPOINT;
10559 pfd = syscall(__NR_perf_event_open, &attr,
10560 pid < 0 ? -1 : pid, /* pid */
10561 pid == -1 ? 0 : -1, /* cpu */
10562 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10565 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10566 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10567 goto err_clean_legacy;
10572 /* Clear the newly added legacy kprobe_event */
10573 remove_kprobe_event_legacy(probe_name, retprobe);
10577 static const char *arch_specific_syscall_pfx(void)
10579 #if defined(__x86_64__)
10581 #elif defined(__i386__)
10583 #elif defined(__s390x__)
10585 #elif defined(__s390__)
10587 #elif defined(__arm__)
10589 #elif defined(__aarch64__)
10591 #elif defined(__mips__)
10593 #elif defined(__riscv)
10595 #elif defined(__powerpc__)
10597 #elif defined(__powerpc64__)
10598 return "powerpc64";
10604 static int probe_kern_syscall_wrapper(void)
10606 char syscall_name[64];
10607 const char *ksys_pfx;
10609 ksys_pfx = arch_specific_syscall_pfx();
10613 snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10615 if (determine_kprobe_perf_type() >= 0) {
10618 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10622 return pfd >= 0 ? 1 : 0;
10623 } else { /* legacy mode */
10624 char probe_name[128];
10626 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10627 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10630 (void)remove_kprobe_event_legacy(probe_name, false);
10636 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10637 const char *func_name,
10638 const struct bpf_kprobe_opts *opts)
10640 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10641 enum probe_attach_mode attach_mode;
10642 char errmsg[STRERR_BUFSIZE];
10643 char *legacy_probe = NULL;
10644 struct bpf_link *link;
10646 bool retprobe, legacy;
10649 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10650 return libbpf_err_ptr(-EINVAL);
10652 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10653 retprobe = OPTS_GET(opts, retprobe, false);
10654 offset = OPTS_GET(opts, offset, 0);
10655 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10657 legacy = determine_kprobe_perf_type() < 0;
10658 switch (attach_mode) {
10659 case PROBE_ATTACH_MODE_LEGACY:
10661 pe_opts.force_ioctl_attach = true;
10663 case PROBE_ATTACH_MODE_PERF:
10665 return libbpf_err_ptr(-ENOTSUP);
10666 pe_opts.force_ioctl_attach = true;
10668 case PROBE_ATTACH_MODE_LINK:
10669 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10670 return libbpf_err_ptr(-ENOTSUP);
10672 case PROBE_ATTACH_MODE_DEFAULT:
10675 return libbpf_err_ptr(-EINVAL);
10679 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10681 -1 /* pid */, 0 /* ref_ctr_off */);
10683 char probe_name[256];
10685 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10686 func_name, offset);
10688 legacy_probe = strdup(probe_name);
10690 return libbpf_err_ptr(-ENOMEM);
10692 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10693 offset, -1 /* pid */);
10697 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10698 prog->name, retprobe ? "kretprobe" : "kprobe",
10700 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10703 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10704 err = libbpf_get_error(link);
10707 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10708 prog->name, retprobe ? "kretprobe" : "kprobe",
10710 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10711 goto err_clean_legacy;
10714 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10716 perf_link->legacy_probe_name = legacy_probe;
10717 perf_link->legacy_is_kprobe = true;
10718 perf_link->legacy_is_retprobe = retprobe;
10725 remove_kprobe_event_legacy(legacy_probe, retprobe);
10727 free(legacy_probe);
10728 return libbpf_err_ptr(err);
10731 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10733 const char *func_name)
10735 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10736 .retprobe = retprobe,
10739 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10742 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10743 const char *syscall_name,
10744 const struct bpf_ksyscall_opts *opts)
10746 LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10747 char func_name[128];
10749 if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10750 return libbpf_err_ptr(-EINVAL);
10752 if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10753 /* arch_specific_syscall_pfx() should never return NULL here
10754 * because it is guarded by kernel_supports(). However, since
10755 * compiler does not know that we have an explicit conditional
10758 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10759 arch_specific_syscall_pfx() ? : "", syscall_name);
10761 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10764 kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10765 kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10767 return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10770 /* Adapted from perf/util/string.c */
10771 bool glob_match(const char *str, const char *pat)
10773 while (*str && *pat && *pat != '*') {
10774 if (*pat == '?') { /* Matches any single character */
10784 /* Check wild card */
10786 while (*pat == '*')
10788 if (!*pat) /* Tail wild card matches all */
10791 if (glob_match(str++, pat))
10794 return !*str && !*pat;
10797 struct kprobe_multi_resolve {
10798 const char *pattern;
10799 unsigned long *addrs;
10804 struct avail_kallsyms_data {
10807 struct kprobe_multi_resolve *res;
10810 static int avail_func_cmp(const void *a, const void *b)
10812 return strcmp(*(const char **)a, *(const char **)b);
10815 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10816 const char *sym_name, void *ctx)
10818 struct avail_kallsyms_data *data = ctx;
10819 struct kprobe_multi_resolve *res = data->res;
10822 if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10825 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10829 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10833 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10835 const char *available_functions_file = tracefs_available_filter_functions();
10836 struct avail_kallsyms_data data;
10837 char sym_name[500];
10839 int err = 0, ret, i;
10840 char **syms = NULL;
10841 size_t cap = 0, cnt = 0;
10843 f = fopen(available_functions_file, "re");
10846 pr_warn("failed to open %s: %d\n", available_functions_file, err);
10853 ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10854 if (ret == EOF && feof(f))
10858 pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10863 if (!glob_match(sym_name, res->pattern))
10866 err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10870 name = strdup(sym_name);
10876 syms[cnt++] = name;
10879 /* no entries found, bail out */
10885 /* sort available functions */
10886 qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10891 libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10897 for (i = 0; i < cnt; i++)
10898 free((char *)syms[i]);
10905 static bool has_available_filter_functions_addrs(void)
10907 return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10910 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10912 const char *available_path = tracefs_available_filter_functions_addrs();
10913 char sym_name[500];
10916 unsigned long long sym_addr;
10918 f = fopen(available_path, "re");
10921 pr_warn("failed to open %s: %d\n", available_path, err);
10926 ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10927 if (ret == EOF && feof(f))
10931 pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10937 if (!glob_match(sym_name, res->pattern))
10940 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10941 sizeof(*res->addrs), res->cnt + 1);
10945 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10957 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10958 const char *pattern,
10959 const struct bpf_kprobe_multi_opts *opts)
10961 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10962 struct kprobe_multi_resolve res = {
10963 .pattern = pattern,
10965 struct bpf_link *link = NULL;
10966 char errmsg[STRERR_BUFSIZE];
10967 const unsigned long *addrs;
10968 int err, link_fd, prog_fd;
10969 const __u64 *cookies;
10974 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10975 return libbpf_err_ptr(-EINVAL);
10977 syms = OPTS_GET(opts, syms, false);
10978 addrs = OPTS_GET(opts, addrs, false);
10979 cnt = OPTS_GET(opts, cnt, false);
10980 cookies = OPTS_GET(opts, cookies, false);
10982 if (!pattern && !addrs && !syms)
10983 return libbpf_err_ptr(-EINVAL);
10984 if (pattern && (addrs || syms || cookies || cnt))
10985 return libbpf_err_ptr(-EINVAL);
10986 if (!pattern && !cnt)
10987 return libbpf_err_ptr(-EINVAL);
10989 return libbpf_err_ptr(-EINVAL);
10992 if (has_available_filter_functions_addrs())
10993 err = libbpf_available_kprobes_parse(&res);
10995 err = libbpf_available_kallsyms_parse(&res);
11002 retprobe = OPTS_GET(opts, retprobe, false);
11004 lopts.kprobe_multi.syms = syms;
11005 lopts.kprobe_multi.addrs = addrs;
11006 lopts.kprobe_multi.cookies = cookies;
11007 lopts.kprobe_multi.cnt = cnt;
11008 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11010 link = calloc(1, sizeof(*link));
11015 link->detach = &bpf_link__detach_fd;
11017 prog_fd = bpf_program__fd(prog);
11018 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11021 pr_warn("prog '%s': failed to attach: %s\n",
11022 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11025 link->fd = link_fd;
11032 return libbpf_err_ptr(err);
11035 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11037 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11038 unsigned long offset = 0;
11039 const char *func_name;
11045 /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11046 if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11049 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11051 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11053 func_name = prog->sec_name + sizeof("kprobe/") - 1;
11055 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11057 pr_warn("kprobe name is invalid: %s\n", func_name);
11060 if (opts.retprobe && offset != 0) {
11062 pr_warn("kretprobes do not support offset specification\n");
11066 opts.offset = offset;
11067 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11069 return libbpf_get_error(*link);
11072 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11074 LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11075 const char *syscall_name;
11079 /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11080 if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11083 opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11085 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11087 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11089 *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11090 return *link ? 0 : -errno;
11093 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11095 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11102 /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11103 if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11104 strcmp(prog->sec_name, "kretprobe.multi") == 0)
11107 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11109 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11111 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11113 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11115 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11119 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11121 return libbpf_get_error(*link);
11124 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11126 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11127 LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11128 int n, ret = -EINVAL;
11132 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11133 &probe_type, &binary_path, &func_name);
11136 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11140 opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11141 *link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11142 ret = libbpf_get_error(*link);
11145 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11155 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11156 const char *binary_path, uint64_t offset)
11160 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11162 /* sanitize binary_path in the probe name */
11163 for (i = 0; buf[i]; i++) {
11164 if (!isalnum(buf[i]))
11169 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11170 const char *binary_path, size_t offset)
11172 return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11173 retprobe ? 'r' : 'p',
11174 retprobe ? "uretprobes" : "uprobes",
11175 probe_name, binary_path, offset);
11178 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11180 return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11181 retprobe ? "uretprobes" : "uprobes", probe_name);
11184 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11188 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11189 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11191 return parse_uint_from_file(file, "%d\n");
11194 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11195 const char *binary_path, size_t offset, int pid)
11197 const size_t attr_sz = sizeof(struct perf_event_attr);
11198 struct perf_event_attr attr;
11199 int type, pfd, err;
11201 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11203 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11204 binary_path, (size_t)offset, err);
11207 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11210 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11211 binary_path, offset, err);
11212 goto err_clean_legacy;
11215 memset(&attr, 0, attr_sz);
11216 attr.size = attr_sz;
11217 attr.config = type;
11218 attr.type = PERF_TYPE_TRACEPOINT;
11220 pfd = syscall(__NR_perf_event_open, &attr,
11221 pid < 0 ? -1 : pid, /* pid */
11222 pid == -1 ? 0 : -1, /* cpu */
11223 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11226 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11227 goto err_clean_legacy;
11232 /* Clear the newly added legacy uprobe_event */
11233 remove_uprobe_event_legacy(probe_name, retprobe);
11237 /* Find offset of function name in archive specified by path. Currently
11238 * supported are .zip files that do not compress their contents, as used on
11239 * Android in the form of APKs, for example. "file_name" is the name of the ELF
11240 * file inside the archive. "func_name" matches symbol name or name@@LIB for
11241 * library functions.
11243 * An overview of the APK format specifically provided here:
11244 * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11246 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11247 const char *func_name)
11249 struct zip_archive *archive;
11250 struct zip_entry entry;
11254 archive = zip_archive_open(archive_path);
11255 if (IS_ERR(archive)) {
11256 ret = PTR_ERR(archive);
11257 pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11261 ret = zip_archive_find_entry(archive, file_name, &entry);
11263 pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11264 archive_path, ret);
11267 pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11268 (unsigned long)entry.data_offset);
11270 if (entry.compression) {
11271 pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11273 ret = -LIBBPF_ERRNO__FORMAT;
11277 elf = elf_memory((void *)entry.data, entry.data_length);
11279 pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11281 ret = -LIBBPF_ERRNO__LIBELF;
11285 ret = elf_find_func_offset(elf, file_name, func_name);
11287 pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11288 func_name, file_name, archive_path, entry.data_offset, ret,
11289 ret + entry.data_offset);
11290 ret += entry.data_offset;
11295 zip_archive_close(archive);
11299 static const char *arch_specific_lib_paths(void)
11302 * Based on https://packages.debian.org/sid/libc6.
11304 * Assume that the traced program is built for the same architecture
11305 * as libbpf, which should cover the vast majority of cases.
11307 #if defined(__x86_64__)
11308 return "/lib/x86_64-linux-gnu";
11309 #elif defined(__i386__)
11310 return "/lib/i386-linux-gnu";
11311 #elif defined(__s390x__)
11312 return "/lib/s390x-linux-gnu";
11313 #elif defined(__s390__)
11314 return "/lib/s390-linux-gnu";
11315 #elif defined(__arm__) && defined(__SOFTFP__)
11316 return "/lib/arm-linux-gnueabi";
11317 #elif defined(__arm__) && !defined(__SOFTFP__)
11318 return "/lib/arm-linux-gnueabihf";
11319 #elif defined(__aarch64__)
11320 return "/lib/aarch64-linux-gnu";
11321 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11322 return "/lib/mips64el-linux-gnuabi64";
11323 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11324 return "/lib/mipsel-linux-gnu";
11325 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11326 return "/lib/powerpc64le-linux-gnu";
11327 #elif defined(__sparc__) && defined(__arch64__)
11328 return "/lib/sparc64-linux-gnu";
11329 #elif defined(__riscv) && __riscv_xlen == 64
11330 return "/lib/riscv64-linux-gnu";
11336 /* Get full path to program/shared library. */
11337 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11339 const char *search_paths[3] = {};
11342 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11343 search_paths[0] = getenv("LD_LIBRARY_PATH");
11344 search_paths[1] = "/usr/lib64:/usr/lib";
11345 search_paths[2] = arch_specific_lib_paths();
11348 search_paths[0] = getenv("PATH");
11349 search_paths[1] = "/usr/bin:/usr/sbin";
11350 perm = R_OK | X_OK;
11353 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11356 if (!search_paths[i])
11358 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11364 next_path = strchr(s, ':');
11365 seg_len = next_path ? next_path - s : strlen(s);
11368 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11369 /* ensure it has required permissions */
11370 if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11372 pr_debug("resolved '%s' to '%s'\n", file, result);
11380 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11383 const char *func_pattern,
11384 const struct bpf_uprobe_multi_opts *opts)
11386 const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11387 LIBBPF_OPTS(bpf_link_create_opts, lopts);
11388 unsigned long *resolved_offsets = NULL;
11389 int err = 0, link_fd, prog_fd;
11390 struct bpf_link *link = NULL;
11391 char errmsg[STRERR_BUFSIZE];
11392 char full_path[PATH_MAX];
11393 const __u64 *cookies;
11397 if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11398 return libbpf_err_ptr(-EINVAL);
11400 syms = OPTS_GET(opts, syms, NULL);
11401 offsets = OPTS_GET(opts, offsets, NULL);
11402 ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11403 cookies = OPTS_GET(opts, cookies, NULL);
11404 cnt = OPTS_GET(opts, cnt, 0);
11407 * User can specify 2 mutually exclusive set of inputs:
11409 * 1) use only path/func_pattern/pid arguments
11411 * 2) use path/pid with allowed combinations of:
11412 * syms/offsets/ref_ctr_offsets/cookies/cnt
11414 * - syms and offsets are mutually exclusive
11415 * - ref_ctr_offsets and cookies are optional
11417 * Any other usage results in error.
11421 return libbpf_err_ptr(-EINVAL);
11422 if (!func_pattern && cnt == 0)
11423 return libbpf_err_ptr(-EINVAL);
11425 if (func_pattern) {
11426 if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11427 return libbpf_err_ptr(-EINVAL);
11429 if (!!syms == !!offsets)
11430 return libbpf_err_ptr(-EINVAL);
11433 if (func_pattern) {
11434 if (!strchr(path, '/')) {
11435 err = resolve_full_path(path, full_path, sizeof(full_path));
11437 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11438 prog->name, path, err);
11439 return libbpf_err_ptr(err);
11444 err = elf_resolve_pattern_offsets(path, func_pattern,
11445 &resolved_offsets, &cnt);
11447 return libbpf_err_ptr(err);
11448 offsets = resolved_offsets;
11450 err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11452 return libbpf_err_ptr(err);
11453 offsets = resolved_offsets;
11456 lopts.uprobe_multi.path = path;
11457 lopts.uprobe_multi.offsets = offsets;
11458 lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11459 lopts.uprobe_multi.cookies = cookies;
11460 lopts.uprobe_multi.cnt = cnt;
11461 lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11466 lopts.uprobe_multi.pid = pid;
11468 link = calloc(1, sizeof(*link));
11473 link->detach = &bpf_link__detach_fd;
11475 prog_fd = bpf_program__fd(prog);
11476 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11479 pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11480 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11483 link->fd = link_fd;
11484 free(resolved_offsets);
11488 free(resolved_offsets);
11490 return libbpf_err_ptr(err);
11493 LIBBPF_API struct bpf_link *
11494 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11495 const char *binary_path, size_t func_offset,
11496 const struct bpf_uprobe_opts *opts)
11498 const char *archive_path = NULL, *archive_sep = NULL;
11499 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11500 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11501 enum probe_attach_mode attach_mode;
11502 char full_path[PATH_MAX];
11503 struct bpf_link *link;
11504 size_t ref_ctr_off;
11506 bool retprobe, legacy;
11507 const char *func_name;
11509 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11510 return libbpf_err_ptr(-EINVAL);
11512 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11513 retprobe = OPTS_GET(opts, retprobe, false);
11514 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11515 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11518 return libbpf_err_ptr(-EINVAL);
11520 /* Check if "binary_path" refers to an archive. */
11521 archive_sep = strstr(binary_path, "!/");
11523 full_path[0] = '\0';
11524 libbpf_strlcpy(full_path, binary_path,
11525 min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11526 archive_path = full_path;
11527 binary_path = archive_sep + 2;
11528 } else if (!strchr(binary_path, '/')) {
11529 err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11531 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11532 prog->name, binary_path, err);
11533 return libbpf_err_ptr(err);
11535 binary_path = full_path;
11537 func_name = OPTS_GET(opts, func_name, NULL);
11541 if (archive_path) {
11542 sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11544 binary_path = archive_path;
11546 sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11549 return libbpf_err_ptr(sym_off);
11550 func_offset += sym_off;
11553 legacy = determine_uprobe_perf_type() < 0;
11554 switch (attach_mode) {
11555 case PROBE_ATTACH_MODE_LEGACY:
11557 pe_opts.force_ioctl_attach = true;
11559 case PROBE_ATTACH_MODE_PERF:
11561 return libbpf_err_ptr(-ENOTSUP);
11562 pe_opts.force_ioctl_attach = true;
11564 case PROBE_ATTACH_MODE_LINK:
11565 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11566 return libbpf_err_ptr(-ENOTSUP);
11568 case PROBE_ATTACH_MODE_DEFAULT:
11571 return libbpf_err_ptr(-EINVAL);
11575 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11576 func_offset, pid, ref_ctr_off);
11578 char probe_name[PATH_MAX + 64];
11581 return libbpf_err_ptr(-EINVAL);
11583 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11584 binary_path, func_offset);
11586 legacy_probe = strdup(probe_name);
11588 return libbpf_err_ptr(-ENOMEM);
11590 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11591 binary_path, func_offset, pid);
11595 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11596 prog->name, retprobe ? "uretprobe" : "uprobe",
11597 binary_path, func_offset,
11598 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11602 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11603 err = libbpf_get_error(link);
11606 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11607 prog->name, retprobe ? "uretprobe" : "uprobe",
11608 binary_path, func_offset,
11609 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11610 goto err_clean_legacy;
11613 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11615 perf_link->legacy_probe_name = legacy_probe;
11616 perf_link->legacy_is_kprobe = false;
11617 perf_link->legacy_is_retprobe = retprobe;
11623 remove_uprobe_event_legacy(legacy_probe, retprobe);
11625 free(legacy_probe);
11626 return libbpf_err_ptr(err);
11629 /* Format of u[ret]probe section definition supporting auto-attach:
11630 * u[ret]probe/binary:function[+offset]
11632 * binary can be an absolute/relative path or a filename; the latter is resolved to a
11633 * full binary path via bpf_program__attach_uprobe_opts.
11635 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11636 * specified (and auto-attach is not possible) or the above format is specified for
11639 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11641 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11642 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
11643 int n, c, ret = -EINVAL;
11648 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11649 &probe_type, &binary_path, &func_name);
11652 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11656 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11657 prog->name, prog->sec_name);
11660 /* check if user specifies `+offset`, if yes, this should be
11661 * the last part of the string, make sure sscanf read to EOL
11663 func_off = strrchr(func_name, '+');
11665 n = sscanf(func_off, "+%li%n", &offset, &c);
11666 if (n == 1 && *(func_off + c) == '\0')
11667 func_off[0] = '\0';
11671 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11672 strcmp(probe_type, "uretprobe.s") == 0;
11673 if (opts.retprobe && offset != 0) {
11674 pr_warn("prog '%s': uretprobes do not support offset specification\n",
11678 opts.func_name = func_name;
11679 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11680 ret = libbpf_get_error(*link);
11683 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11694 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11695 bool retprobe, pid_t pid,
11696 const char *binary_path,
11697 size_t func_offset)
11699 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11701 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11704 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11705 pid_t pid, const char *binary_path,
11706 const char *usdt_provider, const char *usdt_name,
11707 const struct bpf_usdt_opts *opts)
11709 char resolved_path[512];
11710 struct bpf_object *obj = prog->obj;
11711 struct bpf_link *link;
11715 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11716 return libbpf_err_ptr(-EINVAL);
11718 if (bpf_program__fd(prog) < 0) {
11719 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11721 return libbpf_err_ptr(-EINVAL);
11725 return libbpf_err_ptr(-EINVAL);
11727 if (!strchr(binary_path, '/')) {
11728 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11730 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11731 prog->name, binary_path, err);
11732 return libbpf_err_ptr(err);
11734 binary_path = resolved_path;
11737 /* USDT manager is instantiated lazily on first USDT attach. It will
11738 * be destroyed together with BPF object in bpf_object__close().
11740 if (IS_ERR(obj->usdt_man))
11741 return libbpf_ptr(obj->usdt_man);
11742 if (!obj->usdt_man) {
11743 obj->usdt_man = usdt_manager_new(obj);
11744 if (IS_ERR(obj->usdt_man))
11745 return libbpf_ptr(obj->usdt_man);
11748 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11749 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11750 usdt_provider, usdt_name, usdt_cookie);
11751 err = libbpf_get_error(link);
11753 return libbpf_err_ptr(err);
11757 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11759 char *path = NULL, *provider = NULL, *name = NULL;
11760 const char *sec_name;
11763 sec_name = bpf_program__section_name(prog);
11764 if (strcmp(sec_name, "usdt") == 0) {
11765 /* no auto-attach for just SEC("usdt") */
11770 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11772 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11776 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11777 provider, name, NULL);
11778 err = libbpf_get_error(*link);
11786 static int determine_tracepoint_id(const char *tp_category,
11787 const char *tp_name)
11789 char file[PATH_MAX];
11792 ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11793 tracefs_path(), tp_category, tp_name);
11796 if (ret >= sizeof(file)) {
11797 pr_debug("tracepoint %s/%s path is too long\n",
11798 tp_category, tp_name);
11801 return parse_uint_from_file(file, "%d\n");
11804 static int perf_event_open_tracepoint(const char *tp_category,
11805 const char *tp_name)
11807 const size_t attr_sz = sizeof(struct perf_event_attr);
11808 struct perf_event_attr attr;
11809 char errmsg[STRERR_BUFSIZE];
11810 int tp_id, pfd, err;
11812 tp_id = determine_tracepoint_id(tp_category, tp_name);
11814 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11815 tp_category, tp_name,
11816 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11820 memset(&attr, 0, attr_sz);
11821 attr.type = PERF_TYPE_TRACEPOINT;
11822 attr.size = attr_sz;
11823 attr.config = tp_id;
11825 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11826 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11829 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11830 tp_category, tp_name,
11831 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11837 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11838 const char *tp_category,
11839 const char *tp_name,
11840 const struct bpf_tracepoint_opts *opts)
11842 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11843 char errmsg[STRERR_BUFSIZE];
11844 struct bpf_link *link;
11847 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11848 return libbpf_err_ptr(-EINVAL);
11850 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11852 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11854 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11855 prog->name, tp_category, tp_name,
11856 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11857 return libbpf_err_ptr(pfd);
11859 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11860 err = libbpf_get_error(link);
11863 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11864 prog->name, tp_category, tp_name,
11865 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11866 return libbpf_err_ptr(err);
11871 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11872 const char *tp_category,
11873 const char *tp_name)
11875 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11878 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11880 char *sec_name, *tp_cat, *tp_name;
11884 /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11885 if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11888 sec_name = strdup(prog->sec_name);
11892 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11893 if (str_has_pfx(prog->sec_name, "tp/"))
11894 tp_cat = sec_name + sizeof("tp/") - 1;
11896 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11897 tp_name = strchr(tp_cat, '/');
11905 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11907 return libbpf_get_error(*link);
11910 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11911 const char *tp_name)
11913 char errmsg[STRERR_BUFSIZE];
11914 struct bpf_link *link;
11917 prog_fd = bpf_program__fd(prog);
11919 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11920 return libbpf_err_ptr(-EINVAL);
11923 link = calloc(1, sizeof(*link));
11925 return libbpf_err_ptr(-ENOMEM);
11926 link->detach = &bpf_link__detach_fd;
11928 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11932 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11933 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11934 return libbpf_err_ptr(pfd);
11940 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11942 static const char *const prefixes[] = {
11946 "raw_tracepoint.w",
11949 const char *tp_name = NULL;
11953 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11956 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11959 pfx_len = strlen(prefixes[i]);
11960 /* no auto-attach case of, e.g., SEC("raw_tp") */
11961 if (prog->sec_name[pfx_len] == '\0')
11964 if (prog->sec_name[pfx_len] != '/')
11967 tp_name = prog->sec_name + pfx_len + 1;
11972 pr_warn("prog '%s': invalid section name '%s'\n",
11973 prog->name, prog->sec_name);
11977 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11978 return libbpf_get_error(*link);
11981 /* Common logic for all BPF program types that attach to a btf_id */
11982 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11983 const struct bpf_trace_opts *opts)
11985 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11986 char errmsg[STRERR_BUFSIZE];
11987 struct bpf_link *link;
11990 if (!OPTS_VALID(opts, bpf_trace_opts))
11991 return libbpf_err_ptr(-EINVAL);
11993 prog_fd = bpf_program__fd(prog);
11995 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11996 return libbpf_err_ptr(-EINVAL);
11999 link = calloc(1, sizeof(*link));
12001 return libbpf_err_ptr(-ENOMEM);
12002 link->detach = &bpf_link__detach_fd;
12004 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12005 link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12006 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12010 pr_warn("prog '%s': failed to attach: %s\n",
12011 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12012 return libbpf_err_ptr(pfd);
12018 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12020 return bpf_program__attach_btf_id(prog, NULL);
12023 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12024 const struct bpf_trace_opts *opts)
12026 return bpf_program__attach_btf_id(prog, opts);
12029 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12031 return bpf_program__attach_btf_id(prog, NULL);
12034 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12036 *link = bpf_program__attach_trace(prog);
12037 return libbpf_get_error(*link);
12040 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12042 *link = bpf_program__attach_lsm(prog);
12043 return libbpf_get_error(*link);
12046 static struct bpf_link *
12047 bpf_program_attach_fd(const struct bpf_program *prog,
12048 int target_fd, const char *target_name,
12049 const struct bpf_link_create_opts *opts)
12051 enum bpf_attach_type attach_type;
12052 char errmsg[STRERR_BUFSIZE];
12053 struct bpf_link *link;
12054 int prog_fd, link_fd;
12056 prog_fd = bpf_program__fd(prog);
12058 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12059 return libbpf_err_ptr(-EINVAL);
12062 link = calloc(1, sizeof(*link));
12064 return libbpf_err_ptr(-ENOMEM);
12065 link->detach = &bpf_link__detach_fd;
12067 attach_type = bpf_program__expected_attach_type(prog);
12068 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12072 pr_warn("prog '%s': failed to attach to %s: %s\n",
12073 prog->name, target_name,
12074 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12075 return libbpf_err_ptr(link_fd);
12077 link->fd = link_fd;
12082 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12084 return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12088 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12090 return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12093 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12095 /* target_fd/target_ifindex use the same field in LINK_CREATE */
12096 return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12100 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12101 const struct bpf_tcx_opts *opts)
12103 LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12107 if (!OPTS_VALID(opts, bpf_tcx_opts))
12108 return libbpf_err_ptr(-EINVAL);
12110 relative_id = OPTS_GET(opts, relative_id, 0);
12111 relative_fd = OPTS_GET(opts, relative_fd, 0);
12113 /* validate we don't have unexpected combinations of non-zero fields */
12115 pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12117 return libbpf_err_ptr(-EINVAL);
12119 if (relative_fd && relative_id) {
12120 pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12122 return libbpf_err_ptr(-EINVAL);
12125 link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12126 link_create_opts.tcx.relative_fd = relative_fd;
12127 link_create_opts.tcx.relative_id = relative_id;
12128 link_create_opts.flags = OPTS_GET(opts, flags, 0);
12130 /* target_fd/target_ifindex use the same field in LINK_CREATE */
12131 return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12135 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12136 const struct bpf_netkit_opts *opts)
12138 LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12142 if (!OPTS_VALID(opts, bpf_netkit_opts))
12143 return libbpf_err_ptr(-EINVAL);
12145 relative_id = OPTS_GET(opts, relative_id, 0);
12146 relative_fd = OPTS_GET(opts, relative_fd, 0);
12148 /* validate we don't have unexpected combinations of non-zero fields */
12150 pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12152 return libbpf_err_ptr(-EINVAL);
12154 if (relative_fd && relative_id) {
12155 pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12157 return libbpf_err_ptr(-EINVAL);
12160 link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12161 link_create_opts.netkit.relative_fd = relative_fd;
12162 link_create_opts.netkit.relative_id = relative_id;
12163 link_create_opts.flags = OPTS_GET(opts, flags, 0);
12165 return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12168 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12170 const char *attach_func_name)
12174 if (!!target_fd != !!attach_func_name) {
12175 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12177 return libbpf_err_ptr(-EINVAL);
12180 if (prog->type != BPF_PROG_TYPE_EXT) {
12181 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12183 return libbpf_err_ptr(-EINVAL);
12187 LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12189 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12191 return libbpf_err_ptr(btf_id);
12193 target_opts.target_btf_id = btf_id;
12195 return bpf_program_attach_fd(prog, target_fd, "freplace",
12198 /* no target, so use raw_tracepoint_open for compatibility
12201 return bpf_program__attach_trace(prog);
12206 bpf_program__attach_iter(const struct bpf_program *prog,
12207 const struct bpf_iter_attach_opts *opts)
12209 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12210 char errmsg[STRERR_BUFSIZE];
12211 struct bpf_link *link;
12212 int prog_fd, link_fd;
12213 __u32 target_fd = 0;
12215 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12216 return libbpf_err_ptr(-EINVAL);
12218 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12219 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12221 prog_fd = bpf_program__fd(prog);
12223 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12224 return libbpf_err_ptr(-EINVAL);
12227 link = calloc(1, sizeof(*link));
12229 return libbpf_err_ptr(-ENOMEM);
12230 link->detach = &bpf_link__detach_fd;
12232 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12233 &link_create_opts);
12237 pr_warn("prog '%s': failed to attach to iterator: %s\n",
12238 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12239 return libbpf_err_ptr(link_fd);
12241 link->fd = link_fd;
12245 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12247 *link = bpf_program__attach_iter(prog, NULL);
12248 return libbpf_get_error(*link);
12251 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12252 const struct bpf_netfilter_opts *opts)
12254 LIBBPF_OPTS(bpf_link_create_opts, lopts);
12255 struct bpf_link *link;
12256 int prog_fd, link_fd;
12258 if (!OPTS_VALID(opts, bpf_netfilter_opts))
12259 return libbpf_err_ptr(-EINVAL);
12261 prog_fd = bpf_program__fd(prog);
12263 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12264 return libbpf_err_ptr(-EINVAL);
12267 link = calloc(1, sizeof(*link));
12269 return libbpf_err_ptr(-ENOMEM);
12271 link->detach = &bpf_link__detach_fd;
12273 lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12274 lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12275 lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12276 lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12278 link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12280 char errmsg[STRERR_BUFSIZE];
12284 pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12285 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12286 return libbpf_err_ptr(link_fd);
12288 link->fd = link_fd;
12293 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12295 struct bpf_link *link = NULL;
12298 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12299 return libbpf_err_ptr(-EOPNOTSUPP);
12301 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12303 return libbpf_err_ptr(err);
12305 /* When calling bpf_program__attach() explicitly, auto-attach support
12306 * is expected to work, so NULL returned link is considered an error.
12307 * This is different for skeleton's attach, see comment in
12308 * bpf_object__attach_skeleton().
12311 return libbpf_err_ptr(-EOPNOTSUPP);
12316 struct bpf_link_struct_ops {
12317 struct bpf_link link;
12321 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12323 struct bpf_link_struct_ops *st_link;
12326 st_link = container_of(link, struct bpf_link_struct_ops, link);
12328 if (st_link->map_fd < 0)
12329 /* w/o a real link */
12330 return bpf_map_delete_elem(link->fd, &zero);
12332 return close(link->fd);
12335 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12337 struct bpf_link_struct_ops *link;
12341 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12342 return libbpf_err_ptr(-EINVAL);
12344 link = calloc(1, sizeof(*link));
12346 return libbpf_err_ptr(-EINVAL);
12348 /* kern_vdata should be prepared during the loading phase. */
12349 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12350 /* It can be EBUSY if the map has been used to create or
12351 * update a link before. We don't allow updating the value of
12352 * a struct_ops once it is set. That ensures that the value
12353 * never changed. So, it is safe to skip EBUSY.
12355 if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12357 return libbpf_err_ptr(err);
12360 link->link.detach = bpf_link__detach_struct_ops;
12362 if (!(map->def.map_flags & BPF_F_LINK)) {
12363 /* w/o a real link */
12364 link->link.fd = map->fd;
12366 return &link->link;
12369 fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12372 return libbpf_err_ptr(fd);
12375 link->link.fd = fd;
12376 link->map_fd = map->fd;
12378 return &link->link;
12382 * Swap the back struct_ops of a link with a new struct_ops map.
12384 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12386 struct bpf_link_struct_ops *st_ops_link;
12390 if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12393 st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12394 /* Ensure the type of a link is correct */
12395 if (st_ops_link->map_fd < 0)
12398 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12399 /* It can be EBUSY if the map has been used to create or
12400 * update a link before. We don't allow updating the value of
12401 * a struct_ops once it is set. That ensures that the value
12402 * never changed. So, it is safe to skip EBUSY.
12404 if (err && err != -EBUSY)
12407 err = bpf_link_update(link->fd, map->fd, NULL);
12411 st_ops_link->map_fd = map->fd;
12416 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12417 void *private_data);
12419 static enum bpf_perf_event_ret
12420 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12421 void **copy_mem, size_t *copy_size,
12422 bpf_perf_event_print_t fn, void *private_data)
12424 struct perf_event_mmap_page *header = mmap_mem;
12425 __u64 data_head = ring_buffer_read_head(header);
12426 __u64 data_tail = header->data_tail;
12427 void *base = ((__u8 *)header) + page_size;
12428 int ret = LIBBPF_PERF_EVENT_CONT;
12429 struct perf_event_header *ehdr;
12432 while (data_head != data_tail) {
12433 ehdr = base + (data_tail & (mmap_size - 1));
12434 ehdr_size = ehdr->size;
12436 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12437 void *copy_start = ehdr;
12438 size_t len_first = base + mmap_size - copy_start;
12439 size_t len_secnd = ehdr_size - len_first;
12441 if (*copy_size < ehdr_size) {
12443 *copy_mem = malloc(ehdr_size);
12446 ret = LIBBPF_PERF_EVENT_ERROR;
12449 *copy_size = ehdr_size;
12452 memcpy(*copy_mem, copy_start, len_first);
12453 memcpy(*copy_mem + len_first, base, len_secnd);
12457 ret = fn(ehdr, private_data);
12458 data_tail += ehdr_size;
12459 if (ret != LIBBPF_PERF_EVENT_CONT)
12463 ring_buffer_write_tail(header, data_tail);
12464 return libbpf_err(ret);
12467 struct perf_buffer;
12469 struct perf_buffer_params {
12470 struct perf_event_attr *attr;
12471 /* if event_cb is specified, it takes precendence */
12472 perf_buffer_event_fn event_cb;
12473 /* sample_cb and lost_cb are higher-level common-case callbacks */
12474 perf_buffer_sample_fn sample_cb;
12475 perf_buffer_lost_fn lost_cb;
12482 struct perf_cpu_buf {
12483 struct perf_buffer *pb;
12484 void *base; /* mmap()'ed memory */
12485 void *buf; /* for reconstructing segmented data */
12492 struct perf_buffer {
12493 perf_buffer_event_fn event_cb;
12494 perf_buffer_sample_fn sample_cb;
12495 perf_buffer_lost_fn lost_cb;
12496 void *ctx; /* passed into callbacks */
12500 struct perf_cpu_buf **cpu_bufs;
12501 struct epoll_event *events;
12502 int cpu_cnt; /* number of allocated CPU buffers */
12503 int epoll_fd; /* perf event FD */
12504 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12507 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12508 struct perf_cpu_buf *cpu_buf)
12512 if (cpu_buf->base &&
12513 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12514 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12515 if (cpu_buf->fd >= 0) {
12516 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12517 close(cpu_buf->fd);
12519 free(cpu_buf->buf);
12523 void perf_buffer__free(struct perf_buffer *pb)
12527 if (IS_ERR_OR_NULL(pb))
12529 if (pb->cpu_bufs) {
12530 for (i = 0; i < pb->cpu_cnt; i++) {
12531 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12536 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12537 perf_buffer__free_cpu_buf(pb, cpu_buf);
12539 free(pb->cpu_bufs);
12541 if (pb->epoll_fd >= 0)
12542 close(pb->epoll_fd);
12547 static struct perf_cpu_buf *
12548 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12549 int cpu, int map_key)
12551 struct perf_cpu_buf *cpu_buf;
12552 char msg[STRERR_BUFSIZE];
12555 cpu_buf = calloc(1, sizeof(*cpu_buf));
12557 return ERR_PTR(-ENOMEM);
12560 cpu_buf->cpu = cpu;
12561 cpu_buf->map_key = map_key;
12563 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12564 -1, PERF_FLAG_FD_CLOEXEC);
12565 if (cpu_buf->fd < 0) {
12567 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12568 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12572 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12573 PROT_READ | PROT_WRITE, MAP_SHARED,
12575 if (cpu_buf->base == MAP_FAILED) {
12576 cpu_buf->base = NULL;
12578 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12579 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12583 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12585 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12586 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12593 perf_buffer__free_cpu_buf(pb, cpu_buf);
12594 return (struct perf_cpu_buf *)ERR_PTR(err);
12597 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12598 struct perf_buffer_params *p);
12600 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12601 perf_buffer_sample_fn sample_cb,
12602 perf_buffer_lost_fn lost_cb,
12604 const struct perf_buffer_opts *opts)
12606 const size_t attr_sz = sizeof(struct perf_event_attr);
12607 struct perf_buffer_params p = {};
12608 struct perf_event_attr attr;
12609 __u32 sample_period;
12611 if (!OPTS_VALID(opts, perf_buffer_opts))
12612 return libbpf_err_ptr(-EINVAL);
12614 sample_period = OPTS_GET(opts, sample_period, 1);
12615 if (!sample_period)
12618 memset(&attr, 0, attr_sz);
12619 attr.size = attr_sz;
12620 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12621 attr.type = PERF_TYPE_SOFTWARE;
12622 attr.sample_type = PERF_SAMPLE_RAW;
12623 attr.sample_period = sample_period;
12624 attr.wakeup_events = sample_period;
12627 p.sample_cb = sample_cb;
12628 p.lost_cb = lost_cb;
12631 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12634 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12635 struct perf_event_attr *attr,
12636 perf_buffer_event_fn event_cb, void *ctx,
12637 const struct perf_buffer_raw_opts *opts)
12639 struct perf_buffer_params p = {};
12642 return libbpf_err_ptr(-EINVAL);
12644 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12645 return libbpf_err_ptr(-EINVAL);
12648 p.event_cb = event_cb;
12650 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12651 p.cpus = OPTS_GET(opts, cpus, NULL);
12652 p.map_keys = OPTS_GET(opts, map_keys, NULL);
12654 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12657 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12658 struct perf_buffer_params *p)
12660 const char *online_cpus_file = "/sys/devices/system/cpu/online";
12661 struct bpf_map_info map;
12662 char msg[STRERR_BUFSIZE];
12663 struct perf_buffer *pb;
12664 bool *online = NULL;
12665 __u32 map_info_len;
12668 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12669 pr_warn("page count should be power of two, but is %zu\n",
12671 return ERR_PTR(-EINVAL);
12674 /* best-effort sanity checks */
12675 memset(&map, 0, sizeof(map));
12676 map_info_len = sizeof(map);
12677 err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12680 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12681 * -EBADFD, -EFAULT, or -E2BIG on real error
12683 if (err != -EINVAL) {
12684 pr_warn("failed to get map info for map FD %d: %s\n",
12685 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12686 return ERR_PTR(err);
12688 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12691 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12692 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12694 return ERR_PTR(-EINVAL);
12698 pb = calloc(1, sizeof(*pb));
12700 return ERR_PTR(-ENOMEM);
12702 pb->event_cb = p->event_cb;
12703 pb->sample_cb = p->sample_cb;
12704 pb->lost_cb = p->lost_cb;
12707 pb->page_size = getpagesize();
12708 pb->mmap_size = pb->page_size * page_cnt;
12709 pb->map_fd = map_fd;
12711 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12712 if (pb->epoll_fd < 0) {
12714 pr_warn("failed to create epoll instance: %s\n",
12715 libbpf_strerror_r(err, msg, sizeof(msg)));
12719 if (p->cpu_cnt > 0) {
12720 pb->cpu_cnt = p->cpu_cnt;
12722 pb->cpu_cnt = libbpf_num_possible_cpus();
12723 if (pb->cpu_cnt < 0) {
12727 if (map.max_entries && map.max_entries < pb->cpu_cnt)
12728 pb->cpu_cnt = map.max_entries;
12731 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12734 pr_warn("failed to allocate events: out of memory\n");
12737 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12738 if (!pb->cpu_bufs) {
12740 pr_warn("failed to allocate buffers: out of memory\n");
12744 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12746 pr_warn("failed to get online CPU mask: %d\n", err);
12750 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12751 struct perf_cpu_buf *cpu_buf;
12754 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12755 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12757 /* in case user didn't explicitly requested particular CPUs to
12758 * be attached to, skip offline/not present CPUs
12760 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12763 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12764 if (IS_ERR(cpu_buf)) {
12765 err = PTR_ERR(cpu_buf);
12769 pb->cpu_bufs[j] = cpu_buf;
12771 err = bpf_map_update_elem(pb->map_fd, &map_key,
12775 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12776 cpu, map_key, cpu_buf->fd,
12777 libbpf_strerror_r(err, msg, sizeof(msg)));
12781 pb->events[j].events = EPOLLIN;
12782 pb->events[j].data.ptr = cpu_buf;
12783 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12784 &pb->events[j]) < 0) {
12786 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12788 libbpf_strerror_r(err, msg, sizeof(msg)));
12801 perf_buffer__free(pb);
12802 return ERR_PTR(err);
12805 struct perf_sample_raw {
12806 struct perf_event_header header;
12811 struct perf_sample_lost {
12812 struct perf_event_header header;
12815 uint64_t sample_id;
12818 static enum bpf_perf_event_ret
12819 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12821 struct perf_cpu_buf *cpu_buf = ctx;
12822 struct perf_buffer *pb = cpu_buf->pb;
12825 /* user wants full control over parsing perf event */
12827 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12830 case PERF_RECORD_SAMPLE: {
12831 struct perf_sample_raw *s = data;
12834 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12837 case PERF_RECORD_LOST: {
12838 struct perf_sample_lost *s = data;
12841 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12845 pr_warn("unknown perf sample type %d\n", e->type);
12846 return LIBBPF_PERF_EVENT_ERROR;
12848 return LIBBPF_PERF_EVENT_CONT;
12851 static int perf_buffer__process_records(struct perf_buffer *pb,
12852 struct perf_cpu_buf *cpu_buf)
12854 enum bpf_perf_event_ret ret;
12856 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12857 pb->page_size, &cpu_buf->buf,
12858 &cpu_buf->buf_size,
12859 perf_buffer__process_record, cpu_buf);
12860 if (ret != LIBBPF_PERF_EVENT_CONT)
12865 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12867 return pb->epoll_fd;
12870 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12874 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12878 for (i = 0; i < cnt; i++) {
12879 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12881 err = perf_buffer__process_records(pb, cpu_buf);
12883 pr_warn("error while processing records: %d\n", err);
12884 return libbpf_err(err);
12890 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12893 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12895 return pb->cpu_cnt;
12899 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12900 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12901 * select()/poll()/epoll() Linux syscalls.
12903 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12905 struct perf_cpu_buf *cpu_buf;
12907 if (buf_idx >= pb->cpu_cnt)
12908 return libbpf_err(-EINVAL);
12910 cpu_buf = pb->cpu_bufs[buf_idx];
12912 return libbpf_err(-ENOENT);
12914 return cpu_buf->fd;
12917 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12919 struct perf_cpu_buf *cpu_buf;
12921 if (buf_idx >= pb->cpu_cnt)
12922 return libbpf_err(-EINVAL);
12924 cpu_buf = pb->cpu_bufs[buf_idx];
12926 return libbpf_err(-ENOENT);
12928 *buf = cpu_buf->base;
12929 *buf_size = pb->mmap_size;
12934 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12935 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12936 * consume, do nothing and return success.
12941 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12943 struct perf_cpu_buf *cpu_buf;
12945 if (buf_idx >= pb->cpu_cnt)
12946 return libbpf_err(-EINVAL);
12948 cpu_buf = pb->cpu_bufs[buf_idx];
12950 return libbpf_err(-ENOENT);
12952 return perf_buffer__process_records(pb, cpu_buf);
12955 int perf_buffer__consume(struct perf_buffer *pb)
12959 for (i = 0; i < pb->cpu_cnt; i++) {
12960 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12965 err = perf_buffer__process_records(pb, cpu_buf);
12967 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12968 return libbpf_err(err);
12974 int bpf_program__set_attach_target(struct bpf_program *prog,
12975 int attach_prog_fd,
12976 const char *attach_func_name)
12978 int btf_obj_fd = 0, btf_id = 0, err;
12980 if (!prog || attach_prog_fd < 0)
12981 return libbpf_err(-EINVAL);
12983 if (prog->obj->loaded)
12984 return libbpf_err(-EINVAL);
12986 if (attach_prog_fd && !attach_func_name) {
12987 /* remember attach_prog_fd and let bpf_program__load() find
12988 * BTF ID during the program load
12990 prog->attach_prog_fd = attach_prog_fd;
12994 if (attach_prog_fd) {
12995 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12998 return libbpf_err(btf_id);
13000 if (!attach_func_name)
13001 return libbpf_err(-EINVAL);
13003 /* load btf_vmlinux, if not yet */
13004 err = bpf_object__load_vmlinux_btf(prog->obj, true);
13006 return libbpf_err(err);
13007 err = find_kernel_btf_id(prog->obj, attach_func_name,
13008 prog->expected_attach_type,
13009 &btf_obj_fd, &btf_id);
13011 return libbpf_err(err);
13014 prog->attach_btf_id = btf_id;
13015 prog->attach_btf_obj_fd = btf_obj_fd;
13016 prog->attach_prog_fd = attach_prog_fd;
13020 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13022 int err = 0, n, len, start, end = -1;
13028 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13030 if (*s == ',' || *s == '\n') {
13034 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13035 if (n <= 0 || n > 2) {
13036 pr_warn("Failed to get CPU range %s: %d\n", s, n);
13039 } else if (n == 1) {
13042 if (start < 0 || start > end) {
13043 pr_warn("Invalid CPU range [%d,%d] in %s\n",
13048 tmp = realloc(*mask, end + 1);
13054 memset(tmp + *mask_sz, 0, start - *mask_sz);
13055 memset(tmp + start, 1, end - start + 1);
13056 *mask_sz = end + 1;
13060 pr_warn("Empty CPU range\n");
13070 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13072 int fd, err = 0, len;
13075 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13078 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13081 len = read(fd, buf, sizeof(buf));
13084 err = len ? -errno : -EINVAL;
13085 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13088 if (len >= sizeof(buf)) {
13089 pr_warn("CPU mask is too big in file %s\n", fcpu);
13094 return parse_cpu_mask_str(buf, mask, mask_sz);
13097 int libbpf_num_possible_cpus(void)
13099 static const char *fcpu = "/sys/devices/system/cpu/possible";
13101 int err, n, i, tmp_cpus;
13104 tmp_cpus = READ_ONCE(cpus);
13108 err = parse_cpu_mask_file(fcpu, &mask, &n);
13110 return libbpf_err(err);
13113 for (i = 0; i < n; i++) {
13119 WRITE_ONCE(cpus, tmp_cpus);
13123 static int populate_skeleton_maps(const struct bpf_object *obj,
13124 struct bpf_map_skeleton *maps,
13129 for (i = 0; i < map_cnt; i++) {
13130 struct bpf_map **map = maps[i].map;
13131 const char *name = maps[i].name;
13132 void **mmaped = maps[i].mmaped;
13134 *map = bpf_object__find_map_by_name(obj, name);
13136 pr_warn("failed to find skeleton map '%s'\n", name);
13140 /* externs shouldn't be pre-setup from user code */
13141 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13142 *mmaped = (*map)->mmaped;
13147 static int populate_skeleton_progs(const struct bpf_object *obj,
13148 struct bpf_prog_skeleton *progs,
13153 for (i = 0; i < prog_cnt; i++) {
13154 struct bpf_program **prog = progs[i].prog;
13155 const char *name = progs[i].name;
13157 *prog = bpf_object__find_program_by_name(obj, name);
13159 pr_warn("failed to find skeleton program '%s'\n", name);
13166 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13167 const struct bpf_object_open_opts *opts)
13169 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13170 .object_name = s->name,
13172 struct bpf_object *obj;
13175 /* Attempt to preserve opts->object_name, unless overriden by user
13176 * explicitly. Overwriting object name for skeletons is discouraged,
13177 * as it breaks global data maps, because they contain object name
13178 * prefix as their own map name prefix. When skeleton is generated,
13179 * bpftool is making an assumption that this name will stay the same.
13182 memcpy(&skel_opts, opts, sizeof(*opts));
13183 if (!opts->object_name)
13184 skel_opts.object_name = s->name;
13187 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13188 err = libbpf_get_error(obj);
13190 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13192 return libbpf_err(err);
13196 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13198 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13199 return libbpf_err(err);
13202 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13204 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13205 return libbpf_err(err);
13211 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13213 int err, len, var_idx, i;
13214 const char *var_name;
13215 const struct bpf_map *map;
13218 const struct btf_type *map_type, *var_type;
13219 const struct bpf_var_skeleton *var_skel;
13220 struct btf_var_secinfo *var;
13223 return libbpf_err(-EINVAL);
13225 btf = bpf_object__btf(s->obj);
13227 pr_warn("subskeletons require BTF at runtime (object %s)\n",
13228 bpf_object__name(s->obj));
13229 return libbpf_err(-errno);
13232 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13234 pr_warn("failed to populate subskeleton maps: %d\n", err);
13235 return libbpf_err(err);
13238 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13240 pr_warn("failed to populate subskeleton maps: %d\n", err);
13241 return libbpf_err(err);
13244 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13245 var_skel = &s->vars[var_idx];
13246 map = *var_skel->map;
13247 map_type_id = bpf_map__btf_value_type_id(map);
13248 map_type = btf__type_by_id(btf, map_type_id);
13250 if (!btf_is_datasec(map_type)) {
13251 pr_warn("type for map '%1$s' is not a datasec: %2$s",
13252 bpf_map__name(map),
13253 __btf_kind_str(btf_kind(map_type)));
13254 return libbpf_err(-EINVAL);
13257 len = btf_vlen(map_type);
13258 var = btf_var_secinfos(map_type);
13259 for (i = 0; i < len; i++, var++) {
13260 var_type = btf__type_by_id(btf, var->type);
13261 var_name = btf__name_by_offset(btf, var_type->name_off);
13262 if (strcmp(var_name, var_skel->name) == 0) {
13263 *var_skel->addr = map->mmaped + var->offset;
13271 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13281 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13285 err = bpf_object__load(*s->obj);
13287 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13288 return libbpf_err(err);
13291 for (i = 0; i < s->map_cnt; i++) {
13292 struct bpf_map *map = *s->maps[i].map;
13293 size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13294 int prot, map_fd = bpf_map__fd(map);
13295 void **mmaped = s->maps[i].mmaped;
13300 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13305 if (map->def.map_flags & BPF_F_RDONLY_PROG)
13308 prot = PROT_READ | PROT_WRITE;
13310 /* Remap anonymous mmap()-ed "map initialization image" as
13311 * a BPF map-backed mmap()-ed memory, but preserving the same
13312 * memory address. This will cause kernel to change process'
13313 * page table to point to a different piece of kernel memory,
13314 * but from userspace point of view memory address (and its
13315 * contents, being identical at this point) will stay the
13316 * same. This mapping will be released by bpf_object__close()
13317 * as per normal clean up procedure, so we don't need to worry
13318 * about it from skeleton's clean up perspective.
13320 *mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13321 if (*mmaped == MAP_FAILED) {
13324 pr_warn("failed to re-mmap() map '%s': %d\n",
13325 bpf_map__name(map), err);
13326 return libbpf_err(err);
13333 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13337 for (i = 0; i < s->prog_cnt; i++) {
13338 struct bpf_program *prog = *s->progs[i].prog;
13339 struct bpf_link **link = s->progs[i].link;
13341 if (!prog->autoload || !prog->autoattach)
13344 /* auto-attaching not supported for this program */
13345 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13348 /* if user already set the link manually, don't attempt auto-attach */
13352 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13354 pr_warn("prog '%s': failed to auto-attach: %d\n",
13355 bpf_program__name(prog), err);
13356 return libbpf_err(err);
13359 /* It's possible that for some SEC() definitions auto-attach
13360 * is supported in some cases (e.g., if definition completely
13361 * specifies target information), but is not in other cases.
13362 * SEC("uprobe") is one such case. If user specified target
13363 * binary and function name, such BPF program can be
13364 * auto-attached. But if not, it shouldn't trigger skeleton's
13365 * attach to fail. It should just be skipped.
13366 * attach_fn signals such case with returning 0 (no error) and
13367 * setting link to NULL.
13374 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13378 for (i = 0; i < s->prog_cnt; i++) {
13379 struct bpf_link **link = s->progs[i].link;
13381 bpf_link__destroy(*link);
13386 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13392 bpf_object__detach_skeleton(s);
13394 bpf_object__close(*s->obj);