xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 7df45f35313c1ae083dac72c066b3aebfc7fc0cd)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
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>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48 
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
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);
73 static int map_set_def_max_entries(struct bpf_map *map);
74 
75 static const char * const attach_type_name[] = {
76 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
77 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
78 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
79 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
80 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
81 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
82 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
83 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
84 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
85 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_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_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
91 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
92 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
93 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
94 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
95 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
96 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
97 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
98 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
99 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
100 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
101 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
102 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
103 	[BPF_LIRC_MODE2]		= "lirc_mode2",
104 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
105 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
106 	[BPF_TRACE_FENTRY]		= "trace_fentry",
107 	[BPF_TRACE_FEXIT]		= "trace_fexit",
108 	[BPF_MODIFY_RETURN]		= "modify_return",
109 	[BPF_LSM_MAC]			= "lsm_mac",
110 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
111 	[BPF_SK_LOOKUP]			= "sk_lookup",
112 	[BPF_TRACE_ITER]		= "trace_iter",
113 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
114 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
115 	[BPF_XDP]			= "xdp",
116 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
117 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
118 	[BPF_PERF_EVENT]		= "perf_event",
119 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
120 	[BPF_STRUCT_OPS]		= "struct_ops",
121 	[BPF_NETFILTER]			= "netfilter",
122 	[BPF_TCX_INGRESS]		= "tcx_ingress",
123 	[BPF_TCX_EGRESS]		= "tcx_egress",
124 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
125 };
126 
127 static const char * const link_type_name[] = {
128 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
129 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
130 	[BPF_LINK_TYPE_TRACING]			= "tracing",
131 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
132 	[BPF_LINK_TYPE_ITER]			= "iter",
133 	[BPF_LINK_TYPE_NETNS]			= "netns",
134 	[BPF_LINK_TYPE_XDP]			= "xdp",
135 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
136 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
137 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
138 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
139 	[BPF_LINK_TYPE_TCX]			= "tcx",
140 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
141 };
142 
143 static const char * const map_type_name[] = {
144 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
145 	[BPF_MAP_TYPE_HASH]			= "hash",
146 	[BPF_MAP_TYPE_ARRAY]			= "array",
147 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
148 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
149 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
150 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
151 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
152 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
153 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
154 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
155 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
156 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
157 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
158 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
159 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
160 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
161 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
162 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
163 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
164 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
165 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
166 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
167 	[BPF_MAP_TYPE_QUEUE]			= "queue",
168 	[BPF_MAP_TYPE_STACK]			= "stack",
169 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
170 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
171 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
172 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
173 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
174 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
175 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
176 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
177 };
178 
179 static const char * const prog_type_name[] = {
180 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
181 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
182 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
183 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
184 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
185 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
186 	[BPF_PROG_TYPE_XDP]			= "xdp",
187 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
188 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
189 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
190 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
191 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
192 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
193 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
194 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
195 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
196 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
197 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
198 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
199 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
200 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
201 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
202 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
203 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
204 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
205 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
206 	[BPF_PROG_TYPE_TRACING]			= "tracing",
207 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
208 	[BPF_PROG_TYPE_EXT]			= "ext",
209 	[BPF_PROG_TYPE_LSM]			= "lsm",
210 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
211 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
212 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
213 };
214 
__base_pr(enum libbpf_print_level level,const char * format,va_list args)215 static int __base_pr(enum libbpf_print_level level, const char *format,
216 		     va_list args)
217 {
218 	if (level == LIBBPF_DEBUG)
219 		return 0;
220 
221 	return vfprintf(stderr, format, args);
222 }
223 
224 static libbpf_print_fn_t __libbpf_pr = __base_pr;
225 
libbpf_set_print(libbpf_print_fn_t fn)226 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
227 {
228 	libbpf_print_fn_t old_print_fn;
229 
230 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
231 
232 	return old_print_fn;
233 }
234 
235 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)236 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
237 {
238 	va_list args;
239 	int old_errno;
240 	libbpf_print_fn_t print_fn;
241 
242 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
243 	if (!print_fn)
244 		return;
245 
246 	old_errno = errno;
247 
248 	va_start(args, format);
249 	print_fn(level, format, args);
250 	va_end(args);
251 
252 	errno = old_errno;
253 }
254 
pr_perm_msg(int err)255 static void pr_perm_msg(int err)
256 {
257 	struct rlimit limit;
258 	char buf[100];
259 
260 	if (err != -EPERM || geteuid() != 0)
261 		return;
262 
263 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
264 	if (err)
265 		return;
266 
267 	if (limit.rlim_cur == RLIM_INFINITY)
268 		return;
269 
270 	if (limit.rlim_cur < 1024)
271 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
272 	else if (limit.rlim_cur < 1024*1024)
273 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
274 	else
275 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
276 
277 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
278 		buf);
279 }
280 
281 #define STRERR_BUFSIZE  128
282 
283 /* Copied from tools/perf/util/util.h */
284 #ifndef zfree
285 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
286 #endif
287 
288 #ifndef zclose
289 # define zclose(fd) ({			\
290 	int ___err = 0;			\
291 	if ((fd) >= 0)			\
292 		___err = close((fd));	\
293 	fd = -1;			\
294 	___err; })
295 #endif
296 
ptr_to_u64(const void * ptr)297 static inline __u64 ptr_to_u64(const void *ptr)
298 {
299 	return (__u64) (unsigned long) ptr;
300 }
301 
libbpf_set_strict_mode(enum libbpf_strict_mode mode)302 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
303 {
304 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
305 	return 0;
306 }
307 
libbpf_major_version(void)308 __u32 libbpf_major_version(void)
309 {
310 	return LIBBPF_MAJOR_VERSION;
311 }
312 
libbpf_minor_version(void)313 __u32 libbpf_minor_version(void)
314 {
315 	return LIBBPF_MINOR_VERSION;
316 }
317 
libbpf_version_string(void)318 const char *libbpf_version_string(void)
319 {
320 #define __S(X) #X
321 #define _S(X) __S(X)
322 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
323 #undef _S
324 #undef __S
325 }
326 
327 enum reloc_type {
328 	RELO_LD64,
329 	RELO_CALL,
330 	RELO_DATA,
331 	RELO_EXTERN_LD64,
332 	RELO_EXTERN_CALL,
333 	RELO_SUBPROG_ADDR,
334 	RELO_CORE,
335 };
336 
337 struct reloc_desc {
338 	enum reloc_type type;
339 	int insn_idx;
340 	union {
341 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
342 		struct {
343 			int map_idx;
344 			int sym_off;
345 			int ext_idx;
346 		};
347 	};
348 };
349 
350 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
351 enum sec_def_flags {
352 	SEC_NONE = 0,
353 	/* expected_attach_type is optional, if kernel doesn't support that */
354 	SEC_EXP_ATTACH_OPT = 1,
355 	/* legacy, only used by libbpf_get_type_names() and
356 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
357 	 * This used to be associated with cgroup (and few other) BPF programs
358 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
359 	 * meaningless nowadays, though.
360 	 */
361 	SEC_ATTACHABLE = 2,
362 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
363 	/* attachment target is specified through BTF ID in either kernel or
364 	 * other BPF program's BTF object
365 	 */
366 	SEC_ATTACH_BTF = 4,
367 	/* BPF program type allows sleeping/blocking in kernel */
368 	SEC_SLEEPABLE = 8,
369 	/* BPF program support non-linear XDP buffer */
370 	SEC_XDP_FRAGS = 16,
371 	/* Setup proper attach type for usdt probes. */
372 	SEC_USDT = 32,
373 };
374 
375 struct bpf_sec_def {
376 	char *sec;
377 	enum bpf_prog_type prog_type;
378 	enum bpf_attach_type expected_attach_type;
379 	long cookie;
380 	int handler_id;
381 
382 	libbpf_prog_setup_fn_t prog_setup_fn;
383 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
384 	libbpf_prog_attach_fn_t prog_attach_fn;
385 };
386 
387 /*
388  * bpf_prog should be a better name but it has been used in
389  * linux/filter.h.
390  */
391 struct bpf_program {
392 	char *name;
393 	char *sec_name;
394 	size_t sec_idx;
395 	const struct bpf_sec_def *sec_def;
396 	/* this program's instruction offset (in number of instructions)
397 	 * within its containing ELF section
398 	 */
399 	size_t sec_insn_off;
400 	/* number of original instructions in ELF section belonging to this
401 	 * program, not taking into account subprogram instructions possible
402 	 * appended later during relocation
403 	 */
404 	size_t sec_insn_cnt;
405 	/* Offset (in number of instructions) of the start of instruction
406 	 * belonging to this BPF program  within its containing main BPF
407 	 * program. For the entry-point (main) BPF program, this is always
408 	 * zero. For a sub-program, this gets reset before each of main BPF
409 	 * programs are processed and relocated and is used to determined
410 	 * whether sub-program was already appended to the main program, and
411 	 * if yes, at which instruction offset.
412 	 */
413 	size_t sub_insn_off;
414 
415 	/* instructions that belong to BPF program; insns[0] is located at
416 	 * sec_insn_off instruction within its ELF section in ELF file, so
417 	 * when mapping ELF file instruction index to the local instruction,
418 	 * one needs to subtract sec_insn_off; and vice versa.
419 	 */
420 	struct bpf_insn *insns;
421 	/* actual number of instruction in this BPF program's image; for
422 	 * entry-point BPF programs this includes the size of main program
423 	 * itself plus all the used sub-programs, appended at the end
424 	 */
425 	size_t insns_cnt;
426 
427 	struct reloc_desc *reloc_desc;
428 	int nr_reloc;
429 
430 	/* BPF verifier log settings */
431 	char *log_buf;
432 	size_t log_size;
433 	__u32 log_level;
434 
435 	struct bpf_object *obj;
436 
437 	int fd;
438 	bool autoload;
439 	bool autoattach;
440 	bool mark_btf_static;
441 	enum bpf_prog_type type;
442 	enum bpf_attach_type expected_attach_type;
443 
444 	int prog_ifindex;
445 	__u32 attach_btf_obj_fd;
446 	__u32 attach_btf_id;
447 	__u32 attach_prog_fd;
448 
449 	void *func_info;
450 	__u32 func_info_rec_size;
451 	__u32 func_info_cnt;
452 
453 	void *line_info;
454 	__u32 line_info_rec_size;
455 	__u32 line_info_cnt;
456 	__u32 prog_flags;
457 };
458 
459 struct bpf_struct_ops {
460 	const char *tname;
461 	const struct btf_type *type;
462 	struct bpf_program **progs;
463 	__u32 *kern_func_off;
464 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
465 	void *data;
466 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
467 	 *      btf_vmlinux's format.
468 	 * struct bpf_struct_ops_tcp_congestion_ops {
469 	 *	[... some other kernel fields ...]
470 	 *	struct tcp_congestion_ops data;
471 	 * }
472 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
473 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
474 	 * from "data".
475 	 */
476 	void *kern_vdata;
477 	__u32 type_id;
478 };
479 
480 #define DATA_SEC ".data"
481 #define BSS_SEC ".bss"
482 #define RODATA_SEC ".rodata"
483 #define KCONFIG_SEC ".kconfig"
484 #define KSYMS_SEC ".ksyms"
485 #define STRUCT_OPS_SEC ".struct_ops"
486 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
487 
488 enum libbpf_map_type {
489 	LIBBPF_MAP_UNSPEC,
490 	LIBBPF_MAP_DATA,
491 	LIBBPF_MAP_BSS,
492 	LIBBPF_MAP_RODATA,
493 	LIBBPF_MAP_KCONFIG,
494 };
495 
496 struct bpf_map_def {
497 	unsigned int type;
498 	unsigned int key_size;
499 	unsigned int value_size;
500 	unsigned int max_entries;
501 	unsigned int map_flags;
502 };
503 
504 struct bpf_map {
505 	struct bpf_object *obj;
506 	char *name;
507 	/* real_name is defined for special internal maps (.rodata*,
508 	 * .data*, .bss, .kconfig) and preserves their original ELF section
509 	 * name. This is important to be able to find corresponding BTF
510 	 * DATASEC information.
511 	 */
512 	char *real_name;
513 	int fd;
514 	int sec_idx;
515 	size_t sec_offset;
516 	int map_ifindex;
517 	int inner_map_fd;
518 	struct bpf_map_def def;
519 	__u32 numa_node;
520 	__u32 btf_var_idx;
521 	__u32 btf_key_type_id;
522 	__u32 btf_value_type_id;
523 	__u32 btf_vmlinux_value_type_id;
524 	enum libbpf_map_type libbpf_type;
525 	void *mmaped;
526 	struct bpf_struct_ops *st_ops;
527 	struct bpf_map *inner_map;
528 	void **init_slots;
529 	int init_slots_sz;
530 	char *pin_path;
531 	bool pinned;
532 	bool reused;
533 	bool autocreate;
534 	__u64 map_extra;
535 };
536 
537 enum extern_type {
538 	EXT_UNKNOWN,
539 	EXT_KCFG,
540 	EXT_KSYM,
541 };
542 
543 enum kcfg_type {
544 	KCFG_UNKNOWN,
545 	KCFG_CHAR,
546 	KCFG_BOOL,
547 	KCFG_INT,
548 	KCFG_TRISTATE,
549 	KCFG_CHAR_ARR,
550 };
551 
552 struct extern_desc {
553 	enum extern_type type;
554 	int sym_idx;
555 	int btf_id;
556 	int sec_btf_id;
557 	char *name;
558 	char *essent_name;
559 	bool is_set;
560 	bool is_weak;
561 	union {
562 		struct {
563 			enum kcfg_type type;
564 			int sz;
565 			int align;
566 			int data_off;
567 			bool is_signed;
568 		} kcfg;
569 		struct {
570 			unsigned long long addr;
571 
572 			/* target btf_id of the corresponding kernel var. */
573 			int kernel_btf_obj_fd;
574 			int kernel_btf_id;
575 
576 			/* local btf_id of the ksym extern's type. */
577 			__u32 type_id;
578 			/* BTF fd index to be patched in for insn->off, this is
579 			 * 0 for vmlinux BTF, index in obj->fd_array for module
580 			 * BTF
581 			 */
582 			__s16 btf_fd_idx;
583 		} ksym;
584 	};
585 };
586 
587 struct module_btf {
588 	struct btf *btf;
589 	char *name;
590 	__u32 id;
591 	int fd;
592 	int fd_array_idx;
593 };
594 
595 enum sec_type {
596 	SEC_UNUSED = 0,
597 	SEC_RELO,
598 	SEC_BSS,
599 	SEC_DATA,
600 	SEC_RODATA,
601 };
602 
603 struct elf_sec_desc {
604 	enum sec_type sec_type;
605 	Elf64_Shdr *shdr;
606 	Elf_Data *data;
607 };
608 
609 struct elf_state {
610 	int fd;
611 	const void *obj_buf;
612 	size_t obj_buf_sz;
613 	Elf *elf;
614 	Elf64_Ehdr *ehdr;
615 	Elf_Data *symbols;
616 	Elf_Data *st_ops_data;
617 	Elf_Data *st_ops_link_data;
618 	size_t shstrndx; /* section index for section name strings */
619 	size_t strtabidx;
620 	struct elf_sec_desc *secs;
621 	size_t sec_cnt;
622 	int btf_maps_shndx;
623 	__u32 btf_maps_sec_btf_id;
624 	int text_shndx;
625 	int symbols_shndx;
626 	int st_ops_shndx;
627 	int st_ops_link_shndx;
628 };
629 
630 struct usdt_manager;
631 
632 struct bpf_object {
633 	char name[BPF_OBJ_NAME_LEN];
634 	char license[64];
635 	__u32 kern_version;
636 
637 	struct bpf_program *programs;
638 	size_t nr_programs;
639 	struct bpf_map *maps;
640 	size_t nr_maps;
641 	size_t maps_cap;
642 
643 	char *kconfig;
644 	struct extern_desc *externs;
645 	int nr_extern;
646 	int kconfig_map_idx;
647 
648 	bool loaded;
649 	bool has_subcalls;
650 	bool has_rodata;
651 
652 	struct bpf_gen *gen_loader;
653 
654 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
655 	struct elf_state efile;
656 
657 	struct btf *btf;
658 	struct btf_ext *btf_ext;
659 
660 	/* Parse and load BTF vmlinux if any of the programs in the object need
661 	 * it at load time.
662 	 */
663 	struct btf *btf_vmlinux;
664 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
665 	 * override for vmlinux BTF.
666 	 */
667 	char *btf_custom_path;
668 	/* vmlinux BTF override for CO-RE relocations */
669 	struct btf *btf_vmlinux_override;
670 	/* Lazily initialized kernel module BTFs */
671 	struct module_btf *btf_modules;
672 	bool btf_modules_loaded;
673 	size_t btf_module_cnt;
674 	size_t btf_module_cap;
675 
676 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
677 	char *log_buf;
678 	size_t log_size;
679 	__u32 log_level;
680 
681 	int *fd_array;
682 	size_t fd_array_cap;
683 	size_t fd_array_cnt;
684 
685 	struct usdt_manager *usdt_man;
686 
687 	char path[];
688 };
689 
690 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
691 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
692 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
693 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
694 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
695 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
696 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
697 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
698 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
699 
bpf_program__unload(struct bpf_program * prog)700 void bpf_program__unload(struct bpf_program *prog)
701 {
702 	if (!prog)
703 		return;
704 
705 	zclose(prog->fd);
706 
707 	zfree(&prog->func_info);
708 	zfree(&prog->line_info);
709 }
710 
bpf_program__exit(struct bpf_program * prog)711 static void bpf_program__exit(struct bpf_program *prog)
712 {
713 	if (!prog)
714 		return;
715 
716 	bpf_program__unload(prog);
717 	zfree(&prog->name);
718 	zfree(&prog->sec_name);
719 	zfree(&prog->insns);
720 	zfree(&prog->reloc_desc);
721 
722 	prog->nr_reloc = 0;
723 	prog->insns_cnt = 0;
724 	prog->sec_idx = -1;
725 }
726 
insn_is_subprog_call(const struct bpf_insn * insn)727 static bool insn_is_subprog_call(const struct bpf_insn *insn)
728 {
729 	return BPF_CLASS(insn->code) == BPF_JMP &&
730 	       BPF_OP(insn->code) == BPF_CALL &&
731 	       BPF_SRC(insn->code) == BPF_K &&
732 	       insn->src_reg == BPF_PSEUDO_CALL &&
733 	       insn->dst_reg == 0 &&
734 	       insn->off == 0;
735 }
736 
is_call_insn(const struct bpf_insn * insn)737 static bool is_call_insn(const struct bpf_insn *insn)
738 {
739 	return insn->code == (BPF_JMP | BPF_CALL);
740 }
741 
insn_is_pseudo_func(struct bpf_insn * insn)742 static bool insn_is_pseudo_func(struct bpf_insn *insn)
743 {
744 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
745 }
746 
747 static int
bpf_object__init_prog(struct bpf_object * obj,struct bpf_program * prog,const char * name,size_t sec_idx,const char * sec_name,size_t sec_off,void * insn_data,size_t insn_data_sz)748 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
749 		      const char *name, size_t sec_idx, const char *sec_name,
750 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
751 {
752 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
753 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
754 			sec_name, name, sec_off, insn_data_sz);
755 		return -EINVAL;
756 	}
757 
758 	memset(prog, 0, sizeof(*prog));
759 	prog->obj = obj;
760 
761 	prog->sec_idx = sec_idx;
762 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
763 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
764 	/* insns_cnt can later be increased by appending used subprograms */
765 	prog->insns_cnt = prog->sec_insn_cnt;
766 
767 	prog->type = BPF_PROG_TYPE_UNSPEC;
768 	prog->fd = -1;
769 
770 	/* libbpf's convention for SEC("?abc...") is that it's just like
771 	 * SEC("abc...") but the corresponding bpf_program starts out with
772 	 * autoload set to false.
773 	 */
774 	if (sec_name[0] == '?') {
775 		prog->autoload = false;
776 		/* from now on forget there was ? in section name */
777 		sec_name++;
778 	} else {
779 		prog->autoload = true;
780 	}
781 
782 	prog->autoattach = true;
783 
784 	/* inherit object's log_level */
785 	prog->log_level = obj->log_level;
786 
787 	prog->sec_name = strdup(sec_name);
788 	if (!prog->sec_name)
789 		goto errout;
790 
791 	prog->name = strdup(name);
792 	if (!prog->name)
793 		goto errout;
794 
795 	prog->insns = malloc(insn_data_sz);
796 	if (!prog->insns)
797 		goto errout;
798 	memcpy(prog->insns, insn_data, insn_data_sz);
799 
800 	return 0;
801 errout:
802 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
803 	bpf_program__exit(prog);
804 	return -ENOMEM;
805 }
806 
807 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)808 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
809 			 const char *sec_name, int sec_idx)
810 {
811 	Elf_Data *symbols = obj->efile.symbols;
812 	struct bpf_program *prog, *progs;
813 	void *data = sec_data->d_buf;
814 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
815 	int nr_progs, err, i;
816 	const char *name;
817 	Elf64_Sym *sym;
818 
819 	progs = obj->programs;
820 	nr_progs = obj->nr_programs;
821 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
822 
823 	for (i = 0; i < nr_syms; i++) {
824 		sym = elf_sym_by_idx(obj, i);
825 
826 		if (sym->st_shndx != sec_idx)
827 			continue;
828 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
829 			continue;
830 
831 		prog_sz = sym->st_size;
832 		sec_off = sym->st_value;
833 
834 		name = elf_sym_str(obj, sym->st_name);
835 		if (!name) {
836 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
837 				sec_name, sec_off);
838 			return -LIBBPF_ERRNO__FORMAT;
839 		}
840 
841 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
842 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
843 				sec_name, sec_off);
844 			return -LIBBPF_ERRNO__FORMAT;
845 		}
846 
847 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
848 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
849 			return -ENOTSUP;
850 		}
851 
852 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
853 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
854 
855 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
856 		if (!progs) {
857 			/*
858 			 * In this case the original obj->programs
859 			 * is still valid, so don't need special treat for
860 			 * bpf_close_object().
861 			 */
862 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
863 				sec_name, name);
864 			return -ENOMEM;
865 		}
866 		obj->programs = progs;
867 
868 		prog = &progs[nr_progs];
869 
870 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
871 					    sec_off, data + sec_off, prog_sz);
872 		if (err)
873 			return err;
874 
875 		/* if function is a global/weak symbol, but has restricted
876 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
877 		 * as static to enable more permissive BPF verification mode
878 		 * with more outside context available to BPF verifier
879 		 */
880 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
881 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
882 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
883 			prog->mark_btf_static = true;
884 
885 		nr_progs++;
886 		obj->nr_programs = nr_progs;
887 	}
888 
889 	return 0;
890 }
891 
892 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)893 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
894 {
895 	struct btf_member *m;
896 	int i;
897 
898 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
899 		if (btf_member_bit_offset(t, i) == bit_offset)
900 			return m;
901 	}
902 
903 	return NULL;
904 }
905 
906 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)907 find_member_by_name(const struct btf *btf, const struct btf_type *t,
908 		    const char *name)
909 {
910 	struct btf_member *m;
911 	int i;
912 
913 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
914 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
915 			return m;
916 	}
917 
918 	return NULL;
919 }
920 
921 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
922 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
923 				   const char *name, __u32 kind);
924 
925 static int
find_struct_ops_kern_types(const struct btf * btf,const char * tname,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)926 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
927 			   const struct btf_type **type, __u32 *type_id,
928 			   const struct btf_type **vtype, __u32 *vtype_id,
929 			   const struct btf_member **data_member)
930 {
931 	const struct btf_type *kern_type, *kern_vtype;
932 	const struct btf_member *kern_data_member;
933 	__s32 kern_vtype_id, kern_type_id;
934 	__u32 i;
935 
936 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
937 	if (kern_type_id < 0) {
938 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
939 			tname);
940 		return kern_type_id;
941 	}
942 	kern_type = btf__type_by_id(btf, kern_type_id);
943 
944 	/* Find the corresponding "map_value" type that will be used
945 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
946 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
947 	 * btf_vmlinux.
948 	 */
949 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
950 						tname, BTF_KIND_STRUCT);
951 	if (kern_vtype_id < 0) {
952 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
953 			STRUCT_OPS_VALUE_PREFIX, tname);
954 		return kern_vtype_id;
955 	}
956 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
957 
958 	/* Find "struct tcp_congestion_ops" from
959 	 * struct bpf_struct_ops_tcp_congestion_ops {
960 	 *	[ ... ]
961 	 *	struct tcp_congestion_ops data;
962 	 * }
963 	 */
964 	kern_data_member = btf_members(kern_vtype);
965 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
966 		if (kern_data_member->type == kern_type_id)
967 			break;
968 	}
969 	if (i == btf_vlen(kern_vtype)) {
970 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
971 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
972 		return -EINVAL;
973 	}
974 
975 	*type = kern_type;
976 	*type_id = kern_type_id;
977 	*vtype = kern_vtype;
978 	*vtype_id = kern_vtype_id;
979 	*data_member = kern_data_member;
980 
981 	return 0;
982 }
983 
bpf_map__is_struct_ops(const struct bpf_map * map)984 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
985 {
986 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
987 }
988 
989 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map,const struct btf * btf,const struct btf * kern_btf)990 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
991 					 const struct btf *btf,
992 					 const struct btf *kern_btf)
993 {
994 	const struct btf_member *member, *kern_member, *kern_data_member;
995 	const struct btf_type *type, *kern_type, *kern_vtype;
996 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
997 	struct bpf_struct_ops *st_ops;
998 	void *data, *kern_data;
999 	const char *tname;
1000 	int err;
1001 
1002 	st_ops = map->st_ops;
1003 	type = st_ops->type;
1004 	tname = st_ops->tname;
1005 	err = find_struct_ops_kern_types(kern_btf, tname,
1006 					 &kern_type, &kern_type_id,
1007 					 &kern_vtype, &kern_vtype_id,
1008 					 &kern_data_member);
1009 	if (err)
1010 		return err;
1011 
1012 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1013 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1014 
1015 	map->def.value_size = kern_vtype->size;
1016 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1017 
1018 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1019 	if (!st_ops->kern_vdata)
1020 		return -ENOMEM;
1021 
1022 	data = st_ops->data;
1023 	kern_data_off = kern_data_member->offset / 8;
1024 	kern_data = st_ops->kern_vdata + kern_data_off;
1025 
1026 	member = btf_members(type);
1027 	for (i = 0; i < btf_vlen(type); i++, member++) {
1028 		const struct btf_type *mtype, *kern_mtype;
1029 		__u32 mtype_id, kern_mtype_id;
1030 		void *mdata, *kern_mdata;
1031 		__s64 msize, kern_msize;
1032 		__u32 moff, kern_moff;
1033 		__u32 kern_member_idx;
1034 		const char *mname;
1035 
1036 		mname = btf__name_by_offset(btf, member->name_off);
1037 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1038 		if (!kern_member) {
1039 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1040 				map->name, mname);
1041 			return -ENOTSUP;
1042 		}
1043 
1044 		kern_member_idx = kern_member - btf_members(kern_type);
1045 		if (btf_member_bitfield_size(type, i) ||
1046 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1047 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1048 				map->name, mname);
1049 			return -ENOTSUP;
1050 		}
1051 
1052 		moff = member->offset / 8;
1053 		kern_moff = kern_member->offset / 8;
1054 
1055 		mdata = data + moff;
1056 		kern_mdata = kern_data + kern_moff;
1057 
1058 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1059 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1060 						    &kern_mtype_id);
1061 		if (BTF_INFO_KIND(mtype->info) !=
1062 		    BTF_INFO_KIND(kern_mtype->info)) {
1063 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1064 				map->name, mname, BTF_INFO_KIND(mtype->info),
1065 				BTF_INFO_KIND(kern_mtype->info));
1066 			return -ENOTSUP;
1067 		}
1068 
1069 		if (btf_is_ptr(mtype)) {
1070 			struct bpf_program *prog;
1071 
1072 			prog = st_ops->progs[i];
1073 			if (!prog)
1074 				continue;
1075 
1076 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1077 							    kern_mtype->type,
1078 							    &kern_mtype_id);
1079 
1080 			/* mtype->type must be a func_proto which was
1081 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1082 			 * so only check kern_mtype for func_proto here.
1083 			 */
1084 			if (!btf_is_func_proto(kern_mtype)) {
1085 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1086 					map->name, mname);
1087 				return -ENOTSUP;
1088 			}
1089 
1090 			prog->attach_btf_id = kern_type_id;
1091 			prog->expected_attach_type = kern_member_idx;
1092 
1093 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1094 
1095 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1096 				 map->name, mname, prog->name, moff,
1097 				 kern_moff);
1098 
1099 			continue;
1100 		}
1101 
1102 		msize = btf__resolve_size(btf, mtype_id);
1103 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1104 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1105 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1106 				map->name, mname, (ssize_t)msize,
1107 				(ssize_t)kern_msize);
1108 			return -ENOTSUP;
1109 		}
1110 
1111 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1112 			 map->name, mname, (unsigned int)msize,
1113 			 moff, kern_moff);
1114 		memcpy(kern_mdata, mdata, msize);
1115 	}
1116 
1117 	return 0;
1118 }
1119 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1120 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1121 {
1122 	struct bpf_map *map;
1123 	size_t i;
1124 	int err;
1125 
1126 	for (i = 0; i < obj->nr_maps; i++) {
1127 		map = &obj->maps[i];
1128 
1129 		if (!bpf_map__is_struct_ops(map))
1130 			continue;
1131 
1132 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1133 						    obj->btf_vmlinux);
1134 		if (err)
1135 			return err;
1136 	}
1137 
1138 	return 0;
1139 }
1140 
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data,__u32 map_flags)1141 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1142 				int shndx, Elf_Data *data, __u32 map_flags)
1143 {
1144 	const struct btf_type *type, *datasec;
1145 	const struct btf_var_secinfo *vsi;
1146 	struct bpf_struct_ops *st_ops;
1147 	const char *tname, *var_name;
1148 	__s32 type_id, datasec_id;
1149 	const struct btf *btf;
1150 	struct bpf_map *map;
1151 	__u32 i;
1152 
1153 	if (shndx == -1)
1154 		return 0;
1155 
1156 	btf = obj->btf;
1157 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1158 					    BTF_KIND_DATASEC);
1159 	if (datasec_id < 0) {
1160 		pr_warn("struct_ops init: DATASEC %s not found\n",
1161 			sec_name);
1162 		return -EINVAL;
1163 	}
1164 
1165 	datasec = btf__type_by_id(btf, datasec_id);
1166 	vsi = btf_var_secinfos(datasec);
1167 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1168 		type = btf__type_by_id(obj->btf, vsi->type);
1169 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1170 
1171 		type_id = btf__resolve_type(obj->btf, vsi->type);
1172 		if (type_id < 0) {
1173 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1174 				vsi->type, sec_name);
1175 			return -EINVAL;
1176 		}
1177 
1178 		type = btf__type_by_id(obj->btf, type_id);
1179 		tname = btf__name_by_offset(obj->btf, type->name_off);
1180 		if (!tname[0]) {
1181 			pr_warn("struct_ops init: anonymous type is not supported\n");
1182 			return -ENOTSUP;
1183 		}
1184 		if (!btf_is_struct(type)) {
1185 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1186 			return -EINVAL;
1187 		}
1188 
1189 		map = bpf_object__add_map(obj);
1190 		if (IS_ERR(map))
1191 			return PTR_ERR(map);
1192 
1193 		map->sec_idx = shndx;
1194 		map->sec_offset = vsi->offset;
1195 		map->name = strdup(var_name);
1196 		if (!map->name)
1197 			return -ENOMEM;
1198 
1199 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1200 		map->def.key_size = sizeof(int);
1201 		map->def.value_size = type->size;
1202 		map->def.max_entries = 1;
1203 		map->def.map_flags = map_flags;
1204 
1205 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1206 		if (!map->st_ops)
1207 			return -ENOMEM;
1208 		st_ops = map->st_ops;
1209 		st_ops->data = malloc(type->size);
1210 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1211 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1212 					       sizeof(*st_ops->kern_func_off));
1213 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1214 			return -ENOMEM;
1215 
1216 		if (vsi->offset + type->size > data->d_size) {
1217 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1218 				var_name, sec_name);
1219 			return -EINVAL;
1220 		}
1221 
1222 		memcpy(st_ops->data,
1223 		       data->d_buf + vsi->offset,
1224 		       type->size);
1225 		st_ops->tname = tname;
1226 		st_ops->type = type;
1227 		st_ops->type_id = type_id;
1228 
1229 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1230 			 tname, type_id, var_name, vsi->offset);
1231 	}
1232 
1233 	return 0;
1234 }
1235 
bpf_object_init_struct_ops(struct bpf_object * obj)1236 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1237 {
1238 	int err;
1239 
1240 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1241 				   obj->efile.st_ops_data, 0);
1242 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1243 					  obj->efile.st_ops_link_shndx,
1244 					  obj->efile.st_ops_link_data,
1245 					  BPF_F_LINK);
1246 	return err;
1247 }
1248 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1249 static struct bpf_object *bpf_object__new(const char *path,
1250 					  const void *obj_buf,
1251 					  size_t obj_buf_sz,
1252 					  const char *obj_name)
1253 {
1254 	struct bpf_object *obj;
1255 	char *end;
1256 
1257 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1258 	if (!obj) {
1259 		pr_warn("alloc memory failed for %s\n", path);
1260 		return ERR_PTR(-ENOMEM);
1261 	}
1262 
1263 	strcpy(obj->path, path);
1264 	if (obj_name) {
1265 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1266 	} else {
1267 		/* Using basename() GNU version which doesn't modify arg. */
1268 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1269 		end = strchr(obj->name, '.');
1270 		if (end)
1271 			*end = 0;
1272 	}
1273 
1274 	obj->efile.fd = -1;
1275 	/*
1276 	 * Caller of this function should also call
1277 	 * bpf_object__elf_finish() after data collection to return
1278 	 * obj_buf to user. If not, we should duplicate the buffer to
1279 	 * avoid user freeing them before elf finish.
1280 	 */
1281 	obj->efile.obj_buf = obj_buf;
1282 	obj->efile.obj_buf_sz = obj_buf_sz;
1283 	obj->efile.btf_maps_shndx = -1;
1284 	obj->efile.st_ops_shndx = -1;
1285 	obj->efile.st_ops_link_shndx = -1;
1286 	obj->kconfig_map_idx = -1;
1287 
1288 	obj->kern_version = get_kernel_version();
1289 	obj->loaded = false;
1290 
1291 	return obj;
1292 }
1293 
bpf_object__elf_finish(struct bpf_object * obj)1294 static void bpf_object__elf_finish(struct bpf_object *obj)
1295 {
1296 	if (!obj->efile.elf)
1297 		return;
1298 
1299 	elf_end(obj->efile.elf);
1300 	obj->efile.elf = NULL;
1301 	obj->efile.symbols = NULL;
1302 	obj->efile.st_ops_data = NULL;
1303 	obj->efile.st_ops_link_data = NULL;
1304 
1305 	zfree(&obj->efile.secs);
1306 	obj->efile.sec_cnt = 0;
1307 	zclose(obj->efile.fd);
1308 	obj->efile.obj_buf = NULL;
1309 	obj->efile.obj_buf_sz = 0;
1310 }
1311 
bpf_object__elf_init(struct bpf_object * obj)1312 static int bpf_object__elf_init(struct bpf_object *obj)
1313 {
1314 	Elf64_Ehdr *ehdr;
1315 	int err = 0;
1316 	Elf *elf;
1317 
1318 	if (obj->efile.elf) {
1319 		pr_warn("elf: init internal error\n");
1320 		return -LIBBPF_ERRNO__LIBELF;
1321 	}
1322 
1323 	if (obj->efile.obj_buf_sz > 0) {
1324 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1325 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1326 	} else {
1327 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1328 		if (obj->efile.fd < 0) {
1329 			char errmsg[STRERR_BUFSIZE], *cp;
1330 
1331 			err = -errno;
1332 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1333 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1334 			return err;
1335 		}
1336 
1337 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1338 	}
1339 
1340 	if (!elf) {
1341 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1342 		err = -LIBBPF_ERRNO__LIBELF;
1343 		goto errout;
1344 	}
1345 
1346 	obj->efile.elf = elf;
1347 
1348 	if (elf_kind(elf) != ELF_K_ELF) {
1349 		err = -LIBBPF_ERRNO__FORMAT;
1350 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1351 		goto errout;
1352 	}
1353 
1354 	if (gelf_getclass(elf) != ELFCLASS64) {
1355 		err = -LIBBPF_ERRNO__FORMAT;
1356 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1357 		goto errout;
1358 	}
1359 
1360 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1361 	if (!obj->efile.ehdr) {
1362 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1363 		err = -LIBBPF_ERRNO__FORMAT;
1364 		goto errout;
1365 	}
1366 
1367 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1368 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1369 			obj->path, elf_errmsg(-1));
1370 		err = -LIBBPF_ERRNO__FORMAT;
1371 		goto errout;
1372 	}
1373 
1374 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1375 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1376 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1377 			obj->path, elf_errmsg(-1));
1378 		err = -LIBBPF_ERRNO__FORMAT;
1379 		goto errout;
1380 	}
1381 
1382 	/* Old LLVM set e_machine to EM_NONE */
1383 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1384 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1385 		err = -LIBBPF_ERRNO__FORMAT;
1386 		goto errout;
1387 	}
1388 
1389 	return 0;
1390 errout:
1391 	bpf_object__elf_finish(obj);
1392 	return err;
1393 }
1394 
bpf_object__check_endianness(struct bpf_object * obj)1395 static int bpf_object__check_endianness(struct bpf_object *obj)
1396 {
1397 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1398 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1399 		return 0;
1400 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1401 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1402 		return 0;
1403 #else
1404 # error "Unrecognized __BYTE_ORDER__"
1405 #endif
1406 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1407 	return -LIBBPF_ERRNO__ENDIAN;
1408 }
1409 
1410 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1411 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1412 {
1413 	if (!data) {
1414 		pr_warn("invalid license section in %s\n", obj->path);
1415 		return -LIBBPF_ERRNO__FORMAT;
1416 	}
1417 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1418 	 * go over allowed ELF data section buffer
1419 	 */
1420 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1421 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1422 	return 0;
1423 }
1424 
1425 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1426 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1427 {
1428 	__u32 kver;
1429 
1430 	if (!data || size != sizeof(kver)) {
1431 		pr_warn("invalid kver section in %s\n", obj->path);
1432 		return -LIBBPF_ERRNO__FORMAT;
1433 	}
1434 	memcpy(&kver, data, sizeof(kver));
1435 	obj->kern_version = kver;
1436 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1437 	return 0;
1438 }
1439 
bpf_map_type__is_map_in_map(enum bpf_map_type type)1440 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1441 {
1442 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1443 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1444 		return true;
1445 	return false;
1446 }
1447 
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1448 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1449 {
1450 	Elf_Data *data;
1451 	Elf_Scn *scn;
1452 
1453 	if (!name)
1454 		return -EINVAL;
1455 
1456 	scn = elf_sec_by_name(obj, name);
1457 	data = elf_sec_data(obj, scn);
1458 	if (data) {
1459 		*size = data->d_size;
1460 		return 0; /* found it */
1461 	}
1462 
1463 	return -ENOENT;
1464 }
1465 
find_elf_var_sym(const struct bpf_object * obj,const char * name)1466 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1467 {
1468 	Elf_Data *symbols = obj->efile.symbols;
1469 	const char *sname;
1470 	size_t si;
1471 
1472 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1473 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1474 
1475 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1476 			continue;
1477 
1478 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1479 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1480 			continue;
1481 
1482 		sname = elf_sym_str(obj, sym->st_name);
1483 		if (!sname) {
1484 			pr_warn("failed to get sym name string for var %s\n", name);
1485 			return ERR_PTR(-EIO);
1486 		}
1487 		if (strcmp(name, sname) == 0)
1488 			return sym;
1489 	}
1490 
1491 	return ERR_PTR(-ENOENT);
1492 }
1493 
bpf_object__add_map(struct bpf_object * obj)1494 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1495 {
1496 	struct bpf_map *map;
1497 	int err;
1498 
1499 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1500 				sizeof(*obj->maps), obj->nr_maps + 1);
1501 	if (err)
1502 		return ERR_PTR(err);
1503 
1504 	map = &obj->maps[obj->nr_maps++];
1505 	map->obj = obj;
1506 	map->fd = -1;
1507 	map->inner_map_fd = -1;
1508 	map->autocreate = true;
1509 
1510 	return map;
1511 }
1512 
bpf_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1513 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1514 {
1515 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1516 	size_t map_sz;
1517 
1518 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1519 	map_sz = roundup(map_sz, page_sz);
1520 	return map_sz;
1521 }
1522 
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1523 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1524 {
1525 	void *mmaped;
1526 
1527 	if (!map->mmaped)
1528 		return -EINVAL;
1529 
1530 	if (old_sz == new_sz)
1531 		return 0;
1532 
1533 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1534 	if (mmaped == MAP_FAILED)
1535 		return -errno;
1536 
1537 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1538 	munmap(map->mmaped, old_sz);
1539 	map->mmaped = mmaped;
1540 	return 0;
1541 }
1542 
internal_map_name(struct bpf_object * obj,const char * real_name)1543 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1544 {
1545 	char map_name[BPF_OBJ_NAME_LEN], *p;
1546 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1547 
1548 	/* This is one of the more confusing parts of libbpf for various
1549 	 * reasons, some of which are historical. The original idea for naming
1550 	 * internal names was to include as much of BPF object name prefix as
1551 	 * possible, so that it can be distinguished from similar internal
1552 	 * maps of a different BPF object.
1553 	 * As an example, let's say we have bpf_object named 'my_object_name'
1554 	 * and internal map corresponding to '.rodata' ELF section. The final
1555 	 * map name advertised to user and to the kernel will be
1556 	 * 'my_objec.rodata', taking first 8 characters of object name and
1557 	 * entire 7 characters of '.rodata'.
1558 	 * Somewhat confusingly, if internal map ELF section name is shorter
1559 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1560 	 * for the suffix, even though we only have 4 actual characters, and
1561 	 * resulting map will be called 'my_objec.bss', not even using all 15
1562 	 * characters allowed by the kernel. Oh well, at least the truncated
1563 	 * object name is somewhat consistent in this case. But if the map
1564 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1565 	 * (8 chars) and thus will be left with only first 7 characters of the
1566 	 * object name ('my_obje'). Happy guessing, user, that the final map
1567 	 * name will be "my_obje.kconfig".
1568 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1569 	 * and .data.* data sections, it's possible that ELF section name is
1570 	 * longer than allowed 15 chars, so we now need to be careful to take
1571 	 * only up to 15 first characters of ELF name, taking no BPF object
1572 	 * name characters at all. So '.rodata.abracadabra' will result in
1573 	 * '.rodata.abracad' kernel and user-visible name.
1574 	 * We need to keep this convoluted logic intact for .data, .bss and
1575 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1576 	 * maps we use their ELF names as is, not prepending bpf_object name
1577 	 * in front. We still need to truncate them to 15 characters for the
1578 	 * kernel. Full name can be recovered for such maps by using DATASEC
1579 	 * BTF type associated with such map's value type, though.
1580 	 */
1581 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1582 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1583 
1584 	/* if there are two or more dots in map name, it's a custom dot map */
1585 	if (strchr(real_name + 1, '.') != NULL)
1586 		pfx_len = 0;
1587 	else
1588 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1589 
1590 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1591 		 sfx_len, real_name);
1592 
1593 	/* sanitise map name to characters allowed by kernel */
1594 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1595 		if (!isalnum(*p) && *p != '_' && *p != '.')
1596 			*p = '_';
1597 
1598 	return strdup(map_name);
1599 }
1600 
1601 static int
1602 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1603 
1604 /* Internal BPF map is mmap()'able only if at least one of corresponding
1605  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1606  * variable and it's not marked as __hidden (which turns it into, effectively,
1607  * a STATIC variable).
1608  */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1609 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1610 {
1611 	const struct btf_type *t, *vt;
1612 	struct btf_var_secinfo *vsi;
1613 	int i, n;
1614 
1615 	if (!map->btf_value_type_id)
1616 		return false;
1617 
1618 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1619 	if (!btf_is_datasec(t))
1620 		return false;
1621 
1622 	vsi = btf_var_secinfos(t);
1623 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1624 		vt = btf__type_by_id(obj->btf, vsi->type);
1625 		if (!btf_is_var(vt))
1626 			continue;
1627 
1628 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1629 			return true;
1630 	}
1631 
1632 	return false;
1633 }
1634 
1635 static int
bpf_object__init_internal_map(struct bpf_object * obj,enum libbpf_map_type type,const char * real_name,int sec_idx,void * data,size_t data_sz)1636 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1637 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1638 {
1639 	struct bpf_map_def *def;
1640 	struct bpf_map *map;
1641 	size_t mmap_sz;
1642 	int err;
1643 
1644 	map = bpf_object__add_map(obj);
1645 	if (IS_ERR(map))
1646 		return PTR_ERR(map);
1647 
1648 	map->libbpf_type = type;
1649 	map->sec_idx = sec_idx;
1650 	map->sec_offset = 0;
1651 	map->real_name = strdup(real_name);
1652 	map->name = internal_map_name(obj, real_name);
1653 	if (!map->real_name || !map->name) {
1654 		zfree(&map->real_name);
1655 		zfree(&map->name);
1656 		return -ENOMEM;
1657 	}
1658 
1659 	def = &map->def;
1660 	def->type = BPF_MAP_TYPE_ARRAY;
1661 	def->key_size = sizeof(int);
1662 	def->value_size = data_sz;
1663 	def->max_entries = 1;
1664 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1665 			 ? BPF_F_RDONLY_PROG : 0;
1666 
1667 	/* failures are fine because of maps like .rodata.str1.1 */
1668 	(void) map_fill_btf_type_info(obj, map);
1669 
1670 	if (map_is_mmapable(obj, map))
1671 		def->map_flags |= BPF_F_MMAPABLE;
1672 
1673 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1674 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1675 
1676 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1677 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1678 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1679 	if (map->mmaped == MAP_FAILED) {
1680 		err = -errno;
1681 		map->mmaped = NULL;
1682 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1683 			map->name, err);
1684 		zfree(&map->real_name);
1685 		zfree(&map->name);
1686 		return err;
1687 	}
1688 
1689 	if (data)
1690 		memcpy(map->mmaped, data, data_sz);
1691 
1692 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1693 	return 0;
1694 }
1695 
bpf_object__init_global_data_maps(struct bpf_object * obj)1696 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1697 {
1698 	struct elf_sec_desc *sec_desc;
1699 	const char *sec_name;
1700 	int err = 0, sec_idx;
1701 
1702 	/*
1703 	 * Populate obj->maps with libbpf internal maps.
1704 	 */
1705 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1706 		sec_desc = &obj->efile.secs[sec_idx];
1707 
1708 		/* Skip recognized sections with size 0. */
1709 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1710 			continue;
1711 
1712 		switch (sec_desc->sec_type) {
1713 		case SEC_DATA:
1714 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1715 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1716 							    sec_name, sec_idx,
1717 							    sec_desc->data->d_buf,
1718 							    sec_desc->data->d_size);
1719 			break;
1720 		case SEC_RODATA:
1721 			obj->has_rodata = true;
1722 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1723 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1724 							    sec_name, sec_idx,
1725 							    sec_desc->data->d_buf,
1726 							    sec_desc->data->d_size);
1727 			break;
1728 		case SEC_BSS:
1729 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1730 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1731 							    sec_name, sec_idx,
1732 							    NULL,
1733 							    sec_desc->data->d_size);
1734 			break;
1735 		default:
1736 			/* skip */
1737 			break;
1738 		}
1739 		if (err)
1740 			return err;
1741 	}
1742 	return 0;
1743 }
1744 
1745 
find_extern_by_name(const struct bpf_object * obj,const void * name)1746 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1747 					       const void *name)
1748 {
1749 	int i;
1750 
1751 	for (i = 0; i < obj->nr_extern; i++) {
1752 		if (strcmp(obj->externs[i].name, name) == 0)
1753 			return &obj->externs[i];
1754 	}
1755 	return NULL;
1756 }
1757 
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)1758 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1759 			      char value)
1760 {
1761 	switch (ext->kcfg.type) {
1762 	case KCFG_BOOL:
1763 		if (value == 'm') {
1764 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1765 				ext->name, value);
1766 			return -EINVAL;
1767 		}
1768 		*(bool *)ext_val = value == 'y' ? true : false;
1769 		break;
1770 	case KCFG_TRISTATE:
1771 		if (value == 'y')
1772 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1773 		else if (value == 'm')
1774 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1775 		else /* value == 'n' */
1776 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1777 		break;
1778 	case KCFG_CHAR:
1779 		*(char *)ext_val = value;
1780 		break;
1781 	case KCFG_UNKNOWN:
1782 	case KCFG_INT:
1783 	case KCFG_CHAR_ARR:
1784 	default:
1785 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1786 			ext->name, value);
1787 		return -EINVAL;
1788 	}
1789 	ext->is_set = true;
1790 	return 0;
1791 }
1792 
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)1793 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1794 			      const char *value)
1795 {
1796 	size_t len;
1797 
1798 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1799 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1800 			ext->name, value);
1801 		return -EINVAL;
1802 	}
1803 
1804 	len = strlen(value);
1805 	if (len < 2 || value[len - 1] != '"') {
1806 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1807 			ext->name, value);
1808 		return -EINVAL;
1809 	}
1810 
1811 	/* strip quotes */
1812 	len -= 2;
1813 	if (len >= ext->kcfg.sz) {
1814 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1815 			ext->name, value, len, ext->kcfg.sz - 1);
1816 		len = ext->kcfg.sz - 1;
1817 	}
1818 	memcpy(ext_val, value + 1, len);
1819 	ext_val[len] = '\0';
1820 	ext->is_set = true;
1821 	return 0;
1822 }
1823 
parse_u64(const char * value,__u64 * res)1824 static int parse_u64(const char *value, __u64 *res)
1825 {
1826 	char *value_end;
1827 	int err;
1828 
1829 	errno = 0;
1830 	*res = strtoull(value, &value_end, 0);
1831 	if (errno) {
1832 		err = -errno;
1833 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1834 		return err;
1835 	}
1836 	if (*value_end) {
1837 		pr_warn("failed to parse '%s' as integer completely\n", value);
1838 		return -EINVAL;
1839 	}
1840 	return 0;
1841 }
1842 
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)1843 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1844 {
1845 	int bit_sz = ext->kcfg.sz * 8;
1846 
1847 	if (ext->kcfg.sz == 8)
1848 		return true;
1849 
1850 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1851 	 * bytes size without any loss of information. If the target integer
1852 	 * is signed, we rely on the following limits of integer type of
1853 	 * Y bits and subsequent transformation:
1854 	 *
1855 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1856 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1857 	 *            0 <= X + 2^(Y-1) <  2^Y
1858 	 *
1859 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1860 	 *  zero.
1861 	 */
1862 	if (ext->kcfg.is_signed)
1863 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1864 	else
1865 		return (v >> bit_sz) == 0;
1866 }
1867 
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)1868 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1869 			      __u64 value)
1870 {
1871 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1872 	    ext->kcfg.type != KCFG_BOOL) {
1873 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1874 			ext->name, (unsigned long long)value);
1875 		return -EINVAL;
1876 	}
1877 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1878 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1879 			ext->name, (unsigned long long)value);
1880 		return -EINVAL;
1881 
1882 	}
1883 	if (!is_kcfg_value_in_range(ext, value)) {
1884 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1885 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1886 		return -ERANGE;
1887 	}
1888 	switch (ext->kcfg.sz) {
1889 	case 1:
1890 		*(__u8 *)ext_val = value;
1891 		break;
1892 	case 2:
1893 		*(__u16 *)ext_val = value;
1894 		break;
1895 	case 4:
1896 		*(__u32 *)ext_val = value;
1897 		break;
1898 	case 8:
1899 		*(__u64 *)ext_val = value;
1900 		break;
1901 	default:
1902 		return -EINVAL;
1903 	}
1904 	ext->is_set = true;
1905 	return 0;
1906 }
1907 
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)1908 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1909 					    char *buf, void *data)
1910 {
1911 	struct extern_desc *ext;
1912 	char *sep, *value;
1913 	int len, err = 0;
1914 	void *ext_val;
1915 	__u64 num;
1916 
1917 	if (!str_has_pfx(buf, "CONFIG_"))
1918 		return 0;
1919 
1920 	sep = strchr(buf, '=');
1921 	if (!sep) {
1922 		pr_warn("failed to parse '%s': no separator\n", buf);
1923 		return -EINVAL;
1924 	}
1925 
1926 	/* Trim ending '\n' */
1927 	len = strlen(buf);
1928 	if (buf[len - 1] == '\n')
1929 		buf[len - 1] = '\0';
1930 	/* Split on '=' and ensure that a value is present. */
1931 	*sep = '\0';
1932 	if (!sep[1]) {
1933 		*sep = '=';
1934 		pr_warn("failed to parse '%s': no value\n", buf);
1935 		return -EINVAL;
1936 	}
1937 
1938 	ext = find_extern_by_name(obj, buf);
1939 	if (!ext || ext->is_set)
1940 		return 0;
1941 
1942 	ext_val = data + ext->kcfg.data_off;
1943 	value = sep + 1;
1944 
1945 	switch (*value) {
1946 	case 'y': case 'n': case 'm':
1947 		err = set_kcfg_value_tri(ext, ext_val, *value);
1948 		break;
1949 	case '"':
1950 		err = set_kcfg_value_str(ext, ext_val, value);
1951 		break;
1952 	default:
1953 		/* assume integer */
1954 		err = parse_u64(value, &num);
1955 		if (err) {
1956 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1957 			return err;
1958 		}
1959 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1960 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1961 			return -EINVAL;
1962 		}
1963 		err = set_kcfg_value_num(ext, ext_val, num);
1964 		break;
1965 	}
1966 	if (err)
1967 		return err;
1968 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1969 	return 0;
1970 }
1971 
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)1972 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1973 {
1974 	char buf[PATH_MAX];
1975 	struct utsname uts;
1976 	int len, err = 0;
1977 	gzFile file;
1978 
1979 	uname(&uts);
1980 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1981 	if (len < 0)
1982 		return -EINVAL;
1983 	else if (len >= PATH_MAX)
1984 		return -ENAMETOOLONG;
1985 
1986 	/* gzopen also accepts uncompressed files. */
1987 	file = gzopen(buf, "re");
1988 	if (!file)
1989 		file = gzopen("/proc/config.gz", "re");
1990 
1991 	if (!file) {
1992 		pr_warn("failed to open system Kconfig\n");
1993 		return -ENOENT;
1994 	}
1995 
1996 	while (gzgets(file, buf, sizeof(buf))) {
1997 		err = bpf_object__process_kconfig_line(obj, buf, data);
1998 		if (err) {
1999 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2000 				buf, err);
2001 			goto out;
2002 		}
2003 	}
2004 
2005 out:
2006 	gzclose(file);
2007 	return err;
2008 }
2009 
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2010 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2011 					const char *config, void *data)
2012 {
2013 	char buf[PATH_MAX];
2014 	int err = 0;
2015 	FILE *file;
2016 
2017 	file = fmemopen((void *)config, strlen(config), "r");
2018 	if (!file) {
2019 		err = -errno;
2020 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2021 		return err;
2022 	}
2023 
2024 	while (fgets(buf, sizeof(buf), file)) {
2025 		err = bpf_object__process_kconfig_line(obj, buf, data);
2026 		if (err) {
2027 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2028 				buf, err);
2029 			break;
2030 		}
2031 	}
2032 
2033 	fclose(file);
2034 	return err;
2035 }
2036 
bpf_object__init_kconfig_map(struct bpf_object * obj)2037 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2038 {
2039 	struct extern_desc *last_ext = NULL, *ext;
2040 	size_t map_sz;
2041 	int i, err;
2042 
2043 	for (i = 0; i < obj->nr_extern; i++) {
2044 		ext = &obj->externs[i];
2045 		if (ext->type == EXT_KCFG)
2046 			last_ext = ext;
2047 	}
2048 
2049 	if (!last_ext)
2050 		return 0;
2051 
2052 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2053 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2054 					    ".kconfig", obj->efile.symbols_shndx,
2055 					    NULL, map_sz);
2056 	if (err)
2057 		return err;
2058 
2059 	obj->kconfig_map_idx = obj->nr_maps - 1;
2060 
2061 	return 0;
2062 }
2063 
2064 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2065 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2066 {
2067 	const struct btf_type *t = btf__type_by_id(btf, id);
2068 
2069 	if (res_id)
2070 		*res_id = id;
2071 
2072 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2073 		if (res_id)
2074 			*res_id = t->type;
2075 		t = btf__type_by_id(btf, t->type);
2076 	}
2077 
2078 	return t;
2079 }
2080 
2081 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2082 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2083 {
2084 	const struct btf_type *t;
2085 
2086 	t = skip_mods_and_typedefs(btf, id, NULL);
2087 	if (!btf_is_ptr(t))
2088 		return NULL;
2089 
2090 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2091 
2092 	return btf_is_func_proto(t) ? t : NULL;
2093 }
2094 
__btf_kind_str(__u16 kind)2095 static const char *__btf_kind_str(__u16 kind)
2096 {
2097 	switch (kind) {
2098 	case BTF_KIND_UNKN: return "void";
2099 	case BTF_KIND_INT: return "int";
2100 	case BTF_KIND_PTR: return "ptr";
2101 	case BTF_KIND_ARRAY: return "array";
2102 	case BTF_KIND_STRUCT: return "struct";
2103 	case BTF_KIND_UNION: return "union";
2104 	case BTF_KIND_ENUM: return "enum";
2105 	case BTF_KIND_FWD: return "fwd";
2106 	case BTF_KIND_TYPEDEF: return "typedef";
2107 	case BTF_KIND_VOLATILE: return "volatile";
2108 	case BTF_KIND_CONST: return "const";
2109 	case BTF_KIND_RESTRICT: return "restrict";
2110 	case BTF_KIND_FUNC: return "func";
2111 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2112 	case BTF_KIND_VAR: return "var";
2113 	case BTF_KIND_DATASEC: return "datasec";
2114 	case BTF_KIND_FLOAT: return "float";
2115 	case BTF_KIND_DECL_TAG: return "decl_tag";
2116 	case BTF_KIND_TYPE_TAG: return "type_tag";
2117 	case BTF_KIND_ENUM64: return "enum64";
2118 	default: return "unknown";
2119 	}
2120 }
2121 
btf_kind_str(const struct btf_type * t)2122 const char *btf_kind_str(const struct btf_type *t)
2123 {
2124 	return __btf_kind_str(btf_kind(t));
2125 }
2126 
2127 /*
2128  * Fetch integer attribute of BTF map definition. Such attributes are
2129  * represented using a pointer to an array, in which dimensionality of array
2130  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2131  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2132  * type definition, while using only sizeof(void *) space in ELF data section.
2133  */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2134 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2135 			      const struct btf_member *m, __u32 *res)
2136 {
2137 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2138 	const char *name = btf__name_by_offset(btf, m->name_off);
2139 	const struct btf_array *arr_info;
2140 	const struct btf_type *arr_t;
2141 
2142 	if (!btf_is_ptr(t)) {
2143 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2144 			map_name, name, btf_kind_str(t));
2145 		return false;
2146 	}
2147 
2148 	arr_t = btf__type_by_id(btf, t->type);
2149 	if (!arr_t) {
2150 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2151 			map_name, name, t->type);
2152 		return false;
2153 	}
2154 	if (!btf_is_array(arr_t)) {
2155 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2156 			map_name, name, btf_kind_str(arr_t));
2157 		return false;
2158 	}
2159 	arr_info = btf_array(arr_t);
2160 	*res = arr_info->nelems;
2161 	return true;
2162 }
2163 
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2164 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2165 {
2166 	int len;
2167 
2168 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2169 	if (len < 0)
2170 		return -EINVAL;
2171 	if (len >= buf_sz)
2172 		return -ENAMETOOLONG;
2173 
2174 	return 0;
2175 }
2176 
build_map_pin_path(struct bpf_map * map,const char * path)2177 static int build_map_pin_path(struct bpf_map *map, const char *path)
2178 {
2179 	char buf[PATH_MAX];
2180 	int err;
2181 
2182 	if (!path)
2183 		path = "/sys/fs/bpf";
2184 
2185 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2186 	if (err)
2187 		return err;
2188 
2189 	return bpf_map__set_pin_path(map, buf);
2190 }
2191 
2192 /* should match definition in bpf_helpers.h */
2193 enum libbpf_pin_type {
2194 	LIBBPF_PIN_NONE,
2195 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2196 	LIBBPF_PIN_BY_NAME,
2197 };
2198 
parse_btf_map_def(const char * map_name,struct btf * btf,const struct btf_type * def_t,bool strict,struct btf_map_def * map_def,struct btf_map_def * inner_def)2199 int parse_btf_map_def(const char *map_name, struct btf *btf,
2200 		      const struct btf_type *def_t, bool strict,
2201 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2202 {
2203 	const struct btf_type *t;
2204 	const struct btf_member *m;
2205 	bool is_inner = inner_def == NULL;
2206 	int vlen, i;
2207 
2208 	vlen = btf_vlen(def_t);
2209 	m = btf_members(def_t);
2210 	for (i = 0; i < vlen; i++, m++) {
2211 		const char *name = btf__name_by_offset(btf, m->name_off);
2212 
2213 		if (!name) {
2214 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2215 			return -EINVAL;
2216 		}
2217 		if (strcmp(name, "type") == 0) {
2218 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2219 				return -EINVAL;
2220 			map_def->parts |= MAP_DEF_MAP_TYPE;
2221 		} else if (strcmp(name, "max_entries") == 0) {
2222 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2223 				return -EINVAL;
2224 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2225 		} else if (strcmp(name, "map_flags") == 0) {
2226 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2227 				return -EINVAL;
2228 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2229 		} else if (strcmp(name, "numa_node") == 0) {
2230 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2231 				return -EINVAL;
2232 			map_def->parts |= MAP_DEF_NUMA_NODE;
2233 		} else if (strcmp(name, "key_size") == 0) {
2234 			__u32 sz;
2235 
2236 			if (!get_map_field_int(map_name, btf, m, &sz))
2237 				return -EINVAL;
2238 			if (map_def->key_size && map_def->key_size != sz) {
2239 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2240 					map_name, map_def->key_size, sz);
2241 				return -EINVAL;
2242 			}
2243 			map_def->key_size = sz;
2244 			map_def->parts |= MAP_DEF_KEY_SIZE;
2245 		} else if (strcmp(name, "key") == 0) {
2246 			__s64 sz;
2247 
2248 			t = btf__type_by_id(btf, m->type);
2249 			if (!t) {
2250 				pr_warn("map '%s': key type [%d] not found.\n",
2251 					map_name, m->type);
2252 				return -EINVAL;
2253 			}
2254 			if (!btf_is_ptr(t)) {
2255 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2256 					map_name, btf_kind_str(t));
2257 				return -EINVAL;
2258 			}
2259 			sz = btf__resolve_size(btf, t->type);
2260 			if (sz < 0) {
2261 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2262 					map_name, t->type, (ssize_t)sz);
2263 				return sz;
2264 			}
2265 			if (map_def->key_size && map_def->key_size != sz) {
2266 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2267 					map_name, map_def->key_size, (ssize_t)sz);
2268 				return -EINVAL;
2269 			}
2270 			map_def->key_size = sz;
2271 			map_def->key_type_id = t->type;
2272 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2273 		} else if (strcmp(name, "value_size") == 0) {
2274 			__u32 sz;
2275 
2276 			if (!get_map_field_int(map_name, btf, m, &sz))
2277 				return -EINVAL;
2278 			if (map_def->value_size && map_def->value_size != sz) {
2279 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2280 					map_name, map_def->value_size, sz);
2281 				return -EINVAL;
2282 			}
2283 			map_def->value_size = sz;
2284 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2285 		} else if (strcmp(name, "value") == 0) {
2286 			__s64 sz;
2287 
2288 			t = btf__type_by_id(btf, m->type);
2289 			if (!t) {
2290 				pr_warn("map '%s': value type [%d] not found.\n",
2291 					map_name, m->type);
2292 				return -EINVAL;
2293 			}
2294 			if (!btf_is_ptr(t)) {
2295 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2296 					map_name, btf_kind_str(t));
2297 				return -EINVAL;
2298 			}
2299 			sz = btf__resolve_size(btf, t->type);
2300 			if (sz < 0) {
2301 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2302 					map_name, t->type, (ssize_t)sz);
2303 				return sz;
2304 			}
2305 			if (map_def->value_size && map_def->value_size != sz) {
2306 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2307 					map_name, map_def->value_size, (ssize_t)sz);
2308 				return -EINVAL;
2309 			}
2310 			map_def->value_size = sz;
2311 			map_def->value_type_id = t->type;
2312 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2313 		}
2314 		else if (strcmp(name, "values") == 0) {
2315 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2316 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2317 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2318 			char inner_map_name[128];
2319 			int err;
2320 
2321 			if (is_inner) {
2322 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2323 					map_name);
2324 				return -ENOTSUP;
2325 			}
2326 			if (i != vlen - 1) {
2327 				pr_warn("map '%s': '%s' member should be last.\n",
2328 					map_name, name);
2329 				return -EINVAL;
2330 			}
2331 			if (!is_map_in_map && !is_prog_array) {
2332 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2333 					map_name);
2334 				return -ENOTSUP;
2335 			}
2336 			if (map_def->value_size && map_def->value_size != 4) {
2337 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2338 					map_name, map_def->value_size);
2339 				return -EINVAL;
2340 			}
2341 			map_def->value_size = 4;
2342 			t = btf__type_by_id(btf, m->type);
2343 			if (!t) {
2344 				pr_warn("map '%s': %s type [%d] not found.\n",
2345 					map_name, desc, m->type);
2346 				return -EINVAL;
2347 			}
2348 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2349 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2350 					map_name, desc);
2351 				return -EINVAL;
2352 			}
2353 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2354 			if (!btf_is_ptr(t)) {
2355 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2356 					map_name, desc, btf_kind_str(t));
2357 				return -EINVAL;
2358 			}
2359 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2360 			if (is_prog_array) {
2361 				if (!btf_is_func_proto(t)) {
2362 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2363 						map_name, btf_kind_str(t));
2364 					return -EINVAL;
2365 				}
2366 				continue;
2367 			}
2368 			if (!btf_is_struct(t)) {
2369 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2370 					map_name, btf_kind_str(t));
2371 				return -EINVAL;
2372 			}
2373 
2374 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2375 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2376 			if (err)
2377 				return err;
2378 
2379 			map_def->parts |= MAP_DEF_INNER_MAP;
2380 		} else if (strcmp(name, "pinning") == 0) {
2381 			__u32 val;
2382 
2383 			if (is_inner) {
2384 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2385 				return -EINVAL;
2386 			}
2387 			if (!get_map_field_int(map_name, btf, m, &val))
2388 				return -EINVAL;
2389 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2390 				pr_warn("map '%s': invalid pinning value %u.\n",
2391 					map_name, val);
2392 				return -EINVAL;
2393 			}
2394 			map_def->pinning = val;
2395 			map_def->parts |= MAP_DEF_PINNING;
2396 		} else if (strcmp(name, "map_extra") == 0) {
2397 			__u32 map_extra;
2398 
2399 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2400 				return -EINVAL;
2401 			map_def->map_extra = map_extra;
2402 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2403 		} else {
2404 			if (strict) {
2405 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2406 				return -ENOTSUP;
2407 			}
2408 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2409 		}
2410 	}
2411 
2412 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2413 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2414 		return -EINVAL;
2415 	}
2416 
2417 	return 0;
2418 }
2419 
adjust_ringbuf_sz(size_t sz)2420 static size_t adjust_ringbuf_sz(size_t sz)
2421 {
2422 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2423 	__u32 mul;
2424 
2425 	/* if user forgot to set any size, make sure they see error */
2426 	if (sz == 0)
2427 		return 0;
2428 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2429 	 * a power-of-2 multiple of kernel's page size. If user diligently
2430 	 * satisified these conditions, pass the size through.
2431 	 */
2432 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2433 		return sz;
2434 
2435 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2436 	 * user-set size to satisfy both user size request and kernel
2437 	 * requirements and substitute correct max_entries for map creation.
2438 	 */
2439 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2440 		if (mul * page_sz > sz)
2441 			return mul * page_sz;
2442 	}
2443 
2444 	/* if it's impossible to satisfy the conditions (i.e., user size is
2445 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2446 	 * page_size) then just return original size and let kernel reject it
2447 	 */
2448 	return sz;
2449 }
2450 
map_is_ringbuf(const struct bpf_map * map)2451 static bool map_is_ringbuf(const struct bpf_map *map)
2452 {
2453 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2454 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2455 }
2456 
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2457 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2458 {
2459 	map->def.type = def->map_type;
2460 	map->def.key_size = def->key_size;
2461 	map->def.value_size = def->value_size;
2462 	map->def.max_entries = def->max_entries;
2463 	map->def.map_flags = def->map_flags;
2464 	map->map_extra = def->map_extra;
2465 
2466 	map->numa_node = def->numa_node;
2467 	map->btf_key_type_id = def->key_type_id;
2468 	map->btf_value_type_id = def->value_type_id;
2469 
2470 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2471 	if (map_is_ringbuf(map))
2472 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2473 
2474 	if (def->parts & MAP_DEF_MAP_TYPE)
2475 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2476 
2477 	if (def->parts & MAP_DEF_KEY_TYPE)
2478 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2479 			 map->name, def->key_type_id, def->key_size);
2480 	else if (def->parts & MAP_DEF_KEY_SIZE)
2481 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2482 
2483 	if (def->parts & MAP_DEF_VALUE_TYPE)
2484 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2485 			 map->name, def->value_type_id, def->value_size);
2486 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2487 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2488 
2489 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2490 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2491 	if (def->parts & MAP_DEF_MAP_FLAGS)
2492 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2493 	if (def->parts & MAP_DEF_MAP_EXTRA)
2494 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2495 			 (unsigned long long)def->map_extra);
2496 	if (def->parts & MAP_DEF_PINNING)
2497 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2498 	if (def->parts & MAP_DEF_NUMA_NODE)
2499 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2500 
2501 	if (def->parts & MAP_DEF_INNER_MAP)
2502 		pr_debug("map '%s': found inner map definition.\n", map->name);
2503 }
2504 
btf_var_linkage_str(__u32 linkage)2505 static const char *btf_var_linkage_str(__u32 linkage)
2506 {
2507 	switch (linkage) {
2508 	case BTF_VAR_STATIC: return "static";
2509 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2510 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2511 	default: return "unknown";
2512 	}
2513 }
2514 
bpf_object__init_user_btf_map(struct bpf_object * obj,const struct btf_type * sec,int var_idx,int sec_idx,const Elf_Data * data,bool strict,const char * pin_root_path)2515 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2516 					 const struct btf_type *sec,
2517 					 int var_idx, int sec_idx,
2518 					 const Elf_Data *data, bool strict,
2519 					 const char *pin_root_path)
2520 {
2521 	struct btf_map_def map_def = {}, inner_def = {};
2522 	const struct btf_type *var, *def;
2523 	const struct btf_var_secinfo *vi;
2524 	const struct btf_var *var_extra;
2525 	const char *map_name;
2526 	struct bpf_map *map;
2527 	int err;
2528 
2529 	vi = btf_var_secinfos(sec) + var_idx;
2530 	var = btf__type_by_id(obj->btf, vi->type);
2531 	var_extra = btf_var(var);
2532 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2533 
2534 	if (map_name == NULL || map_name[0] == '\0') {
2535 		pr_warn("map #%d: empty name.\n", var_idx);
2536 		return -EINVAL;
2537 	}
2538 	if ((__u64)vi->offset + vi->size > data->d_size) {
2539 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2540 		return -EINVAL;
2541 	}
2542 	if (!btf_is_var(var)) {
2543 		pr_warn("map '%s': unexpected var kind %s.\n",
2544 			map_name, btf_kind_str(var));
2545 		return -EINVAL;
2546 	}
2547 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2548 		pr_warn("map '%s': unsupported map linkage %s.\n",
2549 			map_name, btf_var_linkage_str(var_extra->linkage));
2550 		return -EOPNOTSUPP;
2551 	}
2552 
2553 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2554 	if (!btf_is_struct(def)) {
2555 		pr_warn("map '%s': unexpected def kind %s.\n",
2556 			map_name, btf_kind_str(var));
2557 		return -EINVAL;
2558 	}
2559 	if (def->size > vi->size) {
2560 		pr_warn("map '%s': invalid def size.\n", map_name);
2561 		return -EINVAL;
2562 	}
2563 
2564 	map = bpf_object__add_map(obj);
2565 	if (IS_ERR(map))
2566 		return PTR_ERR(map);
2567 	map->name = strdup(map_name);
2568 	if (!map->name) {
2569 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2570 		return -ENOMEM;
2571 	}
2572 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2573 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2574 	map->sec_idx = sec_idx;
2575 	map->sec_offset = vi->offset;
2576 	map->btf_var_idx = var_idx;
2577 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2578 		 map_name, map->sec_idx, map->sec_offset);
2579 
2580 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2581 	if (err)
2582 		return err;
2583 
2584 	fill_map_from_def(map, &map_def);
2585 
2586 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2587 		err = build_map_pin_path(map, pin_root_path);
2588 		if (err) {
2589 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2590 			return err;
2591 		}
2592 	}
2593 
2594 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2595 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2596 		if (!map->inner_map)
2597 			return -ENOMEM;
2598 		map->inner_map->fd = -1;
2599 		map->inner_map->sec_idx = sec_idx;
2600 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2601 		if (!map->inner_map->name)
2602 			return -ENOMEM;
2603 		sprintf(map->inner_map->name, "%s.inner", map_name);
2604 
2605 		fill_map_from_def(map->inner_map, &inner_def);
2606 	}
2607 
2608 	err = map_fill_btf_type_info(obj, map);
2609 	if (err)
2610 		return err;
2611 
2612 	return 0;
2613 }
2614 
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2615 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2616 					  const char *pin_root_path)
2617 {
2618 	const struct btf_type *sec = NULL;
2619 	int nr_types, i, vlen, err;
2620 	const struct btf_type *t;
2621 	const char *name;
2622 	Elf_Data *data;
2623 	Elf_Scn *scn;
2624 
2625 	if (obj->efile.btf_maps_shndx < 0)
2626 		return 0;
2627 
2628 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2629 	data = elf_sec_data(obj, scn);
2630 	if (!scn || !data) {
2631 		pr_warn("elf: failed to get %s map definitions for %s\n",
2632 			MAPS_ELF_SEC, obj->path);
2633 		return -EINVAL;
2634 	}
2635 
2636 	nr_types = btf__type_cnt(obj->btf);
2637 	for (i = 1; i < nr_types; i++) {
2638 		t = btf__type_by_id(obj->btf, i);
2639 		if (!btf_is_datasec(t))
2640 			continue;
2641 		name = btf__name_by_offset(obj->btf, t->name_off);
2642 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2643 			sec = t;
2644 			obj->efile.btf_maps_sec_btf_id = i;
2645 			break;
2646 		}
2647 	}
2648 
2649 	if (!sec) {
2650 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2651 		return -ENOENT;
2652 	}
2653 
2654 	vlen = btf_vlen(sec);
2655 	for (i = 0; i < vlen; i++) {
2656 		err = bpf_object__init_user_btf_map(obj, sec, i,
2657 						    obj->efile.btf_maps_shndx,
2658 						    data, strict,
2659 						    pin_root_path);
2660 		if (err)
2661 			return err;
2662 	}
2663 
2664 	return 0;
2665 }
2666 
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)2667 static int bpf_object__init_maps(struct bpf_object *obj,
2668 				 const struct bpf_object_open_opts *opts)
2669 {
2670 	const char *pin_root_path;
2671 	bool strict;
2672 	int err = 0;
2673 
2674 	strict = !OPTS_GET(opts, relaxed_maps, false);
2675 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2676 
2677 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2678 	err = err ?: bpf_object__init_global_data_maps(obj);
2679 	err = err ?: bpf_object__init_kconfig_map(obj);
2680 	err = err ?: bpf_object_init_struct_ops(obj);
2681 
2682 	return err;
2683 }
2684 
section_have_execinstr(struct bpf_object * obj,int idx)2685 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2686 {
2687 	Elf64_Shdr *sh;
2688 
2689 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2690 	if (!sh)
2691 		return false;
2692 
2693 	return sh->sh_flags & SHF_EXECINSTR;
2694 }
2695 
btf_needs_sanitization(struct bpf_object * obj)2696 static bool btf_needs_sanitization(struct bpf_object *obj)
2697 {
2698 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2699 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2700 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2701 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2702 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2703 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2704 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2705 
2706 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2707 	       !has_decl_tag || !has_type_tag || !has_enum64;
2708 }
2709 
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)2710 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2711 {
2712 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2713 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2714 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2715 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2716 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2717 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2718 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2719 	int enum64_placeholder_id = 0;
2720 	struct btf_type *t;
2721 	int i, j, vlen;
2722 
2723 	for (i = 1; i < btf__type_cnt(btf); i++) {
2724 		t = (struct btf_type *)btf__type_by_id(btf, i);
2725 
2726 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2727 			/* replace VAR/DECL_TAG with INT */
2728 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2729 			/*
2730 			 * using size = 1 is the safest choice, 4 will be too
2731 			 * big and cause kernel BTF validation failure if
2732 			 * original variable took less than 4 bytes
2733 			 */
2734 			t->size = 1;
2735 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2736 		} else if (!has_datasec && btf_is_datasec(t)) {
2737 			/* replace DATASEC with STRUCT */
2738 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2739 			struct btf_member *m = btf_members(t);
2740 			struct btf_type *vt;
2741 			char *name;
2742 
2743 			name = (char *)btf__name_by_offset(btf, t->name_off);
2744 			while (*name) {
2745 				if (*name == '.')
2746 					*name = '_';
2747 				name++;
2748 			}
2749 
2750 			vlen = btf_vlen(t);
2751 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2752 			for (j = 0; j < vlen; j++, v++, m++) {
2753 				/* order of field assignments is important */
2754 				m->offset = v->offset * 8;
2755 				m->type = v->type;
2756 				/* preserve variable name as member name */
2757 				vt = (void *)btf__type_by_id(btf, v->type);
2758 				m->name_off = vt->name_off;
2759 			}
2760 		} else if (!has_func && btf_is_func_proto(t)) {
2761 			/* replace FUNC_PROTO with ENUM */
2762 			vlen = btf_vlen(t);
2763 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2764 			t->size = sizeof(__u32); /* kernel enforced */
2765 		} else if (!has_func && btf_is_func(t)) {
2766 			/* replace FUNC with TYPEDEF */
2767 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2768 		} else if (!has_func_global && btf_is_func(t)) {
2769 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2770 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2771 		} else if (!has_float && btf_is_float(t)) {
2772 			/* replace FLOAT with an equally-sized empty STRUCT;
2773 			 * since C compilers do not accept e.g. "float" as a
2774 			 * valid struct name, make it anonymous
2775 			 */
2776 			t->name_off = 0;
2777 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2778 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2779 			/* replace TYPE_TAG with a CONST */
2780 			t->name_off = 0;
2781 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2782 		} else if (!has_enum64 && btf_is_enum(t)) {
2783 			/* clear the kflag */
2784 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2785 		} else if (!has_enum64 && btf_is_enum64(t)) {
2786 			/* replace ENUM64 with a union */
2787 			struct btf_member *m;
2788 
2789 			if (enum64_placeholder_id == 0) {
2790 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2791 				if (enum64_placeholder_id < 0)
2792 					return enum64_placeholder_id;
2793 
2794 				t = (struct btf_type *)btf__type_by_id(btf, i);
2795 			}
2796 
2797 			m = btf_members(t);
2798 			vlen = btf_vlen(t);
2799 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2800 			for (j = 0; j < vlen; j++, m++) {
2801 				m->type = enum64_placeholder_id;
2802 				m->offset = 0;
2803 			}
2804 		}
2805 	}
2806 
2807 	return 0;
2808 }
2809 
libbpf_needs_btf(const struct bpf_object * obj)2810 static bool libbpf_needs_btf(const struct bpf_object *obj)
2811 {
2812 	return obj->efile.btf_maps_shndx >= 0 ||
2813 	       obj->efile.st_ops_shndx >= 0 ||
2814 	       obj->efile.st_ops_link_shndx >= 0 ||
2815 	       obj->nr_extern > 0;
2816 }
2817 
kernel_needs_btf(const struct bpf_object * obj)2818 static bool kernel_needs_btf(const struct bpf_object *obj)
2819 {
2820 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2821 }
2822 
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)2823 static int bpf_object__init_btf(struct bpf_object *obj,
2824 				Elf_Data *btf_data,
2825 				Elf_Data *btf_ext_data)
2826 {
2827 	int err = -ENOENT;
2828 
2829 	if (btf_data) {
2830 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2831 		err = libbpf_get_error(obj->btf);
2832 		if (err) {
2833 			obj->btf = NULL;
2834 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2835 			goto out;
2836 		}
2837 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2838 		btf__set_pointer_size(obj->btf, 8);
2839 	}
2840 	if (btf_ext_data) {
2841 		struct btf_ext_info *ext_segs[3];
2842 		int seg_num, sec_num;
2843 
2844 		if (!obj->btf) {
2845 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2846 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2847 			goto out;
2848 		}
2849 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2850 		err = libbpf_get_error(obj->btf_ext);
2851 		if (err) {
2852 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2853 				BTF_EXT_ELF_SEC, err);
2854 			obj->btf_ext = NULL;
2855 			goto out;
2856 		}
2857 
2858 		/* setup .BTF.ext to ELF section mapping */
2859 		ext_segs[0] = &obj->btf_ext->func_info;
2860 		ext_segs[1] = &obj->btf_ext->line_info;
2861 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2862 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2863 			struct btf_ext_info *seg = ext_segs[seg_num];
2864 			const struct btf_ext_info_sec *sec;
2865 			const char *sec_name;
2866 			Elf_Scn *scn;
2867 
2868 			if (seg->sec_cnt == 0)
2869 				continue;
2870 
2871 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2872 			if (!seg->sec_idxs) {
2873 				err = -ENOMEM;
2874 				goto out;
2875 			}
2876 
2877 			sec_num = 0;
2878 			for_each_btf_ext_sec(seg, sec) {
2879 				/* preventively increment index to avoid doing
2880 				 * this before every continue below
2881 				 */
2882 				sec_num++;
2883 
2884 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2885 				if (str_is_empty(sec_name))
2886 					continue;
2887 				scn = elf_sec_by_name(obj, sec_name);
2888 				if (!scn)
2889 					continue;
2890 
2891 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2892 			}
2893 		}
2894 	}
2895 out:
2896 	if (err && libbpf_needs_btf(obj)) {
2897 		pr_warn("BTF is required, but is missing or corrupted.\n");
2898 		return err;
2899 	}
2900 	return 0;
2901 }
2902 
compare_vsi_off(const void * _a,const void * _b)2903 static int compare_vsi_off(const void *_a, const void *_b)
2904 {
2905 	const struct btf_var_secinfo *a = _a;
2906 	const struct btf_var_secinfo *b = _b;
2907 
2908 	return a->offset - b->offset;
2909 }
2910 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)2911 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2912 			     struct btf_type *t)
2913 {
2914 	__u32 size = 0, i, vars = btf_vlen(t);
2915 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2916 	struct btf_var_secinfo *vsi;
2917 	bool fixup_offsets = false;
2918 	int err;
2919 
2920 	if (!sec_name) {
2921 		pr_debug("No name found in string section for DATASEC kind.\n");
2922 		return -ENOENT;
2923 	}
2924 
2925 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2926 	 * variable offsets set at the previous step. Further, not every
2927 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2928 	 * all fixups altogether for such sections and go straight to sorting
2929 	 * VARs within their DATASEC.
2930 	 */
2931 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2932 		goto sort_vars;
2933 
2934 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2935 	 * fix this up. But BPF static linker already fixes this up and fills
2936 	 * all the sizes and offsets during static linking. So this step has
2937 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2938 	 * non-extern DATASEC, so the variable fixup loop below handles both
2939 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2940 	 * symbol matching just once.
2941 	 */
2942 	if (t->size == 0) {
2943 		err = find_elf_sec_sz(obj, sec_name, &size);
2944 		if (err || !size) {
2945 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2946 				 sec_name, size, err);
2947 			return -ENOENT;
2948 		}
2949 
2950 		t->size = size;
2951 		fixup_offsets = true;
2952 	}
2953 
2954 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2955 		const struct btf_type *t_var;
2956 		struct btf_var *var;
2957 		const char *var_name;
2958 		Elf64_Sym *sym;
2959 
2960 		t_var = btf__type_by_id(btf, vsi->type);
2961 		if (!t_var || !btf_is_var(t_var)) {
2962 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2963 			return -EINVAL;
2964 		}
2965 
2966 		var = btf_var(t_var);
2967 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2968 			continue;
2969 
2970 		var_name = btf__name_by_offset(btf, t_var->name_off);
2971 		if (!var_name) {
2972 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2973 				 sec_name, i);
2974 			return -ENOENT;
2975 		}
2976 
2977 		sym = find_elf_var_sym(obj, var_name);
2978 		if (IS_ERR(sym)) {
2979 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2980 				 sec_name, var_name);
2981 			return -ENOENT;
2982 		}
2983 
2984 		if (fixup_offsets)
2985 			vsi->offset = sym->st_value;
2986 
2987 		/* if variable is a global/weak symbol, but has restricted
2988 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2989 		 * as static. This follows similar logic for functions (BPF
2990 		 * subprogs) and influences libbpf's further decisions about
2991 		 * whether to make global data BPF array maps as
2992 		 * BPF_F_MMAPABLE.
2993 		 */
2994 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2995 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2996 			var->linkage = BTF_VAR_STATIC;
2997 	}
2998 
2999 sort_vars:
3000 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3001 	return 0;
3002 }
3003 
bpf_object_fixup_btf(struct bpf_object * obj)3004 static int bpf_object_fixup_btf(struct bpf_object *obj)
3005 {
3006 	int i, n, err = 0;
3007 
3008 	if (!obj->btf)
3009 		return 0;
3010 
3011 	n = btf__type_cnt(obj->btf);
3012 	for (i = 1; i < n; i++) {
3013 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3014 
3015 		/* Loader needs to fix up some of the things compiler
3016 		 * couldn't get its hands on while emitting BTF. This
3017 		 * is section size and global variable offset. We use
3018 		 * the info from the ELF itself for this purpose.
3019 		 */
3020 		if (btf_is_datasec(t)) {
3021 			err = btf_fixup_datasec(obj, obj->btf, t);
3022 			if (err)
3023 				return err;
3024 		}
3025 	}
3026 
3027 	return 0;
3028 }
3029 
prog_needs_vmlinux_btf(struct bpf_program * prog)3030 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3031 {
3032 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3033 	    prog->type == BPF_PROG_TYPE_LSM)
3034 		return true;
3035 
3036 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3037 	 * also need vmlinux BTF
3038 	 */
3039 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3040 		return true;
3041 
3042 	return false;
3043 }
3044 
obj_needs_vmlinux_btf(const struct bpf_object * obj)3045 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3046 {
3047 	struct bpf_program *prog;
3048 	int i;
3049 
3050 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3051 	 * is not specified
3052 	 */
3053 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3054 		return true;
3055 
3056 	/* Support for typed ksyms needs kernel BTF */
3057 	for (i = 0; i < obj->nr_extern; i++) {
3058 		const struct extern_desc *ext;
3059 
3060 		ext = &obj->externs[i];
3061 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3062 			return true;
3063 	}
3064 
3065 	bpf_object__for_each_program(prog, obj) {
3066 		if (!prog->autoload)
3067 			continue;
3068 		if (prog_needs_vmlinux_btf(prog))
3069 			return true;
3070 	}
3071 
3072 	return false;
3073 }
3074 
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3075 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3076 {
3077 	int err;
3078 
3079 	/* btf_vmlinux could be loaded earlier */
3080 	if (obj->btf_vmlinux || obj->gen_loader)
3081 		return 0;
3082 
3083 	if (!force && !obj_needs_vmlinux_btf(obj))
3084 		return 0;
3085 
3086 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3087 	err = libbpf_get_error(obj->btf_vmlinux);
3088 	if (err) {
3089 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3090 		obj->btf_vmlinux = NULL;
3091 		return err;
3092 	}
3093 	return 0;
3094 }
3095 
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3096 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3097 {
3098 	struct btf *kern_btf = obj->btf;
3099 	bool btf_mandatory, sanitize;
3100 	int i, err = 0;
3101 
3102 	if (!obj->btf)
3103 		return 0;
3104 
3105 	if (!kernel_supports(obj, FEAT_BTF)) {
3106 		if (kernel_needs_btf(obj)) {
3107 			err = -EOPNOTSUPP;
3108 			goto report;
3109 		}
3110 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3111 		return 0;
3112 	}
3113 
3114 	/* Even though some subprogs are global/weak, user might prefer more
3115 	 * permissive BPF verification process that BPF verifier performs for
3116 	 * static functions, taking into account more context from the caller
3117 	 * functions. In such case, they need to mark such subprogs with
3118 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3119 	 * corresponding FUNC BTF type to be marked as static and trigger more
3120 	 * involved BPF verification process.
3121 	 */
3122 	for (i = 0; i < obj->nr_programs; i++) {
3123 		struct bpf_program *prog = &obj->programs[i];
3124 		struct btf_type *t;
3125 		const char *name;
3126 		int j, n;
3127 
3128 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3129 			continue;
3130 
3131 		n = btf__type_cnt(obj->btf);
3132 		for (j = 1; j < n; j++) {
3133 			t = btf_type_by_id(obj->btf, j);
3134 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3135 				continue;
3136 
3137 			name = btf__str_by_offset(obj->btf, t->name_off);
3138 			if (strcmp(name, prog->name) != 0)
3139 				continue;
3140 
3141 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3142 			break;
3143 		}
3144 	}
3145 
3146 	sanitize = btf_needs_sanitization(obj);
3147 	if (sanitize) {
3148 		const void *raw_data;
3149 		__u32 sz;
3150 
3151 		/* clone BTF to sanitize a copy and leave the original intact */
3152 		raw_data = btf__raw_data(obj->btf, &sz);
3153 		kern_btf = btf__new(raw_data, sz);
3154 		err = libbpf_get_error(kern_btf);
3155 		if (err)
3156 			return err;
3157 
3158 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3159 		btf__set_pointer_size(obj->btf, 8);
3160 		err = bpf_object__sanitize_btf(obj, kern_btf);
3161 		if (err)
3162 			return err;
3163 	}
3164 
3165 	if (obj->gen_loader) {
3166 		__u32 raw_size = 0;
3167 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3168 
3169 		if (!raw_data)
3170 			return -ENOMEM;
3171 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3172 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3173 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3174 		 */
3175 		btf__set_fd(kern_btf, 0);
3176 	} else {
3177 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3178 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3179 					   obj->log_level ? 1 : 0);
3180 	}
3181 	if (sanitize) {
3182 		if (!err) {
3183 			/* move fd to libbpf's BTF */
3184 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3185 			btf__set_fd(kern_btf, -1);
3186 		}
3187 		btf__free(kern_btf);
3188 	}
3189 report:
3190 	if (err) {
3191 		btf_mandatory = kernel_needs_btf(obj);
3192 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3193 			btf_mandatory ? "BTF is mandatory, can't proceed."
3194 				      : "BTF is optional, ignoring.");
3195 		if (!btf_mandatory)
3196 			err = 0;
3197 	}
3198 	return err;
3199 }
3200 
elf_sym_str(const struct bpf_object * obj,size_t off)3201 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3202 {
3203 	const char *name;
3204 
3205 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3206 	if (!name) {
3207 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3208 			off, obj->path, elf_errmsg(-1));
3209 		return NULL;
3210 	}
3211 
3212 	return name;
3213 }
3214 
elf_sec_str(const struct bpf_object * obj,size_t off)3215 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3216 {
3217 	const char *name;
3218 
3219 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3220 	if (!name) {
3221 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3222 			off, obj->path, elf_errmsg(-1));
3223 		return NULL;
3224 	}
3225 
3226 	return name;
3227 }
3228 
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3229 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3230 {
3231 	Elf_Scn *scn;
3232 
3233 	scn = elf_getscn(obj->efile.elf, idx);
3234 	if (!scn) {
3235 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3236 			idx, obj->path, elf_errmsg(-1));
3237 		return NULL;
3238 	}
3239 	return scn;
3240 }
3241 
elf_sec_by_name(const struct bpf_object * obj,const char * name)3242 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3243 {
3244 	Elf_Scn *scn = NULL;
3245 	Elf *elf = obj->efile.elf;
3246 	const char *sec_name;
3247 
3248 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3249 		sec_name = elf_sec_name(obj, scn);
3250 		if (!sec_name)
3251 			return NULL;
3252 
3253 		if (strcmp(sec_name, name) != 0)
3254 			continue;
3255 
3256 		return scn;
3257 	}
3258 	return NULL;
3259 }
3260 
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3261 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3262 {
3263 	Elf64_Shdr *shdr;
3264 
3265 	if (!scn)
3266 		return NULL;
3267 
3268 	shdr = elf64_getshdr(scn);
3269 	if (!shdr) {
3270 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3271 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3272 		return NULL;
3273 	}
3274 
3275 	return shdr;
3276 }
3277 
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3278 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3279 {
3280 	const char *name;
3281 	Elf64_Shdr *sh;
3282 
3283 	if (!scn)
3284 		return NULL;
3285 
3286 	sh = elf_sec_hdr(obj, scn);
3287 	if (!sh)
3288 		return NULL;
3289 
3290 	name = elf_sec_str(obj, sh->sh_name);
3291 	if (!name) {
3292 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3293 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3294 		return NULL;
3295 	}
3296 
3297 	return name;
3298 }
3299 
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3300 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3301 {
3302 	Elf_Data *data;
3303 
3304 	if (!scn)
3305 		return NULL;
3306 
3307 	data = elf_getdata(scn, 0);
3308 	if (!data) {
3309 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3310 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3311 			obj->path, elf_errmsg(-1));
3312 		return NULL;
3313 	}
3314 
3315 	return data;
3316 }
3317 
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3318 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3319 {
3320 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3321 		return NULL;
3322 
3323 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3324 }
3325 
elf_rel_by_idx(Elf_Data * data,size_t idx)3326 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3327 {
3328 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3329 		return NULL;
3330 
3331 	return (Elf64_Rel *)data->d_buf + idx;
3332 }
3333 
is_sec_name_dwarf(const char * name)3334 static bool is_sec_name_dwarf(const char *name)
3335 {
3336 	/* approximation, but the actual list is too long */
3337 	return str_has_pfx(name, ".debug_");
3338 }
3339 
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3340 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3341 {
3342 	/* no special handling of .strtab */
3343 	if (hdr->sh_type == SHT_STRTAB)
3344 		return true;
3345 
3346 	/* ignore .llvm_addrsig section as well */
3347 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3348 		return true;
3349 
3350 	/* no subprograms will lead to an empty .text section, ignore it */
3351 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3352 	    strcmp(name, ".text") == 0)
3353 		return true;
3354 
3355 	/* DWARF sections */
3356 	if (is_sec_name_dwarf(name))
3357 		return true;
3358 
3359 	if (str_has_pfx(name, ".rel")) {
3360 		name += sizeof(".rel") - 1;
3361 		/* DWARF section relocations */
3362 		if (is_sec_name_dwarf(name))
3363 			return true;
3364 
3365 		/* .BTF and .BTF.ext don't need relocations */
3366 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3367 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3368 			return true;
3369 	}
3370 
3371 	return false;
3372 }
3373 
cmp_progs(const void * _a,const void * _b)3374 static int cmp_progs(const void *_a, const void *_b)
3375 {
3376 	const struct bpf_program *a = _a;
3377 	const struct bpf_program *b = _b;
3378 
3379 	if (a->sec_idx != b->sec_idx)
3380 		return a->sec_idx < b->sec_idx ? -1 : 1;
3381 
3382 	/* sec_insn_off can't be the same within the section */
3383 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3384 }
3385 
bpf_object__elf_collect(struct bpf_object * obj)3386 static int bpf_object__elf_collect(struct bpf_object *obj)
3387 {
3388 	struct elf_sec_desc *sec_desc;
3389 	Elf *elf = obj->efile.elf;
3390 	Elf_Data *btf_ext_data = NULL;
3391 	Elf_Data *btf_data = NULL;
3392 	int idx = 0, err = 0;
3393 	const char *name;
3394 	Elf_Data *data;
3395 	Elf_Scn *scn;
3396 	Elf64_Shdr *sh;
3397 
3398 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3399 	 * section. Since section count retrieved by elf_getshdrnum() does
3400 	 * include sec #0, it is already the necessary size of an array to keep
3401 	 * all the sections.
3402 	 */
3403 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3404 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3405 			obj->path, elf_errmsg(-1));
3406 		return -LIBBPF_ERRNO__FORMAT;
3407 	}
3408 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3409 	if (!obj->efile.secs)
3410 		return -ENOMEM;
3411 
3412 	/* a bunch of ELF parsing functionality depends on processing symbols,
3413 	 * so do the first pass and find the symbol table
3414 	 */
3415 	scn = NULL;
3416 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3417 		sh = elf_sec_hdr(obj, scn);
3418 		if (!sh)
3419 			return -LIBBPF_ERRNO__FORMAT;
3420 
3421 		if (sh->sh_type == SHT_SYMTAB) {
3422 			if (obj->efile.symbols) {
3423 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3424 				return -LIBBPF_ERRNO__FORMAT;
3425 			}
3426 
3427 			data = elf_sec_data(obj, scn);
3428 			if (!data)
3429 				return -LIBBPF_ERRNO__FORMAT;
3430 
3431 			idx = elf_ndxscn(scn);
3432 
3433 			obj->efile.symbols = data;
3434 			obj->efile.symbols_shndx = idx;
3435 			obj->efile.strtabidx = sh->sh_link;
3436 		}
3437 	}
3438 
3439 	if (!obj->efile.symbols) {
3440 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3441 			obj->path);
3442 		return -ENOENT;
3443 	}
3444 
3445 	scn = NULL;
3446 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3447 		idx = elf_ndxscn(scn);
3448 		sec_desc = &obj->efile.secs[idx];
3449 
3450 		sh = elf_sec_hdr(obj, scn);
3451 		if (!sh)
3452 			return -LIBBPF_ERRNO__FORMAT;
3453 
3454 		name = elf_sec_str(obj, sh->sh_name);
3455 		if (!name)
3456 			return -LIBBPF_ERRNO__FORMAT;
3457 
3458 		if (ignore_elf_section(sh, name))
3459 			continue;
3460 
3461 		data = elf_sec_data(obj, scn);
3462 		if (!data)
3463 			return -LIBBPF_ERRNO__FORMAT;
3464 
3465 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3466 			 idx, name, (unsigned long)data->d_size,
3467 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3468 			 (int)sh->sh_type);
3469 
3470 		if (strcmp(name, "license") == 0) {
3471 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3472 			if (err)
3473 				return err;
3474 		} else if (strcmp(name, "version") == 0) {
3475 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3476 			if (err)
3477 				return err;
3478 		} else if (strcmp(name, "maps") == 0) {
3479 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3480 			return -ENOTSUP;
3481 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3482 			obj->efile.btf_maps_shndx = idx;
3483 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3484 			if (sh->sh_type != SHT_PROGBITS)
3485 				return -LIBBPF_ERRNO__FORMAT;
3486 			btf_data = data;
3487 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3488 			if (sh->sh_type != SHT_PROGBITS)
3489 				return -LIBBPF_ERRNO__FORMAT;
3490 			btf_ext_data = data;
3491 		} else if (sh->sh_type == SHT_SYMTAB) {
3492 			/* already processed during the first pass above */
3493 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3494 			if (sh->sh_flags & SHF_EXECINSTR) {
3495 				if (strcmp(name, ".text") == 0)
3496 					obj->efile.text_shndx = idx;
3497 				err = bpf_object__add_programs(obj, data, name, idx);
3498 				if (err)
3499 					return err;
3500 			} else if (strcmp(name, DATA_SEC) == 0 ||
3501 				   str_has_pfx(name, DATA_SEC ".")) {
3502 				sec_desc->sec_type = SEC_DATA;
3503 				sec_desc->shdr = sh;
3504 				sec_desc->data = data;
3505 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3506 				   str_has_pfx(name, RODATA_SEC ".")) {
3507 				sec_desc->sec_type = SEC_RODATA;
3508 				sec_desc->shdr = sh;
3509 				sec_desc->data = data;
3510 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3511 				obj->efile.st_ops_data = data;
3512 				obj->efile.st_ops_shndx = idx;
3513 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3514 				obj->efile.st_ops_link_data = data;
3515 				obj->efile.st_ops_link_shndx = idx;
3516 			} else {
3517 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3518 					idx, name);
3519 			}
3520 		} else if (sh->sh_type == SHT_REL) {
3521 			int targ_sec_idx = sh->sh_info; /* points to other section */
3522 
3523 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3524 			    targ_sec_idx >= obj->efile.sec_cnt)
3525 				return -LIBBPF_ERRNO__FORMAT;
3526 
3527 			/* Only do relo for section with exec instructions */
3528 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3529 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3530 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3531 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3532 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3533 					idx, name, targ_sec_idx,
3534 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3535 				continue;
3536 			}
3537 
3538 			sec_desc->sec_type = SEC_RELO;
3539 			sec_desc->shdr = sh;
3540 			sec_desc->data = data;
3541 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3542 							 str_has_pfx(name, BSS_SEC "."))) {
3543 			sec_desc->sec_type = SEC_BSS;
3544 			sec_desc->shdr = sh;
3545 			sec_desc->data = data;
3546 		} else {
3547 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3548 				(size_t)sh->sh_size);
3549 		}
3550 	}
3551 
3552 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3553 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3554 		return -LIBBPF_ERRNO__FORMAT;
3555 	}
3556 
3557 	/* sort BPF programs by section name and in-section instruction offset
3558 	 * for faster search
3559 	 */
3560 	if (obj->nr_programs)
3561 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3562 
3563 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3564 }
3565 
sym_is_extern(const Elf64_Sym * sym)3566 static bool sym_is_extern(const Elf64_Sym *sym)
3567 {
3568 	int bind = ELF64_ST_BIND(sym->st_info);
3569 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3570 	return sym->st_shndx == SHN_UNDEF &&
3571 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3572 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3573 }
3574 
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)3575 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3576 {
3577 	int bind = ELF64_ST_BIND(sym->st_info);
3578 	int type = ELF64_ST_TYPE(sym->st_info);
3579 
3580 	/* in .text section */
3581 	if (sym->st_shndx != text_shndx)
3582 		return false;
3583 
3584 	/* local function */
3585 	if (bind == STB_LOCAL && type == STT_SECTION)
3586 		return true;
3587 
3588 	/* global function */
3589 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
3590 }
3591 
find_extern_btf_id(const struct btf * btf,const char * ext_name)3592 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3593 {
3594 	const struct btf_type *t;
3595 	const char *tname;
3596 	int i, n;
3597 
3598 	if (!btf)
3599 		return -ESRCH;
3600 
3601 	n = btf__type_cnt(btf);
3602 	for (i = 1; i < n; i++) {
3603 		t = btf__type_by_id(btf, i);
3604 
3605 		if (!btf_is_var(t) && !btf_is_func(t))
3606 			continue;
3607 
3608 		tname = btf__name_by_offset(btf, t->name_off);
3609 		if (strcmp(tname, ext_name))
3610 			continue;
3611 
3612 		if (btf_is_var(t) &&
3613 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3614 			return -EINVAL;
3615 
3616 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3617 			return -EINVAL;
3618 
3619 		return i;
3620 	}
3621 
3622 	return -ENOENT;
3623 }
3624 
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)3625 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3626 	const struct btf_var_secinfo *vs;
3627 	const struct btf_type *t;
3628 	int i, j, n;
3629 
3630 	if (!btf)
3631 		return -ESRCH;
3632 
3633 	n = btf__type_cnt(btf);
3634 	for (i = 1; i < n; i++) {
3635 		t = btf__type_by_id(btf, i);
3636 
3637 		if (!btf_is_datasec(t))
3638 			continue;
3639 
3640 		vs = btf_var_secinfos(t);
3641 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3642 			if (vs->type == ext_btf_id)
3643 				return i;
3644 		}
3645 	}
3646 
3647 	return -ENOENT;
3648 }
3649 
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)3650 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3651 				     bool *is_signed)
3652 {
3653 	const struct btf_type *t;
3654 	const char *name;
3655 
3656 	t = skip_mods_and_typedefs(btf, id, NULL);
3657 	name = btf__name_by_offset(btf, t->name_off);
3658 
3659 	if (is_signed)
3660 		*is_signed = false;
3661 	switch (btf_kind(t)) {
3662 	case BTF_KIND_INT: {
3663 		int enc = btf_int_encoding(t);
3664 
3665 		if (enc & BTF_INT_BOOL)
3666 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3667 		if (is_signed)
3668 			*is_signed = enc & BTF_INT_SIGNED;
3669 		if (t->size == 1)
3670 			return KCFG_CHAR;
3671 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3672 			return KCFG_UNKNOWN;
3673 		return KCFG_INT;
3674 	}
3675 	case BTF_KIND_ENUM:
3676 		if (t->size != 4)
3677 			return KCFG_UNKNOWN;
3678 		if (strcmp(name, "libbpf_tristate"))
3679 			return KCFG_UNKNOWN;
3680 		return KCFG_TRISTATE;
3681 	case BTF_KIND_ENUM64:
3682 		if (strcmp(name, "libbpf_tristate"))
3683 			return KCFG_UNKNOWN;
3684 		return KCFG_TRISTATE;
3685 	case BTF_KIND_ARRAY:
3686 		if (btf_array(t)->nelems == 0)
3687 			return KCFG_UNKNOWN;
3688 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3689 			return KCFG_UNKNOWN;
3690 		return KCFG_CHAR_ARR;
3691 	default:
3692 		return KCFG_UNKNOWN;
3693 	}
3694 }
3695 
cmp_externs(const void * _a,const void * _b)3696 static int cmp_externs(const void *_a, const void *_b)
3697 {
3698 	const struct extern_desc *a = _a;
3699 	const struct extern_desc *b = _b;
3700 
3701 	if (a->type != b->type)
3702 		return a->type < b->type ? -1 : 1;
3703 
3704 	if (a->type == EXT_KCFG) {
3705 		/* descending order by alignment requirements */
3706 		if (a->kcfg.align != b->kcfg.align)
3707 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3708 		/* ascending order by size, within same alignment class */
3709 		if (a->kcfg.sz != b->kcfg.sz)
3710 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3711 	}
3712 
3713 	/* resolve ties by name */
3714 	return strcmp(a->name, b->name);
3715 }
3716 
find_int_btf_id(const struct btf * btf)3717 static int find_int_btf_id(const struct btf *btf)
3718 {
3719 	const struct btf_type *t;
3720 	int i, n;
3721 
3722 	n = btf__type_cnt(btf);
3723 	for (i = 1; i < n; i++) {
3724 		t = btf__type_by_id(btf, i);
3725 
3726 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3727 			return i;
3728 	}
3729 
3730 	return 0;
3731 }
3732 
add_dummy_ksym_var(struct btf * btf)3733 static int add_dummy_ksym_var(struct btf *btf)
3734 {
3735 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3736 	const struct btf_var_secinfo *vs;
3737 	const struct btf_type *sec;
3738 
3739 	if (!btf)
3740 		return 0;
3741 
3742 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3743 					    BTF_KIND_DATASEC);
3744 	if (sec_btf_id < 0)
3745 		return 0;
3746 
3747 	sec = btf__type_by_id(btf, sec_btf_id);
3748 	vs = btf_var_secinfos(sec);
3749 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3750 		const struct btf_type *vt;
3751 
3752 		vt = btf__type_by_id(btf, vs->type);
3753 		if (btf_is_func(vt))
3754 			break;
3755 	}
3756 
3757 	/* No func in ksyms sec.  No need to add dummy var. */
3758 	if (i == btf_vlen(sec))
3759 		return 0;
3760 
3761 	int_btf_id = find_int_btf_id(btf);
3762 	dummy_var_btf_id = btf__add_var(btf,
3763 					"dummy_ksym",
3764 					BTF_VAR_GLOBAL_ALLOCATED,
3765 					int_btf_id);
3766 	if (dummy_var_btf_id < 0)
3767 		pr_warn("cannot create a dummy_ksym var\n");
3768 
3769 	return dummy_var_btf_id;
3770 }
3771 
bpf_object__collect_externs(struct bpf_object * obj)3772 static int bpf_object__collect_externs(struct bpf_object *obj)
3773 {
3774 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3775 	const struct btf_type *t;
3776 	struct extern_desc *ext;
3777 	int i, n, off, dummy_var_btf_id;
3778 	const char *ext_name, *sec_name;
3779 	size_t ext_essent_len;
3780 	Elf_Scn *scn;
3781 	Elf64_Shdr *sh;
3782 
3783 	if (!obj->efile.symbols)
3784 		return 0;
3785 
3786 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3787 	sh = elf_sec_hdr(obj, scn);
3788 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3789 		return -LIBBPF_ERRNO__FORMAT;
3790 
3791 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3792 	if (dummy_var_btf_id < 0)
3793 		return dummy_var_btf_id;
3794 
3795 	n = sh->sh_size / sh->sh_entsize;
3796 	pr_debug("looking for externs among %d symbols...\n", n);
3797 
3798 	for (i = 0; i < n; i++) {
3799 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3800 
3801 		if (!sym)
3802 			return -LIBBPF_ERRNO__FORMAT;
3803 		if (!sym_is_extern(sym))
3804 			continue;
3805 		ext_name = elf_sym_str(obj, sym->st_name);
3806 		if (!ext_name || !ext_name[0])
3807 			continue;
3808 
3809 		ext = obj->externs;
3810 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3811 		if (!ext)
3812 			return -ENOMEM;
3813 		obj->externs = ext;
3814 		ext = &ext[obj->nr_extern];
3815 		memset(ext, 0, sizeof(*ext));
3816 		obj->nr_extern++;
3817 
3818 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3819 		if (ext->btf_id <= 0) {
3820 			pr_warn("failed to find BTF for extern '%s': %d\n",
3821 				ext_name, ext->btf_id);
3822 			return ext->btf_id;
3823 		}
3824 		t = btf__type_by_id(obj->btf, ext->btf_id);
3825 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
3826 		if (!ext->name)
3827 			return -ENOMEM;
3828 		ext->sym_idx = i;
3829 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3830 
3831 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3832 		ext->essent_name = NULL;
3833 		if (ext_essent_len != strlen(ext->name)) {
3834 			ext->essent_name = strndup(ext->name, ext_essent_len);
3835 			if (!ext->essent_name)
3836 				return -ENOMEM;
3837 		}
3838 
3839 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3840 		if (ext->sec_btf_id <= 0) {
3841 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3842 				ext_name, ext->btf_id, ext->sec_btf_id);
3843 			return ext->sec_btf_id;
3844 		}
3845 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3846 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3847 
3848 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3849 			if (btf_is_func(t)) {
3850 				pr_warn("extern function %s is unsupported under %s section\n",
3851 					ext->name, KCONFIG_SEC);
3852 				return -ENOTSUP;
3853 			}
3854 			kcfg_sec = sec;
3855 			ext->type = EXT_KCFG;
3856 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3857 			if (ext->kcfg.sz <= 0) {
3858 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3859 					ext_name, ext->kcfg.sz);
3860 				return ext->kcfg.sz;
3861 			}
3862 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3863 			if (ext->kcfg.align <= 0) {
3864 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3865 					ext_name, ext->kcfg.align);
3866 				return -EINVAL;
3867 			}
3868 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3869 							&ext->kcfg.is_signed);
3870 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3871 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3872 				return -ENOTSUP;
3873 			}
3874 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3875 			ksym_sec = sec;
3876 			ext->type = EXT_KSYM;
3877 			skip_mods_and_typedefs(obj->btf, t->type,
3878 					       &ext->ksym.type_id);
3879 		} else {
3880 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3881 			return -ENOTSUP;
3882 		}
3883 	}
3884 	pr_debug("collected %d externs total\n", obj->nr_extern);
3885 
3886 	if (!obj->nr_extern)
3887 		return 0;
3888 
3889 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3890 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3891 
3892 	/* for .ksyms section, we need to turn all externs into allocated
3893 	 * variables in BTF to pass kernel verification; we do this by
3894 	 * pretending that each extern is a 8-byte variable
3895 	 */
3896 	if (ksym_sec) {
3897 		/* find existing 4-byte integer type in BTF to use for fake
3898 		 * extern variables in DATASEC
3899 		 */
3900 		int int_btf_id = find_int_btf_id(obj->btf);
3901 		/* For extern function, a dummy_var added earlier
3902 		 * will be used to replace the vs->type and
3903 		 * its name string will be used to refill
3904 		 * the missing param's name.
3905 		 */
3906 		const struct btf_type *dummy_var;
3907 
3908 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3909 		for (i = 0; i < obj->nr_extern; i++) {
3910 			ext = &obj->externs[i];
3911 			if (ext->type != EXT_KSYM)
3912 				continue;
3913 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3914 				 i, ext->sym_idx, ext->name);
3915 		}
3916 
3917 		sec = ksym_sec;
3918 		n = btf_vlen(sec);
3919 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3920 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3921 			struct btf_type *vt;
3922 
3923 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3924 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3925 			ext = find_extern_by_name(obj, ext_name);
3926 			if (!ext) {
3927 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3928 					btf_kind_str(vt), ext_name);
3929 				return -ESRCH;
3930 			}
3931 			if (btf_is_func(vt)) {
3932 				const struct btf_type *func_proto;
3933 				struct btf_param *param;
3934 				int j;
3935 
3936 				func_proto = btf__type_by_id(obj->btf,
3937 							     vt->type);
3938 				param = btf_params(func_proto);
3939 				/* Reuse the dummy_var string if the
3940 				 * func proto does not have param name.
3941 				 */
3942 				for (j = 0; j < btf_vlen(func_proto); j++)
3943 					if (param[j].type && !param[j].name_off)
3944 						param[j].name_off =
3945 							dummy_var->name_off;
3946 				vs->type = dummy_var_btf_id;
3947 				vt->info &= ~0xffff;
3948 				vt->info |= BTF_FUNC_GLOBAL;
3949 			} else {
3950 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3951 				vt->type = int_btf_id;
3952 			}
3953 			vs->offset = off;
3954 			vs->size = sizeof(int);
3955 		}
3956 		sec->size = off;
3957 	}
3958 
3959 	if (kcfg_sec) {
3960 		sec = kcfg_sec;
3961 		/* for kcfg externs calculate their offsets within a .kconfig map */
3962 		off = 0;
3963 		for (i = 0; i < obj->nr_extern; i++) {
3964 			ext = &obj->externs[i];
3965 			if (ext->type != EXT_KCFG)
3966 				continue;
3967 
3968 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3969 			off = ext->kcfg.data_off + ext->kcfg.sz;
3970 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3971 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3972 		}
3973 		sec->size = off;
3974 		n = btf_vlen(sec);
3975 		for (i = 0; i < n; i++) {
3976 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3977 
3978 			t = btf__type_by_id(obj->btf, vs->type);
3979 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3980 			ext = find_extern_by_name(obj, ext_name);
3981 			if (!ext) {
3982 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3983 					ext_name);
3984 				return -ESRCH;
3985 			}
3986 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3987 			vs->offset = ext->kcfg.data_off;
3988 		}
3989 	}
3990 	return 0;
3991 }
3992 
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)3993 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3994 {
3995 	return prog->sec_idx == obj->efile.text_shndx;
3996 }
3997 
3998 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)3999 bpf_object__find_program_by_name(const struct bpf_object *obj,
4000 				 const char *name)
4001 {
4002 	struct bpf_program *prog;
4003 
4004 	bpf_object__for_each_program(prog, obj) {
4005 		if (prog_is_subprog(obj, prog))
4006 			continue;
4007 		if (!strcmp(prog->name, name))
4008 			return prog;
4009 	}
4010 	return errno = ENOENT, NULL;
4011 }
4012 
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4013 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4014 				      int shndx)
4015 {
4016 	switch (obj->efile.secs[shndx].sec_type) {
4017 	case SEC_BSS:
4018 	case SEC_DATA:
4019 	case SEC_RODATA:
4020 		return true;
4021 	default:
4022 		return false;
4023 	}
4024 }
4025 
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4026 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4027 				      int shndx)
4028 {
4029 	return shndx == obj->efile.btf_maps_shndx;
4030 }
4031 
4032 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4033 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4034 {
4035 	if (shndx == obj->efile.symbols_shndx)
4036 		return LIBBPF_MAP_KCONFIG;
4037 
4038 	switch (obj->efile.secs[shndx].sec_type) {
4039 	case SEC_BSS:
4040 		return LIBBPF_MAP_BSS;
4041 	case SEC_DATA:
4042 		return LIBBPF_MAP_DATA;
4043 	case SEC_RODATA:
4044 		return LIBBPF_MAP_RODATA;
4045 	default:
4046 		return LIBBPF_MAP_UNSPEC;
4047 	}
4048 }
4049 
bpf_program__record_reloc(struct bpf_program * prog,struct reloc_desc * reloc_desc,__u32 insn_idx,const char * sym_name,const Elf64_Sym * sym,const Elf64_Rel * rel)4050 static int bpf_program__record_reloc(struct bpf_program *prog,
4051 				     struct reloc_desc *reloc_desc,
4052 				     __u32 insn_idx, const char *sym_name,
4053 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4054 {
4055 	struct bpf_insn *insn = &prog->insns[insn_idx];
4056 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4057 	struct bpf_object *obj = prog->obj;
4058 	__u32 shdr_idx = sym->st_shndx;
4059 	enum libbpf_map_type type;
4060 	const char *sym_sec_name;
4061 	struct bpf_map *map;
4062 
4063 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4064 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4065 			prog->name, sym_name, insn_idx, insn->code);
4066 		return -LIBBPF_ERRNO__RELOC;
4067 	}
4068 
4069 	if (sym_is_extern(sym)) {
4070 		int sym_idx = ELF64_R_SYM(rel->r_info);
4071 		int i, n = obj->nr_extern;
4072 		struct extern_desc *ext;
4073 
4074 		for (i = 0; i < n; i++) {
4075 			ext = &obj->externs[i];
4076 			if (ext->sym_idx == sym_idx)
4077 				break;
4078 		}
4079 		if (i >= n) {
4080 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4081 				prog->name, sym_name, sym_idx);
4082 			return -LIBBPF_ERRNO__RELOC;
4083 		}
4084 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4085 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4086 		if (insn->code == (BPF_JMP | BPF_CALL))
4087 			reloc_desc->type = RELO_EXTERN_CALL;
4088 		else
4089 			reloc_desc->type = RELO_EXTERN_LD64;
4090 		reloc_desc->insn_idx = insn_idx;
4091 		reloc_desc->ext_idx = i;
4092 		return 0;
4093 	}
4094 
4095 	/* sub-program call relocation */
4096 	if (is_call_insn(insn)) {
4097 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4098 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4099 			return -LIBBPF_ERRNO__RELOC;
4100 		}
4101 		/* text_shndx can be 0, if no default "main" program exists */
4102 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4103 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4104 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4105 				prog->name, sym_name, sym_sec_name);
4106 			return -LIBBPF_ERRNO__RELOC;
4107 		}
4108 		if (sym->st_value % BPF_INSN_SZ) {
4109 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4110 				prog->name, sym_name, (size_t)sym->st_value);
4111 			return -LIBBPF_ERRNO__RELOC;
4112 		}
4113 		reloc_desc->type = RELO_CALL;
4114 		reloc_desc->insn_idx = insn_idx;
4115 		reloc_desc->sym_off = sym->st_value;
4116 		return 0;
4117 	}
4118 
4119 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4120 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4121 			prog->name, sym_name, shdr_idx);
4122 		return -LIBBPF_ERRNO__RELOC;
4123 	}
4124 
4125 	/* loading subprog addresses */
4126 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4127 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4128 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4129 		 */
4130 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4131 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4132 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4133 			return -LIBBPF_ERRNO__RELOC;
4134 		}
4135 
4136 		reloc_desc->type = RELO_SUBPROG_ADDR;
4137 		reloc_desc->insn_idx = insn_idx;
4138 		reloc_desc->sym_off = sym->st_value;
4139 		return 0;
4140 	}
4141 
4142 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4143 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4144 
4145 	/* generic map reference relocation */
4146 	if (type == LIBBPF_MAP_UNSPEC) {
4147 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4148 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4149 				prog->name, sym_name, sym_sec_name);
4150 			return -LIBBPF_ERRNO__RELOC;
4151 		}
4152 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4153 			map = &obj->maps[map_idx];
4154 			if (map->libbpf_type != type ||
4155 			    map->sec_idx != sym->st_shndx ||
4156 			    map->sec_offset != sym->st_value)
4157 				continue;
4158 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4159 				 prog->name, map_idx, map->name, map->sec_idx,
4160 				 map->sec_offset, insn_idx);
4161 			break;
4162 		}
4163 		if (map_idx >= nr_maps) {
4164 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4165 				prog->name, sym_sec_name, (size_t)sym->st_value);
4166 			return -LIBBPF_ERRNO__RELOC;
4167 		}
4168 		reloc_desc->type = RELO_LD64;
4169 		reloc_desc->insn_idx = insn_idx;
4170 		reloc_desc->map_idx = map_idx;
4171 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4172 		return 0;
4173 	}
4174 
4175 	/* global data map relocation */
4176 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4177 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4178 			prog->name, sym_sec_name);
4179 		return -LIBBPF_ERRNO__RELOC;
4180 	}
4181 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4182 		map = &obj->maps[map_idx];
4183 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4184 			continue;
4185 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4186 			 prog->name, map_idx, map->name, map->sec_idx,
4187 			 map->sec_offset, insn_idx);
4188 		break;
4189 	}
4190 	if (map_idx >= nr_maps) {
4191 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4192 			prog->name, sym_sec_name);
4193 		return -LIBBPF_ERRNO__RELOC;
4194 	}
4195 
4196 	reloc_desc->type = RELO_DATA;
4197 	reloc_desc->insn_idx = insn_idx;
4198 	reloc_desc->map_idx = map_idx;
4199 	reloc_desc->sym_off = sym->st_value;
4200 	return 0;
4201 }
4202 
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4203 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4204 {
4205 	return insn_idx >= prog->sec_insn_off &&
4206 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4207 }
4208 
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4209 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4210 						 size_t sec_idx, size_t insn_idx)
4211 {
4212 	int l = 0, r = obj->nr_programs - 1, m;
4213 	struct bpf_program *prog;
4214 
4215 	if (!obj->nr_programs)
4216 		return NULL;
4217 
4218 	while (l < r) {
4219 		m = l + (r - l + 1) / 2;
4220 		prog = &obj->programs[m];
4221 
4222 		if (prog->sec_idx < sec_idx ||
4223 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4224 			l = m;
4225 		else
4226 			r = m - 1;
4227 	}
4228 	/* matching program could be at index l, but it still might be the
4229 	 * wrong one, so we need to double check conditions for the last time
4230 	 */
4231 	prog = &obj->programs[l];
4232 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4233 		return prog;
4234 	return NULL;
4235 }
4236 
4237 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4238 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4239 {
4240 	const char *relo_sec_name, *sec_name;
4241 	size_t sec_idx = shdr->sh_info, sym_idx;
4242 	struct bpf_program *prog;
4243 	struct reloc_desc *relos;
4244 	int err, i, nrels;
4245 	const char *sym_name;
4246 	__u32 insn_idx;
4247 	Elf_Scn *scn;
4248 	Elf_Data *scn_data;
4249 	Elf64_Sym *sym;
4250 	Elf64_Rel *rel;
4251 
4252 	if (sec_idx >= obj->efile.sec_cnt)
4253 		return -EINVAL;
4254 
4255 	scn = elf_sec_by_idx(obj, sec_idx);
4256 	scn_data = elf_sec_data(obj, scn);
4257 	if (!scn_data)
4258 		return -LIBBPF_ERRNO__FORMAT;
4259 
4260 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4261 	sec_name = elf_sec_name(obj, scn);
4262 	if (!relo_sec_name || !sec_name)
4263 		return -EINVAL;
4264 
4265 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4266 		 relo_sec_name, sec_idx, sec_name);
4267 	nrels = shdr->sh_size / shdr->sh_entsize;
4268 
4269 	for (i = 0; i < nrels; i++) {
4270 		rel = elf_rel_by_idx(data, i);
4271 		if (!rel) {
4272 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4273 			return -LIBBPF_ERRNO__FORMAT;
4274 		}
4275 
4276 		sym_idx = ELF64_R_SYM(rel->r_info);
4277 		sym = elf_sym_by_idx(obj, sym_idx);
4278 		if (!sym) {
4279 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4280 				relo_sec_name, sym_idx, i);
4281 			return -LIBBPF_ERRNO__FORMAT;
4282 		}
4283 
4284 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4285 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4286 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4287 			return -LIBBPF_ERRNO__FORMAT;
4288 		}
4289 
4290 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4291 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4292 				relo_sec_name, (size_t)rel->r_offset, i);
4293 			return -LIBBPF_ERRNO__FORMAT;
4294 		}
4295 
4296 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4297 		/* relocations against static functions are recorded as
4298 		 * relocations against the section that contains a function;
4299 		 * in such case, symbol will be STT_SECTION and sym.st_name
4300 		 * will point to empty string (0), so fetch section name
4301 		 * instead
4302 		 */
4303 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4304 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4305 		else
4306 			sym_name = elf_sym_str(obj, sym->st_name);
4307 		sym_name = sym_name ?: "<?";
4308 
4309 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4310 			 relo_sec_name, i, insn_idx, sym_name);
4311 
4312 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4313 		if (!prog) {
4314 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4315 				relo_sec_name, i, sec_name, insn_idx);
4316 			continue;
4317 		}
4318 
4319 		relos = libbpf_reallocarray(prog->reloc_desc,
4320 					    prog->nr_reloc + 1, sizeof(*relos));
4321 		if (!relos)
4322 			return -ENOMEM;
4323 		prog->reloc_desc = relos;
4324 
4325 		/* adjust insn_idx to local BPF program frame of reference */
4326 		insn_idx -= prog->sec_insn_off;
4327 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4328 						insn_idx, sym_name, sym, rel);
4329 		if (err)
4330 			return err;
4331 
4332 		prog->nr_reloc++;
4333 	}
4334 	return 0;
4335 }
4336 
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4337 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4338 {
4339 	int id;
4340 
4341 	if (!obj->btf)
4342 		return -ENOENT;
4343 
4344 	/* if it's BTF-defined map, we don't need to search for type IDs.
4345 	 * For struct_ops map, it does not need btf_key_type_id and
4346 	 * btf_value_type_id.
4347 	 */
4348 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4349 		return 0;
4350 
4351 	/*
4352 	 * LLVM annotates global data differently in BTF, that is,
4353 	 * only as '.data', '.bss' or '.rodata'.
4354 	 */
4355 	if (!bpf_map__is_internal(map))
4356 		return -ENOENT;
4357 
4358 	id = btf__find_by_name(obj->btf, map->real_name);
4359 	if (id < 0)
4360 		return id;
4361 
4362 	map->btf_key_type_id = 0;
4363 	map->btf_value_type_id = id;
4364 	return 0;
4365 }
4366 
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4367 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4368 {
4369 	char file[PATH_MAX], buff[4096];
4370 	FILE *fp;
4371 	__u32 val;
4372 	int err;
4373 
4374 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4375 	memset(info, 0, sizeof(*info));
4376 
4377 	fp = fopen(file, "re");
4378 	if (!fp) {
4379 		err = -errno;
4380 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4381 			err);
4382 		return err;
4383 	}
4384 
4385 	while (fgets(buff, sizeof(buff), fp)) {
4386 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4387 			info->type = val;
4388 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4389 			info->key_size = val;
4390 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4391 			info->value_size = val;
4392 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4393 			info->max_entries = val;
4394 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4395 			info->map_flags = val;
4396 	}
4397 
4398 	fclose(fp);
4399 
4400 	return 0;
4401 }
4402 
bpf_map__autocreate(const struct bpf_map * map)4403 bool bpf_map__autocreate(const struct bpf_map *map)
4404 {
4405 	return map->autocreate;
4406 }
4407 
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4408 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4409 {
4410 	if (map->obj->loaded)
4411 		return libbpf_err(-EBUSY);
4412 
4413 	map->autocreate = autocreate;
4414 	return 0;
4415 }
4416 
bpf_map__reuse_fd(struct bpf_map * map,int fd)4417 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4418 {
4419 	struct bpf_map_info info;
4420 	__u32 len = sizeof(info), name_len;
4421 	int new_fd, err;
4422 	char *new_name;
4423 
4424 	memset(&info, 0, len);
4425 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4426 	if (err && errno == EINVAL)
4427 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4428 	if (err)
4429 		return libbpf_err(err);
4430 
4431 	name_len = strlen(info.name);
4432 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4433 		new_name = strdup(map->name);
4434 	else
4435 		new_name = strdup(info.name);
4436 
4437 	if (!new_name)
4438 		return libbpf_err(-errno);
4439 
4440 	/*
4441 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4442 	 * This is similar to what we do in ensure_good_fd(), but without
4443 	 * closing original FD.
4444 	 */
4445 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4446 	if (new_fd < 0) {
4447 		err = -errno;
4448 		goto err_free_new_name;
4449 	}
4450 
4451 	err = zclose(map->fd);
4452 	if (err) {
4453 		err = -errno;
4454 		goto err_close_new_fd;
4455 	}
4456 	free(map->name);
4457 
4458 	map->fd = new_fd;
4459 	map->name = new_name;
4460 	map->def.type = info.type;
4461 	map->def.key_size = info.key_size;
4462 	map->def.value_size = info.value_size;
4463 	map->def.max_entries = info.max_entries;
4464 	map->def.map_flags = info.map_flags;
4465 	map->btf_key_type_id = info.btf_key_type_id;
4466 	map->btf_value_type_id = info.btf_value_type_id;
4467 	map->reused = true;
4468 	map->map_extra = info.map_extra;
4469 
4470 	return 0;
4471 
4472 err_close_new_fd:
4473 	close(new_fd);
4474 err_free_new_name:
4475 	free(new_name);
4476 	return libbpf_err(err);
4477 }
4478 
bpf_map__max_entries(const struct bpf_map * map)4479 __u32 bpf_map__max_entries(const struct bpf_map *map)
4480 {
4481 	return map->def.max_entries;
4482 }
4483 
bpf_map__inner_map(struct bpf_map * map)4484 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4485 {
4486 	if (!bpf_map_type__is_map_in_map(map->def.type))
4487 		return errno = EINVAL, NULL;
4488 
4489 	return map->inner_map;
4490 }
4491 
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4492 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4493 {
4494 	if (map->obj->loaded)
4495 		return libbpf_err(-EBUSY);
4496 
4497 	map->def.max_entries = max_entries;
4498 
4499 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4500 	if (map_is_ringbuf(map))
4501 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4502 
4503 	return 0;
4504 }
4505 
4506 static int
bpf_object__probe_loading(struct bpf_object * obj)4507 bpf_object__probe_loading(struct bpf_object *obj)
4508 {
4509 	char *cp, errmsg[STRERR_BUFSIZE];
4510 	struct bpf_insn insns[] = {
4511 		BPF_MOV64_IMM(BPF_REG_0, 0),
4512 		BPF_EXIT_INSN(),
4513 	};
4514 	int ret, insn_cnt = ARRAY_SIZE(insns);
4515 
4516 	if (obj->gen_loader)
4517 		return 0;
4518 
4519 	ret = bump_rlimit_memlock();
4520 	if (ret)
4521 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4522 
4523 	/* make sure basic loading works */
4524 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4525 	if (ret < 0)
4526 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4527 	if (ret < 0) {
4528 		ret = errno;
4529 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4530 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4531 			"program. Make sure your kernel supports BPF "
4532 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4533 			"set to big enough value.\n", __func__, cp, ret);
4534 		return -ret;
4535 	}
4536 	close(ret);
4537 
4538 	return 0;
4539 }
4540 
probe_fd(int fd)4541 static int probe_fd(int fd)
4542 {
4543 	if (fd >= 0)
4544 		close(fd);
4545 	return fd >= 0;
4546 }
4547 
probe_kern_prog_name(void)4548 static int probe_kern_prog_name(void)
4549 {
4550 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4551 	struct bpf_insn insns[] = {
4552 		BPF_MOV64_IMM(BPF_REG_0, 0),
4553 		BPF_EXIT_INSN(),
4554 	};
4555 	union bpf_attr attr;
4556 	int ret;
4557 
4558 	memset(&attr, 0, attr_sz);
4559 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4560 	attr.license = ptr_to_u64("GPL");
4561 	attr.insns = ptr_to_u64(insns);
4562 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4563 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4564 
4565 	/* make sure loading with name works */
4566 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4567 	return probe_fd(ret);
4568 }
4569 
probe_kern_global_data(void)4570 static int probe_kern_global_data(void)
4571 {
4572 	char *cp, errmsg[STRERR_BUFSIZE];
4573 	struct bpf_insn insns[] = {
4574 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4575 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4576 		BPF_MOV64_IMM(BPF_REG_0, 0),
4577 		BPF_EXIT_INSN(),
4578 	};
4579 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4580 
4581 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4582 	if (map < 0) {
4583 		ret = -errno;
4584 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4585 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4586 			__func__, cp, -ret);
4587 		return ret;
4588 	}
4589 
4590 	insns[0].imm = map;
4591 
4592 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4593 	close(map);
4594 	return probe_fd(ret);
4595 }
4596 
probe_kern_btf(void)4597 static int probe_kern_btf(void)
4598 {
4599 	static const char strs[] = "\0int";
4600 	__u32 types[] = {
4601 		/* int */
4602 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4603 	};
4604 
4605 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4606 					     strs, sizeof(strs)));
4607 }
4608 
probe_kern_btf_func(void)4609 static int probe_kern_btf_func(void)
4610 {
4611 	static const char strs[] = "\0int\0x\0a";
4612 	/* void x(int a) {} */
4613 	__u32 types[] = {
4614 		/* int */
4615 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4616 		/* FUNC_PROTO */                                /* [2] */
4617 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4618 		BTF_PARAM_ENC(7, 1),
4619 		/* FUNC x */                                    /* [3] */
4620 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4621 	};
4622 
4623 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4624 					     strs, sizeof(strs)));
4625 }
4626 
probe_kern_btf_func_global(void)4627 static int probe_kern_btf_func_global(void)
4628 {
4629 	static const char strs[] = "\0int\0x\0a";
4630 	/* static void x(int a) {} */
4631 	__u32 types[] = {
4632 		/* int */
4633 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4634 		/* FUNC_PROTO */                                /* [2] */
4635 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4636 		BTF_PARAM_ENC(7, 1),
4637 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4638 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4639 	};
4640 
4641 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4642 					     strs, sizeof(strs)));
4643 }
4644 
probe_kern_btf_datasec(void)4645 static int probe_kern_btf_datasec(void)
4646 {
4647 	static const char strs[] = "\0x\0.data";
4648 	/* static int a; */
4649 	__u32 types[] = {
4650 		/* int */
4651 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4652 		/* VAR x */                                     /* [2] */
4653 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4654 		BTF_VAR_STATIC,
4655 		/* DATASEC val */                               /* [3] */
4656 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4657 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4658 	};
4659 
4660 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4661 					     strs, sizeof(strs)));
4662 }
4663 
probe_kern_btf_float(void)4664 static int probe_kern_btf_float(void)
4665 {
4666 	static const char strs[] = "\0float";
4667 	__u32 types[] = {
4668 		/* float */
4669 		BTF_TYPE_FLOAT_ENC(1, 4),
4670 	};
4671 
4672 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4673 					     strs, sizeof(strs)));
4674 }
4675 
probe_kern_btf_decl_tag(void)4676 static int probe_kern_btf_decl_tag(void)
4677 {
4678 	static const char strs[] = "\0tag";
4679 	__u32 types[] = {
4680 		/* int */
4681 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4682 		/* VAR x */                                     /* [2] */
4683 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4684 		BTF_VAR_STATIC,
4685 		/* attr */
4686 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4687 	};
4688 
4689 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4690 					     strs, sizeof(strs)));
4691 }
4692 
probe_kern_btf_type_tag(void)4693 static int probe_kern_btf_type_tag(void)
4694 {
4695 	static const char strs[] = "\0tag";
4696 	__u32 types[] = {
4697 		/* int */
4698 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4699 		/* attr */
4700 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4701 		/* ptr */
4702 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4703 	};
4704 
4705 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4706 					     strs, sizeof(strs)));
4707 }
4708 
probe_kern_array_mmap(void)4709 static int probe_kern_array_mmap(void)
4710 {
4711 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4712 	int fd;
4713 
4714 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4715 	return probe_fd(fd);
4716 }
4717 
probe_kern_exp_attach_type(void)4718 static int probe_kern_exp_attach_type(void)
4719 {
4720 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4721 	struct bpf_insn insns[] = {
4722 		BPF_MOV64_IMM(BPF_REG_0, 0),
4723 		BPF_EXIT_INSN(),
4724 	};
4725 	int fd, insn_cnt = ARRAY_SIZE(insns);
4726 
4727 	/* use any valid combination of program type and (optional)
4728 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4729 	 * to see if kernel supports expected_attach_type field for
4730 	 * BPF_PROG_LOAD command
4731 	 */
4732 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4733 	return probe_fd(fd);
4734 }
4735 
probe_kern_probe_read_kernel(void)4736 static int probe_kern_probe_read_kernel(void)
4737 {
4738 	struct bpf_insn insns[] = {
4739 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4740 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4741 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4742 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4743 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4744 		BPF_EXIT_INSN(),
4745 	};
4746 	int fd, insn_cnt = ARRAY_SIZE(insns);
4747 
4748 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4749 	return probe_fd(fd);
4750 }
4751 
probe_prog_bind_map(void)4752 static int probe_prog_bind_map(void)
4753 {
4754 	char *cp, errmsg[STRERR_BUFSIZE];
4755 	struct bpf_insn insns[] = {
4756 		BPF_MOV64_IMM(BPF_REG_0, 0),
4757 		BPF_EXIT_INSN(),
4758 	};
4759 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4760 
4761 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4762 	if (map < 0) {
4763 		ret = -errno;
4764 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4765 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4766 			__func__, cp, -ret);
4767 		return ret;
4768 	}
4769 
4770 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4771 	if (prog < 0) {
4772 		close(map);
4773 		return 0;
4774 	}
4775 
4776 	ret = bpf_prog_bind_map(prog, map, NULL);
4777 
4778 	close(map);
4779 	close(prog);
4780 
4781 	return ret >= 0;
4782 }
4783 
probe_module_btf(void)4784 static int probe_module_btf(void)
4785 {
4786 	static const char strs[] = "\0int";
4787 	__u32 types[] = {
4788 		/* int */
4789 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4790 	};
4791 	struct bpf_btf_info info;
4792 	__u32 len = sizeof(info);
4793 	char name[16];
4794 	int fd, err;
4795 
4796 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4797 	if (fd < 0)
4798 		return 0; /* BTF not supported at all */
4799 
4800 	memset(&info, 0, sizeof(info));
4801 	info.name = ptr_to_u64(name);
4802 	info.name_len = sizeof(name);
4803 
4804 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4805 	 * kernel's module BTF support coincides with support for
4806 	 * name/name_len fields in struct bpf_btf_info.
4807 	 */
4808 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4809 	close(fd);
4810 	return !err;
4811 }
4812 
probe_perf_link(void)4813 static int probe_perf_link(void)
4814 {
4815 	struct bpf_insn insns[] = {
4816 		BPF_MOV64_IMM(BPF_REG_0, 0),
4817 		BPF_EXIT_INSN(),
4818 	};
4819 	int prog_fd, link_fd, err;
4820 
4821 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4822 				insns, ARRAY_SIZE(insns), NULL);
4823 	if (prog_fd < 0)
4824 		return -errno;
4825 
4826 	/* use invalid perf_event FD to get EBADF, if link is supported;
4827 	 * otherwise EINVAL should be returned
4828 	 */
4829 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4830 	err = -errno; /* close() can clobber errno */
4831 
4832 	if (link_fd >= 0)
4833 		close(link_fd);
4834 	close(prog_fd);
4835 
4836 	return link_fd < 0 && err == -EBADF;
4837 }
4838 
probe_uprobe_multi_link(void)4839 static int probe_uprobe_multi_link(void)
4840 {
4841 	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4842 		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4843 	);
4844 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4845 	struct bpf_insn insns[] = {
4846 		BPF_MOV64_IMM(BPF_REG_0, 0),
4847 		BPF_EXIT_INSN(),
4848 	};
4849 	int prog_fd, link_fd, err;
4850 	unsigned long offset = 0;
4851 
4852 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4853 				insns, ARRAY_SIZE(insns), &load_opts);
4854 	if (prog_fd < 0)
4855 		return -errno;
4856 
4857 	/* Creating uprobe in '/' binary should fail with -EBADF. */
4858 	link_opts.uprobe_multi.path = "/";
4859 	link_opts.uprobe_multi.offsets = &offset;
4860 	link_opts.uprobe_multi.cnt = 1;
4861 
4862 	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4863 	err = -errno; /* close() can clobber errno */
4864 
4865 	if (link_fd >= 0)
4866 		close(link_fd);
4867 	close(prog_fd);
4868 
4869 	return link_fd < 0 && err == -EBADF;
4870 }
4871 
probe_kern_bpf_cookie(void)4872 static int probe_kern_bpf_cookie(void)
4873 {
4874 	struct bpf_insn insns[] = {
4875 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4876 		BPF_EXIT_INSN(),
4877 	};
4878 	int ret, insn_cnt = ARRAY_SIZE(insns);
4879 
4880 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4881 	return probe_fd(ret);
4882 }
4883 
probe_kern_btf_enum64(void)4884 static int probe_kern_btf_enum64(void)
4885 {
4886 	static const char strs[] = "\0enum64";
4887 	__u32 types[] = {
4888 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4889 	};
4890 
4891 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4892 					     strs, sizeof(strs)));
4893 }
4894 
4895 static int probe_kern_syscall_wrapper(void);
4896 
4897 enum kern_feature_result {
4898 	FEAT_UNKNOWN = 0,
4899 	FEAT_SUPPORTED = 1,
4900 	FEAT_MISSING = 2,
4901 };
4902 
4903 typedef int (*feature_probe_fn)(void);
4904 
4905 static struct kern_feature_desc {
4906 	const char *desc;
4907 	feature_probe_fn probe;
4908 	enum kern_feature_result res;
4909 } feature_probes[__FEAT_CNT] = {
4910 	[FEAT_PROG_NAME] = {
4911 		"BPF program name", probe_kern_prog_name,
4912 	},
4913 	[FEAT_GLOBAL_DATA] = {
4914 		"global variables", probe_kern_global_data,
4915 	},
4916 	[FEAT_BTF] = {
4917 		"minimal BTF", probe_kern_btf,
4918 	},
4919 	[FEAT_BTF_FUNC] = {
4920 		"BTF functions", probe_kern_btf_func,
4921 	},
4922 	[FEAT_BTF_GLOBAL_FUNC] = {
4923 		"BTF global function", probe_kern_btf_func_global,
4924 	},
4925 	[FEAT_BTF_DATASEC] = {
4926 		"BTF data section and variable", probe_kern_btf_datasec,
4927 	},
4928 	[FEAT_ARRAY_MMAP] = {
4929 		"ARRAY map mmap()", probe_kern_array_mmap,
4930 	},
4931 	[FEAT_EXP_ATTACH_TYPE] = {
4932 		"BPF_PROG_LOAD expected_attach_type attribute",
4933 		probe_kern_exp_attach_type,
4934 	},
4935 	[FEAT_PROBE_READ_KERN] = {
4936 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4937 	},
4938 	[FEAT_PROG_BIND_MAP] = {
4939 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4940 	},
4941 	[FEAT_MODULE_BTF] = {
4942 		"module BTF support", probe_module_btf,
4943 	},
4944 	[FEAT_BTF_FLOAT] = {
4945 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4946 	},
4947 	[FEAT_PERF_LINK] = {
4948 		"BPF perf link support", probe_perf_link,
4949 	},
4950 	[FEAT_BTF_DECL_TAG] = {
4951 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4952 	},
4953 	[FEAT_BTF_TYPE_TAG] = {
4954 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4955 	},
4956 	[FEAT_MEMCG_ACCOUNT] = {
4957 		"memcg-based memory accounting", probe_memcg_account,
4958 	},
4959 	[FEAT_BPF_COOKIE] = {
4960 		"BPF cookie support", probe_kern_bpf_cookie,
4961 	},
4962 	[FEAT_BTF_ENUM64] = {
4963 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4964 	},
4965 	[FEAT_SYSCALL_WRAPPER] = {
4966 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4967 	},
4968 	[FEAT_UPROBE_MULTI_LINK] = {
4969 		"BPF multi-uprobe link support", probe_uprobe_multi_link,
4970 	},
4971 };
4972 
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)4973 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4974 {
4975 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4976 	int ret;
4977 
4978 	if (obj && obj->gen_loader)
4979 		/* To generate loader program assume the latest kernel
4980 		 * to avoid doing extra prog_load, map_create syscalls.
4981 		 */
4982 		return true;
4983 
4984 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4985 		ret = feat->probe();
4986 		if (ret > 0) {
4987 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4988 		} else if (ret == 0) {
4989 			WRITE_ONCE(feat->res, FEAT_MISSING);
4990 		} else {
4991 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4992 			WRITE_ONCE(feat->res, FEAT_MISSING);
4993 		}
4994 	}
4995 
4996 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4997 }
4998 
map_is_reuse_compat(const struct bpf_map * map,int map_fd)4999 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5000 {
5001 	struct bpf_map_info map_info;
5002 	char msg[STRERR_BUFSIZE];
5003 	__u32 map_info_len = sizeof(map_info);
5004 	int err;
5005 
5006 	memset(&map_info, 0, map_info_len);
5007 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5008 	if (err && errno == EINVAL)
5009 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5010 	if (err) {
5011 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5012 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5013 		return false;
5014 	}
5015 
5016 	return (map_info.type == map->def.type &&
5017 		map_info.key_size == map->def.key_size &&
5018 		map_info.value_size == map->def.value_size &&
5019 		map_info.max_entries == map->def.max_entries &&
5020 		map_info.map_flags == map->def.map_flags &&
5021 		map_info.map_extra == map->map_extra);
5022 }
5023 
5024 static int
bpf_object__reuse_map(struct bpf_map * map)5025 bpf_object__reuse_map(struct bpf_map *map)
5026 {
5027 	char *cp, errmsg[STRERR_BUFSIZE];
5028 	int err, pin_fd;
5029 
5030 	pin_fd = bpf_obj_get(map->pin_path);
5031 	if (pin_fd < 0) {
5032 		err = -errno;
5033 		if (err == -ENOENT) {
5034 			pr_debug("found no pinned map to reuse at '%s'\n",
5035 				 map->pin_path);
5036 			return 0;
5037 		}
5038 
5039 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5040 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5041 			map->pin_path, cp);
5042 		return err;
5043 	}
5044 
5045 	if (!map_is_reuse_compat(map, pin_fd)) {
5046 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5047 			map->pin_path);
5048 		close(pin_fd);
5049 		return -EINVAL;
5050 	}
5051 
5052 	err = bpf_map__reuse_fd(map, pin_fd);
5053 	close(pin_fd);
5054 	if (err)
5055 		return err;
5056 
5057 	map->pinned = true;
5058 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5059 
5060 	return 0;
5061 }
5062 
5063 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5064 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5065 {
5066 	enum libbpf_map_type map_type = map->libbpf_type;
5067 	char *cp, errmsg[STRERR_BUFSIZE];
5068 	int err, zero = 0;
5069 
5070 	if (obj->gen_loader) {
5071 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5072 					 map->mmaped, map->def.value_size);
5073 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5074 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5075 		return 0;
5076 	}
5077 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5078 	if (err) {
5079 		err = -errno;
5080 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5081 		pr_warn("Error setting initial map(%s) contents: %s\n",
5082 			map->name, cp);
5083 		return err;
5084 	}
5085 
5086 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5087 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5088 		err = bpf_map_freeze(map->fd);
5089 		if (err) {
5090 			err = -errno;
5091 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5092 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5093 				map->name, cp);
5094 			return err;
5095 		}
5096 	}
5097 	return 0;
5098 }
5099 
5100 static void bpf_map__destroy(struct bpf_map *map);
5101 
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5102 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5103 {
5104 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5105 	struct bpf_map_def *def = &map->def;
5106 	const char *map_name = NULL;
5107 	int err = 0;
5108 
5109 	if (kernel_supports(obj, FEAT_PROG_NAME))
5110 		map_name = map->name;
5111 	create_attr.map_ifindex = map->map_ifindex;
5112 	create_attr.map_flags = def->map_flags;
5113 	create_attr.numa_node = map->numa_node;
5114 	create_attr.map_extra = map->map_extra;
5115 
5116 	if (bpf_map__is_struct_ops(map))
5117 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5118 
5119 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5120 		create_attr.btf_fd = btf__fd(obj->btf);
5121 		create_attr.btf_key_type_id = map->btf_key_type_id;
5122 		create_attr.btf_value_type_id = map->btf_value_type_id;
5123 	}
5124 
5125 	if (bpf_map_type__is_map_in_map(def->type)) {
5126 		if (map->inner_map) {
5127 			err = map_set_def_max_entries(map->inner_map);
5128 			if (err)
5129 				return err;
5130 			err = bpf_object__create_map(obj, map->inner_map, true);
5131 			if (err) {
5132 				pr_warn("map '%s': failed to create inner map: %d\n",
5133 					map->name, err);
5134 				return err;
5135 			}
5136 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5137 		}
5138 		if (map->inner_map_fd >= 0)
5139 			create_attr.inner_map_fd = map->inner_map_fd;
5140 	}
5141 
5142 	switch (def->type) {
5143 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5144 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5145 	case BPF_MAP_TYPE_STACK_TRACE:
5146 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5147 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5148 	case BPF_MAP_TYPE_DEVMAP:
5149 	case BPF_MAP_TYPE_DEVMAP_HASH:
5150 	case BPF_MAP_TYPE_CPUMAP:
5151 	case BPF_MAP_TYPE_XSKMAP:
5152 	case BPF_MAP_TYPE_SOCKMAP:
5153 	case BPF_MAP_TYPE_SOCKHASH:
5154 	case BPF_MAP_TYPE_QUEUE:
5155 	case BPF_MAP_TYPE_STACK:
5156 		create_attr.btf_fd = 0;
5157 		create_attr.btf_key_type_id = 0;
5158 		create_attr.btf_value_type_id = 0;
5159 		map->btf_key_type_id = 0;
5160 		map->btf_value_type_id = 0;
5161 	default:
5162 		break;
5163 	}
5164 
5165 	if (obj->gen_loader) {
5166 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5167 				    def->key_size, def->value_size, def->max_entries,
5168 				    &create_attr, is_inner ? -1 : map - obj->maps);
5169 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5170 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5171 		 */
5172 		map->fd = 0;
5173 	} else {
5174 		map->fd = bpf_map_create(def->type, map_name,
5175 					 def->key_size, def->value_size,
5176 					 def->max_entries, &create_attr);
5177 	}
5178 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5179 			    create_attr.btf_value_type_id)) {
5180 		char *cp, errmsg[STRERR_BUFSIZE];
5181 
5182 		err = -errno;
5183 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5184 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5185 			map->name, cp, err);
5186 		create_attr.btf_fd = 0;
5187 		create_attr.btf_key_type_id = 0;
5188 		create_attr.btf_value_type_id = 0;
5189 		map->btf_key_type_id = 0;
5190 		map->btf_value_type_id = 0;
5191 		map->fd = bpf_map_create(def->type, map_name,
5192 					 def->key_size, def->value_size,
5193 					 def->max_entries, &create_attr);
5194 	}
5195 
5196 	err = map->fd < 0 ? -errno : 0;
5197 
5198 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5199 		if (obj->gen_loader)
5200 			map->inner_map->fd = -1;
5201 		bpf_map__destroy(map->inner_map);
5202 		zfree(&map->inner_map);
5203 	}
5204 
5205 	return err;
5206 }
5207 
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5208 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5209 {
5210 	const struct bpf_map *targ_map;
5211 	unsigned int i;
5212 	int fd, err = 0;
5213 
5214 	for (i = 0; i < map->init_slots_sz; i++) {
5215 		if (!map->init_slots[i])
5216 			continue;
5217 
5218 		targ_map = map->init_slots[i];
5219 		fd = bpf_map__fd(targ_map);
5220 
5221 		if (obj->gen_loader) {
5222 			bpf_gen__populate_outer_map(obj->gen_loader,
5223 						    map - obj->maps, i,
5224 						    targ_map - obj->maps);
5225 		} else {
5226 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5227 		}
5228 		if (err) {
5229 			err = -errno;
5230 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5231 				map->name, i, targ_map->name, fd, err);
5232 			return err;
5233 		}
5234 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5235 			 map->name, i, targ_map->name, fd);
5236 	}
5237 
5238 	zfree(&map->init_slots);
5239 	map->init_slots_sz = 0;
5240 
5241 	return 0;
5242 }
5243 
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5244 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5245 {
5246 	const struct bpf_program *targ_prog;
5247 	unsigned int i;
5248 	int fd, err;
5249 
5250 	if (obj->gen_loader)
5251 		return -ENOTSUP;
5252 
5253 	for (i = 0; i < map->init_slots_sz; i++) {
5254 		if (!map->init_slots[i])
5255 			continue;
5256 
5257 		targ_prog = map->init_slots[i];
5258 		fd = bpf_program__fd(targ_prog);
5259 
5260 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5261 		if (err) {
5262 			err = -errno;
5263 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5264 				map->name, i, targ_prog->name, fd, err);
5265 			return err;
5266 		}
5267 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5268 			 map->name, i, targ_prog->name, fd);
5269 	}
5270 
5271 	zfree(&map->init_slots);
5272 	map->init_slots_sz = 0;
5273 
5274 	return 0;
5275 }
5276 
bpf_object_init_prog_arrays(struct bpf_object * obj)5277 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5278 {
5279 	struct bpf_map *map;
5280 	int i, err;
5281 
5282 	for (i = 0; i < obj->nr_maps; i++) {
5283 		map = &obj->maps[i];
5284 
5285 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5286 			continue;
5287 
5288 		err = init_prog_array_slots(obj, map);
5289 		if (err < 0) {
5290 			zclose(map->fd);
5291 			return err;
5292 		}
5293 	}
5294 	return 0;
5295 }
5296 
map_set_def_max_entries(struct bpf_map * map)5297 static int map_set_def_max_entries(struct bpf_map *map)
5298 {
5299 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5300 		int nr_cpus;
5301 
5302 		nr_cpus = libbpf_num_possible_cpus();
5303 		if (nr_cpus < 0) {
5304 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5305 				map->name, nr_cpus);
5306 			return nr_cpus;
5307 		}
5308 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5309 		map->def.max_entries = nr_cpus;
5310 	}
5311 
5312 	return 0;
5313 }
5314 
5315 static int
bpf_object__create_maps(struct bpf_object * obj)5316 bpf_object__create_maps(struct bpf_object *obj)
5317 {
5318 	struct bpf_map *map;
5319 	char *cp, errmsg[STRERR_BUFSIZE];
5320 	unsigned int i, j;
5321 	int err;
5322 	bool retried;
5323 
5324 	for (i = 0; i < obj->nr_maps; i++) {
5325 		map = &obj->maps[i];
5326 
5327 		/* To support old kernels, we skip creating global data maps
5328 		 * (.rodata, .data, .kconfig, etc); later on, during program
5329 		 * loading, if we detect that at least one of the to-be-loaded
5330 		 * programs is referencing any global data map, we'll error
5331 		 * out with program name and relocation index logged.
5332 		 * This approach allows to accommodate Clang emitting
5333 		 * unnecessary .rodata.str1.1 sections for string literals,
5334 		 * but also it allows to have CO-RE applications that use
5335 		 * global variables in some of BPF programs, but not others.
5336 		 * If those global variable-using programs are not loaded at
5337 		 * runtime due to bpf_program__set_autoload(prog, false),
5338 		 * bpf_object loading will succeed just fine even on old
5339 		 * kernels.
5340 		 */
5341 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5342 			map->autocreate = false;
5343 
5344 		if (!map->autocreate) {
5345 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5346 			continue;
5347 		}
5348 
5349 		err = map_set_def_max_entries(map);
5350 		if (err)
5351 			goto err_out;
5352 
5353 		retried = false;
5354 retry:
5355 		if (map->pin_path) {
5356 			err = bpf_object__reuse_map(map);
5357 			if (err) {
5358 				pr_warn("map '%s': error reusing pinned map\n",
5359 					map->name);
5360 				goto err_out;
5361 			}
5362 			if (retried && map->fd < 0) {
5363 				pr_warn("map '%s': cannot find pinned map\n",
5364 					map->name);
5365 				err = -ENOENT;
5366 				goto err_out;
5367 			}
5368 		}
5369 
5370 		if (map->fd >= 0) {
5371 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5372 				 map->name, map->fd);
5373 		} else {
5374 			err = bpf_object__create_map(obj, map, false);
5375 			if (err)
5376 				goto err_out;
5377 
5378 			pr_debug("map '%s': created successfully, fd=%d\n",
5379 				 map->name, map->fd);
5380 
5381 			if (bpf_map__is_internal(map)) {
5382 				err = bpf_object__populate_internal_map(obj, map);
5383 				if (err < 0) {
5384 					zclose(map->fd);
5385 					goto err_out;
5386 				}
5387 			}
5388 
5389 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5390 				err = init_map_in_map_slots(obj, map);
5391 				if (err < 0) {
5392 					zclose(map->fd);
5393 					goto err_out;
5394 				}
5395 			}
5396 		}
5397 
5398 		if (map->pin_path && !map->pinned) {
5399 			err = bpf_map__pin(map, NULL);
5400 			if (err) {
5401 				zclose(map->fd);
5402 				if (!retried && err == -EEXIST) {
5403 					retried = true;
5404 					goto retry;
5405 				}
5406 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5407 					map->name, map->pin_path, err);
5408 				goto err_out;
5409 			}
5410 		}
5411 	}
5412 
5413 	return 0;
5414 
5415 err_out:
5416 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5417 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5418 	pr_perm_msg(err);
5419 	for (j = 0; j < i; j++)
5420 		zclose(obj->maps[j].fd);
5421 	return err;
5422 }
5423 
bpf_core_is_flavor_sep(const char * s)5424 static bool bpf_core_is_flavor_sep(const char *s)
5425 {
5426 	/* check X___Y name pattern, where X and Y are not underscores */
5427 	return s[0] != '_' &&				      /* X */
5428 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5429 	       s[4] != '_';				      /* Y */
5430 }
5431 
5432 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5433  * before last triple underscore. Struct name part after last triple
5434  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5435  */
bpf_core_essential_name_len(const char * name)5436 size_t bpf_core_essential_name_len(const char *name)
5437 {
5438 	size_t n = strlen(name);
5439 	int i;
5440 
5441 	for (i = n - 5; i >= 0; i--) {
5442 		if (bpf_core_is_flavor_sep(name + i))
5443 			return i + 1;
5444 	}
5445 	return n;
5446 }
5447 
bpf_core_free_cands(struct bpf_core_cand_list * cands)5448 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5449 {
5450 	if (!cands)
5451 		return;
5452 
5453 	free(cands->cands);
5454 	free(cands);
5455 }
5456 
bpf_core_add_cands(struct bpf_core_cand * local_cand,size_t local_essent_len,const struct btf * targ_btf,const char * targ_btf_name,int targ_start_id,struct bpf_core_cand_list * cands)5457 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5458 		       size_t local_essent_len,
5459 		       const struct btf *targ_btf,
5460 		       const char *targ_btf_name,
5461 		       int targ_start_id,
5462 		       struct bpf_core_cand_list *cands)
5463 {
5464 	struct bpf_core_cand *new_cands, *cand;
5465 	const struct btf_type *t, *local_t;
5466 	const char *targ_name, *local_name;
5467 	size_t targ_essent_len;
5468 	int n, i;
5469 
5470 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5471 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5472 
5473 	n = btf__type_cnt(targ_btf);
5474 	for (i = targ_start_id; i < n; i++) {
5475 		t = btf__type_by_id(targ_btf, i);
5476 		if (!btf_kind_core_compat(t, local_t))
5477 			continue;
5478 
5479 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5480 		if (str_is_empty(targ_name))
5481 			continue;
5482 
5483 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5484 		if (targ_essent_len != local_essent_len)
5485 			continue;
5486 
5487 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5488 			continue;
5489 
5490 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5491 			 local_cand->id, btf_kind_str(local_t),
5492 			 local_name, i, btf_kind_str(t), targ_name,
5493 			 targ_btf_name);
5494 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5495 					      sizeof(*cands->cands));
5496 		if (!new_cands)
5497 			return -ENOMEM;
5498 
5499 		cand = &new_cands[cands->len];
5500 		cand->btf = targ_btf;
5501 		cand->id = i;
5502 
5503 		cands->cands = new_cands;
5504 		cands->len++;
5505 	}
5506 	return 0;
5507 }
5508 
load_module_btfs(struct bpf_object * obj)5509 static int load_module_btfs(struct bpf_object *obj)
5510 {
5511 	struct bpf_btf_info info;
5512 	struct module_btf *mod_btf;
5513 	struct btf *btf;
5514 	char name[64];
5515 	__u32 id = 0, len;
5516 	int err, fd;
5517 
5518 	if (obj->btf_modules_loaded)
5519 		return 0;
5520 
5521 	if (obj->gen_loader)
5522 		return 0;
5523 
5524 	/* don't do this again, even if we find no module BTFs */
5525 	obj->btf_modules_loaded = true;
5526 
5527 	/* kernel too old to support module BTFs */
5528 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5529 		return 0;
5530 
5531 	while (true) {
5532 		err = bpf_btf_get_next_id(id, &id);
5533 		if (err && errno == ENOENT)
5534 			return 0;
5535 		if (err && errno == EPERM) {
5536 			pr_debug("skipping module BTFs loading, missing privileges\n");
5537 			return 0;
5538 		}
5539 		if (err) {
5540 			err = -errno;
5541 			pr_warn("failed to iterate BTF objects: %d\n", err);
5542 			return err;
5543 		}
5544 
5545 		fd = bpf_btf_get_fd_by_id(id);
5546 		if (fd < 0) {
5547 			if (errno == ENOENT)
5548 				continue; /* expected race: BTF was unloaded */
5549 			err = -errno;
5550 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5551 			return err;
5552 		}
5553 
5554 		len = sizeof(info);
5555 		memset(&info, 0, sizeof(info));
5556 		info.name = ptr_to_u64(name);
5557 		info.name_len = sizeof(name);
5558 
5559 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5560 		if (err) {
5561 			err = -errno;
5562 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5563 			goto err_out;
5564 		}
5565 
5566 		/* ignore non-module BTFs */
5567 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5568 			close(fd);
5569 			continue;
5570 		}
5571 
5572 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5573 		err = libbpf_get_error(btf);
5574 		if (err) {
5575 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5576 				name, id, err);
5577 			goto err_out;
5578 		}
5579 
5580 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5581 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5582 		if (err)
5583 			goto err_out;
5584 
5585 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5586 
5587 		mod_btf->btf = btf;
5588 		mod_btf->id = id;
5589 		mod_btf->fd = fd;
5590 		mod_btf->name = strdup(name);
5591 		if (!mod_btf->name) {
5592 			err = -ENOMEM;
5593 			goto err_out;
5594 		}
5595 		continue;
5596 
5597 err_out:
5598 		close(fd);
5599 		return err;
5600 	}
5601 
5602 	return 0;
5603 }
5604 
5605 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5606 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5607 {
5608 	struct bpf_core_cand local_cand = {};
5609 	struct bpf_core_cand_list *cands;
5610 	const struct btf *main_btf;
5611 	const struct btf_type *local_t;
5612 	const char *local_name;
5613 	size_t local_essent_len;
5614 	int err, i;
5615 
5616 	local_cand.btf = local_btf;
5617 	local_cand.id = local_type_id;
5618 	local_t = btf__type_by_id(local_btf, local_type_id);
5619 	if (!local_t)
5620 		return ERR_PTR(-EINVAL);
5621 
5622 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5623 	if (str_is_empty(local_name))
5624 		return ERR_PTR(-EINVAL);
5625 	local_essent_len = bpf_core_essential_name_len(local_name);
5626 
5627 	cands = calloc(1, sizeof(*cands));
5628 	if (!cands)
5629 		return ERR_PTR(-ENOMEM);
5630 
5631 	/* Attempt to find target candidates in vmlinux BTF first */
5632 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5633 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5634 	if (err)
5635 		goto err_out;
5636 
5637 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5638 	if (cands->len)
5639 		return cands;
5640 
5641 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5642 	if (obj->btf_vmlinux_override)
5643 		return cands;
5644 
5645 	/* now look through module BTFs, trying to still find candidates */
5646 	err = load_module_btfs(obj);
5647 	if (err)
5648 		goto err_out;
5649 
5650 	for (i = 0; i < obj->btf_module_cnt; i++) {
5651 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5652 					 obj->btf_modules[i].btf,
5653 					 obj->btf_modules[i].name,
5654 					 btf__type_cnt(obj->btf_vmlinux),
5655 					 cands);
5656 		if (err)
5657 			goto err_out;
5658 	}
5659 
5660 	return cands;
5661 err_out:
5662 	bpf_core_free_cands(cands);
5663 	return ERR_PTR(err);
5664 }
5665 
5666 /* Check local and target types for compatibility. This check is used for
5667  * type-based CO-RE relocations and follow slightly different rules than
5668  * field-based relocations. This function assumes that root types were already
5669  * checked for name match. Beyond that initial root-level name check, names
5670  * are completely ignored. Compatibility rules are as follows:
5671  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5672  *     kind should match for local and target types (i.e., STRUCT is not
5673  *     compatible with UNION);
5674  *   - for ENUMs, the size is ignored;
5675  *   - for INT, size and signedness are ignored;
5676  *   - for ARRAY, dimensionality is ignored, element types are checked for
5677  *     compatibility recursively;
5678  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5679  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5680  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5681  *     number of input args and compatible return and argument types.
5682  * These rules are not set in stone and probably will be adjusted as we get
5683  * more experience with using BPF CO-RE relocations.
5684  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5685 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5686 			      const struct btf *targ_btf, __u32 targ_id)
5687 {
5688 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5689 }
5690 
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5691 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5692 			 const struct btf *targ_btf, __u32 targ_id)
5693 {
5694 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5695 }
5696 
bpf_core_hash_fn(const long key,void * ctx)5697 static size_t bpf_core_hash_fn(const long key, void *ctx)
5698 {
5699 	return key;
5700 }
5701 
bpf_core_equal_fn(const long k1,const long k2,void * ctx)5702 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5703 {
5704 	return k1 == k2;
5705 }
5706 
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5707 static int record_relo_core(struct bpf_program *prog,
5708 			    const struct bpf_core_relo *core_relo, int insn_idx)
5709 {
5710 	struct reloc_desc *relos, *relo;
5711 
5712 	relos = libbpf_reallocarray(prog->reloc_desc,
5713 				    prog->nr_reloc + 1, sizeof(*relos));
5714 	if (!relos)
5715 		return -ENOMEM;
5716 	relo = &relos[prog->nr_reloc];
5717 	relo->type = RELO_CORE;
5718 	relo->insn_idx = insn_idx;
5719 	relo->core_relo = core_relo;
5720 	prog->reloc_desc = relos;
5721 	prog->nr_reloc++;
5722 	return 0;
5723 }
5724 
find_relo_core(struct bpf_program * prog,int insn_idx)5725 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5726 {
5727 	struct reloc_desc *relo;
5728 	int i;
5729 
5730 	for (i = 0; i < prog->nr_reloc; i++) {
5731 		relo = &prog->reloc_desc[i];
5732 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5733 			continue;
5734 
5735 		return relo->core_relo;
5736 	}
5737 
5738 	return NULL;
5739 }
5740 
bpf_core_resolve_relo(struct bpf_program * prog,const struct bpf_core_relo * relo,int relo_idx,const struct btf * local_btf,struct hashmap * cand_cache,struct bpf_core_relo_res * targ_res)5741 static int bpf_core_resolve_relo(struct bpf_program *prog,
5742 				 const struct bpf_core_relo *relo,
5743 				 int relo_idx,
5744 				 const struct btf *local_btf,
5745 				 struct hashmap *cand_cache,
5746 				 struct bpf_core_relo_res *targ_res)
5747 {
5748 	struct bpf_core_spec specs_scratch[3] = {};
5749 	struct bpf_core_cand_list *cands = NULL;
5750 	const char *prog_name = prog->name;
5751 	const struct btf_type *local_type;
5752 	const char *local_name;
5753 	__u32 local_id = relo->type_id;
5754 	int err;
5755 
5756 	local_type = btf__type_by_id(local_btf, local_id);
5757 	if (!local_type)
5758 		return -EINVAL;
5759 
5760 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5761 	if (!local_name)
5762 		return -EINVAL;
5763 
5764 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5765 	    !hashmap__find(cand_cache, local_id, &cands)) {
5766 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5767 		if (IS_ERR(cands)) {
5768 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5769 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5770 				local_name, PTR_ERR(cands));
5771 			return PTR_ERR(cands);
5772 		}
5773 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5774 		if (err) {
5775 			bpf_core_free_cands(cands);
5776 			return err;
5777 		}
5778 	}
5779 
5780 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5781 				       targ_res);
5782 }
5783 
5784 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5785 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5786 {
5787 	const struct btf_ext_info_sec *sec;
5788 	struct bpf_core_relo_res targ_res;
5789 	const struct bpf_core_relo *rec;
5790 	const struct btf_ext_info *seg;
5791 	struct hashmap_entry *entry;
5792 	struct hashmap *cand_cache = NULL;
5793 	struct bpf_program *prog;
5794 	struct bpf_insn *insn;
5795 	const char *sec_name;
5796 	int i, err = 0, insn_idx, sec_idx, sec_num;
5797 
5798 	if (obj->btf_ext->core_relo_info.len == 0)
5799 		return 0;
5800 
5801 	if (targ_btf_path) {
5802 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5803 		err = libbpf_get_error(obj->btf_vmlinux_override);
5804 		if (err) {
5805 			pr_warn("failed to parse target BTF: %d\n", err);
5806 			return err;
5807 		}
5808 	}
5809 
5810 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5811 	if (IS_ERR(cand_cache)) {
5812 		err = PTR_ERR(cand_cache);
5813 		goto out;
5814 	}
5815 
5816 	seg = &obj->btf_ext->core_relo_info;
5817 	sec_num = 0;
5818 	for_each_btf_ext_sec(seg, sec) {
5819 		sec_idx = seg->sec_idxs[sec_num];
5820 		sec_num++;
5821 
5822 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5823 		if (str_is_empty(sec_name)) {
5824 			err = -EINVAL;
5825 			goto out;
5826 		}
5827 
5828 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5829 
5830 		for_each_btf_ext_rec(seg, sec, i, rec) {
5831 			if (rec->insn_off % BPF_INSN_SZ)
5832 				return -EINVAL;
5833 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5834 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5835 			if (!prog) {
5836 				/* When __weak subprog is "overridden" by another instance
5837 				 * of the subprog from a different object file, linker still
5838 				 * appends all the .BTF.ext info that used to belong to that
5839 				 * eliminated subprogram.
5840 				 * This is similar to what x86-64 linker does for relocations.
5841 				 * So just ignore such relocations just like we ignore
5842 				 * subprog instructions when discovering subprograms.
5843 				 */
5844 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5845 					 sec_name, i, insn_idx);
5846 				continue;
5847 			}
5848 			/* no need to apply CO-RE relocation if the program is
5849 			 * not going to be loaded
5850 			 */
5851 			if (!prog->autoload)
5852 				continue;
5853 
5854 			/* adjust insn_idx from section frame of reference to the local
5855 			 * program's frame of reference; (sub-)program code is not yet
5856 			 * relocated, so it's enough to just subtract in-section offset
5857 			 */
5858 			insn_idx = insn_idx - prog->sec_insn_off;
5859 			if (insn_idx >= prog->insns_cnt)
5860 				return -EINVAL;
5861 			insn = &prog->insns[insn_idx];
5862 
5863 			err = record_relo_core(prog, rec, insn_idx);
5864 			if (err) {
5865 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5866 					prog->name, i, err);
5867 				goto out;
5868 			}
5869 
5870 			if (prog->obj->gen_loader)
5871 				continue;
5872 
5873 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5874 			if (err) {
5875 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5876 					prog->name, i, err);
5877 				goto out;
5878 			}
5879 
5880 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5881 			if (err) {
5882 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5883 					prog->name, i, insn_idx, err);
5884 				goto out;
5885 			}
5886 		}
5887 	}
5888 
5889 out:
5890 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5891 	btf__free(obj->btf_vmlinux_override);
5892 	obj->btf_vmlinux_override = NULL;
5893 
5894 	if (!IS_ERR_OR_NULL(cand_cache)) {
5895 		hashmap__for_each_entry(cand_cache, entry, i) {
5896 			bpf_core_free_cands(entry->pvalue);
5897 		}
5898 		hashmap__free(cand_cache);
5899 	}
5900 	return err;
5901 }
5902 
5903 /* base map load ldimm64 special constant, used also for log fixup logic */
5904 #define POISON_LDIMM64_MAP_BASE 2001000000
5905 #define POISON_LDIMM64_MAP_PFX "200100"
5906 
poison_map_ldimm64(struct bpf_program * prog,int relo_idx,int insn_idx,struct bpf_insn * insn,int map_idx,const struct bpf_map * map)5907 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5908 			       int insn_idx, struct bpf_insn *insn,
5909 			       int map_idx, const struct bpf_map *map)
5910 {
5911 	int i;
5912 
5913 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5914 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5915 
5916 	/* we turn single ldimm64 into two identical invalid calls */
5917 	for (i = 0; i < 2; i++) {
5918 		insn->code = BPF_JMP | BPF_CALL;
5919 		insn->dst_reg = 0;
5920 		insn->src_reg = 0;
5921 		insn->off = 0;
5922 		/* if this instruction is reachable (not a dead code),
5923 		 * verifier will complain with something like:
5924 		 * invalid func unknown#2001000123
5925 		 * where lower 123 is map index into obj->maps[] array
5926 		 */
5927 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5928 
5929 		insn++;
5930 	}
5931 }
5932 
5933 /* unresolved kfunc call special constant, used also for log fixup logic */
5934 #define POISON_CALL_KFUNC_BASE 2002000000
5935 #define POISON_CALL_KFUNC_PFX "2002"
5936 
poison_kfunc_call(struct bpf_program * prog,int relo_idx,int insn_idx,struct bpf_insn * insn,int ext_idx,const struct extern_desc * ext)5937 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5938 			      int insn_idx, struct bpf_insn *insn,
5939 			      int ext_idx, const struct extern_desc *ext)
5940 {
5941 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5942 		 prog->name, relo_idx, insn_idx, ext->name);
5943 
5944 	/* we turn kfunc call into invalid helper call with identifiable constant */
5945 	insn->code = BPF_JMP | BPF_CALL;
5946 	insn->dst_reg = 0;
5947 	insn->src_reg = 0;
5948 	insn->off = 0;
5949 	/* if this instruction is reachable (not a dead code),
5950 	 * verifier will complain with something like:
5951 	 * invalid func unknown#2001000123
5952 	 * where lower 123 is extern index into obj->externs[] array
5953 	 */
5954 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5955 }
5956 
5957 /* Relocate data references within program code:
5958  *  - map references;
5959  *  - global variable references;
5960  *  - extern references.
5961  */
5962 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)5963 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5964 {
5965 	int i;
5966 
5967 	for (i = 0; i < prog->nr_reloc; i++) {
5968 		struct reloc_desc *relo = &prog->reloc_desc[i];
5969 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5970 		const struct bpf_map *map;
5971 		struct extern_desc *ext;
5972 
5973 		switch (relo->type) {
5974 		case RELO_LD64:
5975 			map = &obj->maps[relo->map_idx];
5976 			if (obj->gen_loader) {
5977 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5978 				insn[0].imm = relo->map_idx;
5979 			} else if (map->autocreate) {
5980 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5981 				insn[0].imm = map->fd;
5982 			} else {
5983 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5984 						   relo->map_idx, map);
5985 			}
5986 			break;
5987 		case RELO_DATA:
5988 			map = &obj->maps[relo->map_idx];
5989 			insn[1].imm = insn[0].imm + relo->sym_off;
5990 			if (obj->gen_loader) {
5991 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5992 				insn[0].imm = relo->map_idx;
5993 			} else if (map->autocreate) {
5994 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5995 				insn[0].imm = map->fd;
5996 			} else {
5997 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5998 						   relo->map_idx, map);
5999 			}
6000 			break;
6001 		case RELO_EXTERN_LD64:
6002 			ext = &obj->externs[relo->ext_idx];
6003 			if (ext->type == EXT_KCFG) {
6004 				if (obj->gen_loader) {
6005 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6006 					insn[0].imm = obj->kconfig_map_idx;
6007 				} else {
6008 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6009 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6010 				}
6011 				insn[1].imm = ext->kcfg.data_off;
6012 			} else /* EXT_KSYM */ {
6013 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6014 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6015 					insn[0].imm = ext->ksym.kernel_btf_id;
6016 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6017 				} else { /* typeless ksyms or unresolved typed ksyms */
6018 					insn[0].imm = (__u32)ext->ksym.addr;
6019 					insn[1].imm = ext->ksym.addr >> 32;
6020 				}
6021 			}
6022 			break;
6023 		case RELO_EXTERN_CALL:
6024 			ext = &obj->externs[relo->ext_idx];
6025 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6026 			if (ext->is_set) {
6027 				insn[0].imm = ext->ksym.kernel_btf_id;
6028 				insn[0].off = ext->ksym.btf_fd_idx;
6029 			} else { /* unresolved weak kfunc call */
6030 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6031 						  relo->ext_idx, ext);
6032 			}
6033 			break;
6034 		case RELO_SUBPROG_ADDR:
6035 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6036 				pr_warn("prog '%s': relo #%d: bad insn\n",
6037 					prog->name, i);
6038 				return -EINVAL;
6039 			}
6040 			/* handled already */
6041 			break;
6042 		case RELO_CALL:
6043 			/* handled already */
6044 			break;
6045 		case RELO_CORE:
6046 			/* will be handled by bpf_program_record_relos() */
6047 			break;
6048 		default:
6049 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6050 				prog->name, i, relo->type);
6051 			return -EINVAL;
6052 		}
6053 	}
6054 
6055 	return 0;
6056 }
6057 
adjust_prog_btf_ext_info(const struct bpf_object * obj,const struct bpf_program * prog,const struct btf_ext_info * ext_info,void ** prog_info,__u32 * prog_rec_cnt,__u32 * prog_rec_sz)6058 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6059 				    const struct bpf_program *prog,
6060 				    const struct btf_ext_info *ext_info,
6061 				    void **prog_info, __u32 *prog_rec_cnt,
6062 				    __u32 *prog_rec_sz)
6063 {
6064 	void *copy_start = NULL, *copy_end = NULL;
6065 	void *rec, *rec_end, *new_prog_info;
6066 	const struct btf_ext_info_sec *sec;
6067 	size_t old_sz, new_sz;
6068 	int i, sec_num, sec_idx, off_adj;
6069 
6070 	sec_num = 0;
6071 	for_each_btf_ext_sec(ext_info, sec) {
6072 		sec_idx = ext_info->sec_idxs[sec_num];
6073 		sec_num++;
6074 		if (prog->sec_idx != sec_idx)
6075 			continue;
6076 
6077 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6078 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6079 
6080 			if (insn_off < prog->sec_insn_off)
6081 				continue;
6082 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6083 				break;
6084 
6085 			if (!copy_start)
6086 				copy_start = rec;
6087 			copy_end = rec + ext_info->rec_size;
6088 		}
6089 
6090 		if (!copy_start)
6091 			return -ENOENT;
6092 
6093 		/* append func/line info of a given (sub-)program to the main
6094 		 * program func/line info
6095 		 */
6096 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6097 		new_sz = old_sz + (copy_end - copy_start);
6098 		new_prog_info = realloc(*prog_info, new_sz);
6099 		if (!new_prog_info)
6100 			return -ENOMEM;
6101 		*prog_info = new_prog_info;
6102 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6103 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6104 
6105 		/* Kernel instruction offsets are in units of 8-byte
6106 		 * instructions, while .BTF.ext instruction offsets generated
6107 		 * by Clang are in units of bytes. So convert Clang offsets
6108 		 * into kernel offsets and adjust offset according to program
6109 		 * relocated position.
6110 		 */
6111 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6112 		rec = new_prog_info + old_sz;
6113 		rec_end = new_prog_info + new_sz;
6114 		for (; rec < rec_end; rec += ext_info->rec_size) {
6115 			__u32 *insn_off = rec;
6116 
6117 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6118 		}
6119 		*prog_rec_sz = ext_info->rec_size;
6120 		return 0;
6121 	}
6122 
6123 	return -ENOENT;
6124 }
6125 
6126 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6127 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6128 			      struct bpf_program *main_prog,
6129 			      const struct bpf_program *prog)
6130 {
6131 	int err;
6132 
6133 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6134 	 * supprot func/line info
6135 	 */
6136 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6137 		return 0;
6138 
6139 	/* only attempt func info relocation if main program's func_info
6140 	 * relocation was successful
6141 	 */
6142 	if (main_prog != prog && !main_prog->func_info)
6143 		goto line_info;
6144 
6145 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6146 				       &main_prog->func_info,
6147 				       &main_prog->func_info_cnt,
6148 				       &main_prog->func_info_rec_size);
6149 	if (err) {
6150 		if (err != -ENOENT) {
6151 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6152 				prog->name, err);
6153 			return err;
6154 		}
6155 		if (main_prog->func_info) {
6156 			/*
6157 			 * Some info has already been found but has problem
6158 			 * in the last btf_ext reloc. Must have to error out.
6159 			 */
6160 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6161 			return err;
6162 		}
6163 		/* Have problem loading the very first info. Ignore the rest. */
6164 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6165 			prog->name);
6166 	}
6167 
6168 line_info:
6169 	/* don't relocate line info if main program's relocation failed */
6170 	if (main_prog != prog && !main_prog->line_info)
6171 		return 0;
6172 
6173 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6174 				       &main_prog->line_info,
6175 				       &main_prog->line_info_cnt,
6176 				       &main_prog->line_info_rec_size);
6177 	if (err) {
6178 		if (err != -ENOENT) {
6179 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6180 				prog->name, err);
6181 			return err;
6182 		}
6183 		if (main_prog->line_info) {
6184 			/*
6185 			 * Some info has already been found but has problem
6186 			 * in the last btf_ext reloc. Must have to error out.
6187 			 */
6188 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6189 			return err;
6190 		}
6191 		/* Have problem loading the very first info. Ignore the rest. */
6192 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6193 			prog->name);
6194 	}
6195 	return 0;
6196 }
6197 
cmp_relo_by_insn_idx(const void * key,const void * elem)6198 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6199 {
6200 	size_t insn_idx = *(const size_t *)key;
6201 	const struct reloc_desc *relo = elem;
6202 
6203 	if (insn_idx == relo->insn_idx)
6204 		return 0;
6205 	return insn_idx < relo->insn_idx ? -1 : 1;
6206 }
6207 
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6208 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6209 {
6210 	if (!prog->nr_reloc)
6211 		return NULL;
6212 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6213 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6214 }
6215 
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6216 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6217 {
6218 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6219 	struct reloc_desc *relos;
6220 	int i;
6221 
6222 	if (main_prog == subprog)
6223 		return 0;
6224 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6225 	/* if new count is zero, reallocarray can return a valid NULL result;
6226 	 * in this case the previous pointer will be freed, so we *have to*
6227 	 * reassign old pointer to the new value (even if it's NULL)
6228 	 */
6229 	if (!relos && new_cnt)
6230 		return -ENOMEM;
6231 	if (subprog->nr_reloc)
6232 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6233 		       sizeof(*relos) * subprog->nr_reloc);
6234 
6235 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6236 		relos[i].insn_idx += subprog->sub_insn_off;
6237 	/* After insn_idx adjustment the 'relos' array is still sorted
6238 	 * by insn_idx and doesn't break bsearch.
6239 	 */
6240 	main_prog->reloc_desc = relos;
6241 	main_prog->nr_reloc = new_cnt;
6242 	return 0;
6243 }
6244 
6245 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6246 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6247 		       struct bpf_program *prog)
6248 {
6249 	size_t sub_insn_idx, insn_idx, new_cnt;
6250 	struct bpf_program *subprog;
6251 	struct bpf_insn *insns, *insn;
6252 	struct reloc_desc *relo;
6253 	int err;
6254 
6255 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6256 	if (err)
6257 		return err;
6258 
6259 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6260 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6261 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6262 			continue;
6263 
6264 		relo = find_prog_insn_relo(prog, insn_idx);
6265 		if (relo && relo->type == RELO_EXTERN_CALL)
6266 			/* kfunc relocations will be handled later
6267 			 * in bpf_object__relocate_data()
6268 			 */
6269 			continue;
6270 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6271 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6272 				prog->name, insn_idx, relo->type);
6273 			return -LIBBPF_ERRNO__RELOC;
6274 		}
6275 		if (relo) {
6276 			/* sub-program instruction index is a combination of
6277 			 * an offset of a symbol pointed to by relocation and
6278 			 * call instruction's imm field; for global functions,
6279 			 * call always has imm = -1, but for static functions
6280 			 * relocation is against STT_SECTION and insn->imm
6281 			 * points to a start of a static function
6282 			 *
6283 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6284 			 * the byte offset in the corresponding section.
6285 			 */
6286 			if (relo->type == RELO_CALL)
6287 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6288 			else
6289 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6290 		} else if (insn_is_pseudo_func(insn)) {
6291 			/*
6292 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6293 			 * functions are in the same section, so it shouldn't reach here.
6294 			 */
6295 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6296 				prog->name, insn_idx);
6297 			return -LIBBPF_ERRNO__RELOC;
6298 		} else {
6299 			/* if subprogram call is to a static function within
6300 			 * the same ELF section, there won't be any relocation
6301 			 * emitted, but it also means there is no additional
6302 			 * offset necessary, insns->imm is relative to
6303 			 * instruction's original position within the section
6304 			 */
6305 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6306 		}
6307 
6308 		/* we enforce that sub-programs should be in .text section */
6309 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6310 		if (!subprog) {
6311 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6312 				prog->name);
6313 			return -LIBBPF_ERRNO__RELOC;
6314 		}
6315 
6316 		/* if it's the first call instruction calling into this
6317 		 * subprogram (meaning this subprog hasn't been processed
6318 		 * yet) within the context of current main program:
6319 		 *   - append it at the end of main program's instructions blog;
6320 		 *   - process is recursively, while current program is put on hold;
6321 		 *   - if that subprogram calls some other not yet processes
6322 		 *   subprogram, same thing will happen recursively until
6323 		 *   there are no more unprocesses subprograms left to append
6324 		 *   and relocate.
6325 		 */
6326 		if (subprog->sub_insn_off == 0) {
6327 			subprog->sub_insn_off = main_prog->insns_cnt;
6328 
6329 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6330 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6331 			if (!insns) {
6332 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6333 				return -ENOMEM;
6334 			}
6335 			main_prog->insns = insns;
6336 			main_prog->insns_cnt = new_cnt;
6337 
6338 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6339 			       subprog->insns_cnt * sizeof(*insns));
6340 
6341 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6342 				 main_prog->name, subprog->insns_cnt, subprog->name);
6343 
6344 			/* The subprog insns are now appended. Append its relos too. */
6345 			err = append_subprog_relos(main_prog, subprog);
6346 			if (err)
6347 				return err;
6348 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6349 			if (err)
6350 				return err;
6351 		}
6352 
6353 		/* main_prog->insns memory could have been re-allocated, so
6354 		 * calculate pointer again
6355 		 */
6356 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6357 		/* calculate correct instruction position within current main
6358 		 * prog; each main prog can have a different set of
6359 		 * subprograms appended (potentially in different order as
6360 		 * well), so position of any subprog can be different for
6361 		 * different main programs
6362 		 */
6363 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6364 
6365 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6366 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6367 	}
6368 
6369 	return 0;
6370 }
6371 
6372 /*
6373  * Relocate sub-program calls.
6374  *
6375  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6376  * main prog) is processed separately. For each subprog (non-entry functions,
6377  * that can be called from either entry progs or other subprogs) gets their
6378  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6379  * hasn't been yet appended and relocated within current main prog. Once its
6380  * relocated, sub_insn_off will point at the position within current main prog
6381  * where given subprog was appended. This will further be used to relocate all
6382  * the call instructions jumping into this subprog.
6383  *
6384  * We start with main program and process all call instructions. If the call
6385  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6386  * is zero), subprog instructions are appended at the end of main program's
6387  * instruction array. Then main program is "put on hold" while we recursively
6388  * process newly appended subprogram. If that subprogram calls into another
6389  * subprogram that hasn't been appended, new subprogram is appended again to
6390  * the *main* prog's instructions (subprog's instructions are always left
6391  * untouched, as they need to be in unmodified state for subsequent main progs
6392  * and subprog instructions are always sent only as part of a main prog) and
6393  * the process continues recursively. Once all the subprogs called from a main
6394  * prog or any of its subprogs are appended (and relocated), all their
6395  * positions within finalized instructions array are known, so it's easy to
6396  * rewrite call instructions with correct relative offsets, corresponding to
6397  * desired target subprog.
6398  *
6399  * Its important to realize that some subprogs might not be called from some
6400  * main prog and any of its called/used subprogs. Those will keep their
6401  * subprog->sub_insn_off as zero at all times and won't be appended to current
6402  * main prog and won't be relocated within the context of current main prog.
6403  * They might still be used from other main progs later.
6404  *
6405  * Visually this process can be shown as below. Suppose we have two main
6406  * programs mainA and mainB and BPF object contains three subprogs: subA,
6407  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6408  * subC both call subB:
6409  *
6410  *        +--------+ +-------+
6411  *        |        v v       |
6412  *     +--+---+ +--+-+-+ +---+--+
6413  *     | subA | | subB | | subC |
6414  *     +--+---+ +------+ +---+--+
6415  *        ^                  ^
6416  *        |                  |
6417  *    +---+-------+   +------+----+
6418  *    |   mainA   |   |   mainB   |
6419  *    +-----------+   +-----------+
6420  *
6421  * We'll start relocating mainA, will find subA, append it and start
6422  * processing sub A recursively:
6423  *
6424  *    +-----------+------+
6425  *    |   mainA   | subA |
6426  *    +-----------+------+
6427  *
6428  * At this point we notice that subB is used from subA, so we append it and
6429  * relocate (there are no further subcalls from subB):
6430  *
6431  *    +-----------+------+------+
6432  *    |   mainA   | subA | subB |
6433  *    +-----------+------+------+
6434  *
6435  * At this point, we relocate subA calls, then go one level up and finish with
6436  * relocatin mainA calls. mainA is done.
6437  *
6438  * For mainB process is similar but results in different order. We start with
6439  * mainB and skip subA and subB, as mainB never calls them (at least
6440  * directly), but we see subC is needed, so we append and start processing it:
6441  *
6442  *    +-----------+------+
6443  *    |   mainB   | subC |
6444  *    +-----------+------+
6445  * Now we see subC needs subB, so we go back to it, append and relocate it:
6446  *
6447  *    +-----------+------+------+
6448  *    |   mainB   | subC | subB |
6449  *    +-----------+------+------+
6450  *
6451  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6452  */
6453 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6454 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6455 {
6456 	struct bpf_program *subprog;
6457 	int i, err;
6458 
6459 	/* mark all subprogs as not relocated (yet) within the context of
6460 	 * current main program
6461 	 */
6462 	for (i = 0; i < obj->nr_programs; i++) {
6463 		subprog = &obj->programs[i];
6464 		if (!prog_is_subprog(obj, subprog))
6465 			continue;
6466 
6467 		subprog->sub_insn_off = 0;
6468 	}
6469 
6470 	err = bpf_object__reloc_code(obj, prog, prog);
6471 	if (err)
6472 		return err;
6473 
6474 	return 0;
6475 }
6476 
6477 static void
bpf_object__free_relocs(struct bpf_object * obj)6478 bpf_object__free_relocs(struct bpf_object *obj)
6479 {
6480 	struct bpf_program *prog;
6481 	int i;
6482 
6483 	/* free up relocation descriptors */
6484 	for (i = 0; i < obj->nr_programs; i++) {
6485 		prog = &obj->programs[i];
6486 		zfree(&prog->reloc_desc);
6487 		prog->nr_reloc = 0;
6488 	}
6489 }
6490 
cmp_relocs(const void * _a,const void * _b)6491 static int cmp_relocs(const void *_a, const void *_b)
6492 {
6493 	const struct reloc_desc *a = _a;
6494 	const struct reloc_desc *b = _b;
6495 
6496 	if (a->insn_idx != b->insn_idx)
6497 		return a->insn_idx < b->insn_idx ? -1 : 1;
6498 
6499 	/* no two relocations should have the same insn_idx, but ... */
6500 	if (a->type != b->type)
6501 		return a->type < b->type ? -1 : 1;
6502 
6503 	return 0;
6504 }
6505 
bpf_object__sort_relos(struct bpf_object * obj)6506 static void bpf_object__sort_relos(struct bpf_object *obj)
6507 {
6508 	int i;
6509 
6510 	for (i = 0; i < obj->nr_programs; i++) {
6511 		struct bpf_program *p = &obj->programs[i];
6512 
6513 		if (!p->nr_reloc)
6514 			continue;
6515 
6516 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6517 	}
6518 }
6519 
6520 static int
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)6521 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6522 {
6523 	struct bpf_program *prog;
6524 	size_t i, j;
6525 	int err;
6526 
6527 	if (obj->btf_ext) {
6528 		err = bpf_object__relocate_core(obj, targ_btf_path);
6529 		if (err) {
6530 			pr_warn("failed to perform CO-RE relocations: %d\n",
6531 				err);
6532 			return err;
6533 		}
6534 		bpf_object__sort_relos(obj);
6535 	}
6536 
6537 	/* Before relocating calls pre-process relocations and mark
6538 	 * few ld_imm64 instructions that points to subprogs.
6539 	 * Otherwise bpf_object__reloc_code() later would have to consider
6540 	 * all ld_imm64 insns as relocation candidates. That would
6541 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6542 	 * would increase and most of them will fail to find a relo.
6543 	 */
6544 	for (i = 0; i < obj->nr_programs; i++) {
6545 		prog = &obj->programs[i];
6546 		for (j = 0; j < prog->nr_reloc; j++) {
6547 			struct reloc_desc *relo = &prog->reloc_desc[j];
6548 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6549 
6550 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6551 			if (relo->type == RELO_SUBPROG_ADDR)
6552 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6553 		}
6554 	}
6555 
6556 	/* relocate subprogram calls and append used subprograms to main
6557 	 * programs; each copy of subprogram code needs to be relocated
6558 	 * differently for each main program, because its code location might
6559 	 * have changed.
6560 	 * Append subprog relos to main programs to allow data relos to be
6561 	 * processed after text is completely relocated.
6562 	 */
6563 	for (i = 0; i < obj->nr_programs; i++) {
6564 		prog = &obj->programs[i];
6565 		/* sub-program's sub-calls are relocated within the context of
6566 		 * its main program only
6567 		 */
6568 		if (prog_is_subprog(obj, prog))
6569 			continue;
6570 		if (!prog->autoload)
6571 			continue;
6572 
6573 		err = bpf_object__relocate_calls(obj, prog);
6574 		if (err) {
6575 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6576 				prog->name, err);
6577 			return err;
6578 		}
6579 	}
6580 	/* Process data relos for main programs */
6581 	for (i = 0; i < obj->nr_programs; i++) {
6582 		prog = &obj->programs[i];
6583 		if (prog_is_subprog(obj, prog))
6584 			continue;
6585 		if (!prog->autoload)
6586 			continue;
6587 		err = bpf_object__relocate_data(obj, prog);
6588 		if (err) {
6589 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6590 				prog->name, err);
6591 			return err;
6592 		}
6593 	}
6594 
6595 	return 0;
6596 }
6597 
6598 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6599 					    Elf64_Shdr *shdr, Elf_Data *data);
6600 
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)6601 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6602 					 Elf64_Shdr *shdr, Elf_Data *data)
6603 {
6604 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6605 	int i, j, nrels, new_sz;
6606 	const struct btf_var_secinfo *vi = NULL;
6607 	const struct btf_type *sec, *var, *def;
6608 	struct bpf_map *map = NULL, *targ_map = NULL;
6609 	struct bpf_program *targ_prog = NULL;
6610 	bool is_prog_array, is_map_in_map;
6611 	const struct btf_member *member;
6612 	const char *name, *mname, *type;
6613 	unsigned int moff;
6614 	Elf64_Sym *sym;
6615 	Elf64_Rel *rel;
6616 	void *tmp;
6617 
6618 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6619 		return -EINVAL;
6620 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6621 	if (!sec)
6622 		return -EINVAL;
6623 
6624 	nrels = shdr->sh_size / shdr->sh_entsize;
6625 	for (i = 0; i < nrels; i++) {
6626 		rel = elf_rel_by_idx(data, i);
6627 		if (!rel) {
6628 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6629 			return -LIBBPF_ERRNO__FORMAT;
6630 		}
6631 
6632 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6633 		if (!sym) {
6634 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6635 				i, (size_t)ELF64_R_SYM(rel->r_info));
6636 			return -LIBBPF_ERRNO__FORMAT;
6637 		}
6638 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6639 
6640 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6641 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6642 			 (size_t)rel->r_offset, sym->st_name, name);
6643 
6644 		for (j = 0; j < obj->nr_maps; j++) {
6645 			map = &obj->maps[j];
6646 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6647 				continue;
6648 
6649 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6650 			if (vi->offset <= rel->r_offset &&
6651 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6652 				break;
6653 		}
6654 		if (j == obj->nr_maps) {
6655 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6656 				i, name, (size_t)rel->r_offset);
6657 			return -EINVAL;
6658 		}
6659 
6660 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6661 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6662 		type = is_map_in_map ? "map" : "prog";
6663 		if (is_map_in_map) {
6664 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6665 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6666 					i, name);
6667 				return -LIBBPF_ERRNO__RELOC;
6668 			}
6669 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6670 			    map->def.key_size != sizeof(int)) {
6671 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6672 					i, map->name, sizeof(int));
6673 				return -EINVAL;
6674 			}
6675 			targ_map = bpf_object__find_map_by_name(obj, name);
6676 			if (!targ_map) {
6677 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6678 					i, name);
6679 				return -ESRCH;
6680 			}
6681 		} else if (is_prog_array) {
6682 			targ_prog = bpf_object__find_program_by_name(obj, name);
6683 			if (!targ_prog) {
6684 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6685 					i, name);
6686 				return -ESRCH;
6687 			}
6688 			if (targ_prog->sec_idx != sym->st_shndx ||
6689 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6690 			    prog_is_subprog(obj, targ_prog)) {
6691 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6692 					i, name);
6693 				return -LIBBPF_ERRNO__RELOC;
6694 			}
6695 		} else {
6696 			return -EINVAL;
6697 		}
6698 
6699 		var = btf__type_by_id(obj->btf, vi->type);
6700 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6701 		if (btf_vlen(def) == 0)
6702 			return -EINVAL;
6703 		member = btf_members(def) + btf_vlen(def) - 1;
6704 		mname = btf__name_by_offset(obj->btf, member->name_off);
6705 		if (strcmp(mname, "values"))
6706 			return -EINVAL;
6707 
6708 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6709 		if (rel->r_offset - vi->offset < moff)
6710 			return -EINVAL;
6711 
6712 		moff = rel->r_offset - vi->offset - moff;
6713 		/* here we use BPF pointer size, which is always 64 bit, as we
6714 		 * are parsing ELF that was built for BPF target
6715 		 */
6716 		if (moff % bpf_ptr_sz)
6717 			return -EINVAL;
6718 		moff /= bpf_ptr_sz;
6719 		if (moff >= map->init_slots_sz) {
6720 			new_sz = moff + 1;
6721 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6722 			if (!tmp)
6723 				return -ENOMEM;
6724 			map->init_slots = tmp;
6725 			memset(map->init_slots + map->init_slots_sz, 0,
6726 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6727 			map->init_slots_sz = new_sz;
6728 		}
6729 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6730 
6731 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6732 			 i, map->name, moff, type, name);
6733 	}
6734 
6735 	return 0;
6736 }
6737 
bpf_object__collect_relos(struct bpf_object * obj)6738 static int bpf_object__collect_relos(struct bpf_object *obj)
6739 {
6740 	int i, err;
6741 
6742 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6743 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6744 		Elf64_Shdr *shdr;
6745 		Elf_Data *data;
6746 		int idx;
6747 
6748 		if (sec_desc->sec_type != SEC_RELO)
6749 			continue;
6750 
6751 		shdr = sec_desc->shdr;
6752 		data = sec_desc->data;
6753 		idx = shdr->sh_info;
6754 
6755 		if (shdr->sh_type != SHT_REL) {
6756 			pr_warn("internal error at %d\n", __LINE__);
6757 			return -LIBBPF_ERRNO__INTERNAL;
6758 		}
6759 
6760 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6761 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6762 		else if (idx == obj->efile.btf_maps_shndx)
6763 			err = bpf_object__collect_map_relos(obj, shdr, data);
6764 		else
6765 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6766 		if (err)
6767 			return err;
6768 	}
6769 
6770 	bpf_object__sort_relos(obj);
6771 	return 0;
6772 }
6773 
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)6774 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6775 {
6776 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6777 	    BPF_OP(insn->code) == BPF_CALL &&
6778 	    BPF_SRC(insn->code) == BPF_K &&
6779 	    insn->src_reg == 0 &&
6780 	    insn->dst_reg == 0) {
6781 		    *func_id = insn->imm;
6782 		    return true;
6783 	}
6784 	return false;
6785 }
6786 
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)6787 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6788 {
6789 	struct bpf_insn *insn = prog->insns;
6790 	enum bpf_func_id func_id;
6791 	int i;
6792 
6793 	if (obj->gen_loader)
6794 		return 0;
6795 
6796 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6797 		if (!insn_is_helper_call(insn, &func_id))
6798 			continue;
6799 
6800 		/* on kernels that don't yet support
6801 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6802 		 * to bpf_probe_read() which works well for old kernels
6803 		 */
6804 		switch (func_id) {
6805 		case BPF_FUNC_probe_read_kernel:
6806 		case BPF_FUNC_probe_read_user:
6807 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6808 				insn->imm = BPF_FUNC_probe_read;
6809 			break;
6810 		case BPF_FUNC_probe_read_kernel_str:
6811 		case BPF_FUNC_probe_read_user_str:
6812 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6813 				insn->imm = BPF_FUNC_probe_read_str;
6814 			break;
6815 		default:
6816 			break;
6817 		}
6818 	}
6819 	return 0;
6820 }
6821 
6822 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6823 				     int *btf_obj_fd, int *btf_type_id);
6824 
6825 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
libbpf_prepare_prog_load(struct bpf_program * prog,struct bpf_prog_load_opts * opts,long cookie)6826 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6827 				    struct bpf_prog_load_opts *opts, long cookie)
6828 {
6829 	enum sec_def_flags def = cookie;
6830 
6831 	/* old kernels might not support specifying expected_attach_type */
6832 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6833 		opts->expected_attach_type = 0;
6834 
6835 	if (def & SEC_SLEEPABLE)
6836 		opts->prog_flags |= BPF_F_SLEEPABLE;
6837 
6838 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6839 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6840 
6841 	/* special check for usdt to use uprobe_multi link */
6842 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
6843 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
6844 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
6845 		 * update both.
6846 		 */
6847 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6848 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6849 	}
6850 
6851 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6852 		int btf_obj_fd = 0, btf_type_id = 0, err;
6853 		const char *attach_name;
6854 
6855 		attach_name = strchr(prog->sec_name, '/');
6856 		if (!attach_name) {
6857 			/* if BPF program is annotated with just SEC("fentry")
6858 			 * (or similar) without declaratively specifying
6859 			 * target, then it is expected that target will be
6860 			 * specified with bpf_program__set_attach_target() at
6861 			 * runtime before BPF object load step. If not, then
6862 			 * there is nothing to load into the kernel as BPF
6863 			 * verifier won't be able to validate BPF program
6864 			 * correctness anyways.
6865 			 */
6866 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6867 				prog->name);
6868 			return -EINVAL;
6869 		}
6870 		attach_name++; /* skip over / */
6871 
6872 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6873 		if (err)
6874 			return err;
6875 
6876 		/* cache resolved BTF FD and BTF type ID in the prog */
6877 		prog->attach_btf_obj_fd = btf_obj_fd;
6878 		prog->attach_btf_id = btf_type_id;
6879 
6880 		/* but by now libbpf common logic is not utilizing
6881 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6882 		 * this callback is called after opts were populated by
6883 		 * libbpf, so this callback has to update opts explicitly here
6884 		 */
6885 		opts->attach_btf_obj_fd = btf_obj_fd;
6886 		opts->attach_btf_id = btf_type_id;
6887 	}
6888 	return 0;
6889 }
6890 
6891 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6892 
bpf_object_load_prog(struct bpf_object * obj,struct bpf_program * prog,struct bpf_insn * insns,int insns_cnt,const char * license,__u32 kern_version,int * prog_fd)6893 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6894 				struct bpf_insn *insns, int insns_cnt,
6895 				const char *license, __u32 kern_version, int *prog_fd)
6896 {
6897 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6898 	const char *prog_name = NULL;
6899 	char *cp, errmsg[STRERR_BUFSIZE];
6900 	size_t log_buf_size = 0;
6901 	char *log_buf = NULL, *tmp;
6902 	int btf_fd, ret, err;
6903 	bool own_log_buf = true;
6904 	__u32 log_level = prog->log_level;
6905 
6906 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6907 		/*
6908 		 * The program type must be set.  Most likely we couldn't find a proper
6909 		 * section definition at load time, and thus we didn't infer the type.
6910 		 */
6911 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6912 			prog->name, prog->sec_name);
6913 		return -EINVAL;
6914 	}
6915 
6916 	if (!insns || !insns_cnt)
6917 		return -EINVAL;
6918 
6919 	if (kernel_supports(obj, FEAT_PROG_NAME))
6920 		prog_name = prog->name;
6921 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6922 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6923 	load_attr.attach_btf_id = prog->attach_btf_id;
6924 	load_attr.kern_version = kern_version;
6925 	load_attr.prog_ifindex = prog->prog_ifindex;
6926 	load_attr.expected_attach_type = prog->expected_attach_type;
6927 
6928 	/* specify func_info/line_info only if kernel supports them */
6929 	btf_fd = bpf_object__btf_fd(obj);
6930 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6931 		load_attr.prog_btf_fd = btf_fd;
6932 		load_attr.func_info = prog->func_info;
6933 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6934 		load_attr.func_info_cnt = prog->func_info_cnt;
6935 		load_attr.line_info = prog->line_info;
6936 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6937 		load_attr.line_info_cnt = prog->line_info_cnt;
6938 	}
6939 	load_attr.log_level = log_level;
6940 	load_attr.prog_flags = prog->prog_flags;
6941 	load_attr.fd_array = obj->fd_array;
6942 
6943 	/* adjust load_attr if sec_def provides custom preload callback */
6944 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6945 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6946 		if (err < 0) {
6947 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6948 				prog->name, err);
6949 			return err;
6950 		}
6951 		insns = prog->insns;
6952 		insns_cnt = prog->insns_cnt;
6953 	}
6954 
6955 	if (obj->gen_loader) {
6956 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6957 				   license, insns, insns_cnt, &load_attr,
6958 				   prog - obj->programs);
6959 		*prog_fd = -1;
6960 		return 0;
6961 	}
6962 
6963 retry_load:
6964 	/* if log_level is zero, we don't request logs initially even if
6965 	 * custom log_buf is specified; if the program load fails, then we'll
6966 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6967 	 * our own and retry the load to get details on what failed
6968 	 */
6969 	if (log_level) {
6970 		if (prog->log_buf) {
6971 			log_buf = prog->log_buf;
6972 			log_buf_size = prog->log_size;
6973 			own_log_buf = false;
6974 		} else if (obj->log_buf) {
6975 			log_buf = obj->log_buf;
6976 			log_buf_size = obj->log_size;
6977 			own_log_buf = false;
6978 		} else {
6979 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6980 			tmp = realloc(log_buf, log_buf_size);
6981 			if (!tmp) {
6982 				ret = -ENOMEM;
6983 				goto out;
6984 			}
6985 			log_buf = tmp;
6986 			log_buf[0] = '\0';
6987 			own_log_buf = true;
6988 		}
6989 	}
6990 
6991 	load_attr.log_buf = log_buf;
6992 	load_attr.log_size = log_buf_size;
6993 	load_attr.log_level = log_level;
6994 
6995 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6996 	if (ret >= 0) {
6997 		if (log_level && own_log_buf) {
6998 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6999 				 prog->name, log_buf);
7000 		}
7001 
7002 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7003 			struct bpf_map *map;
7004 			int i;
7005 
7006 			for (i = 0; i < obj->nr_maps; i++) {
7007 				map = &prog->obj->maps[i];
7008 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7009 					continue;
7010 
7011 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7012 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7013 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7014 						prog->name, map->real_name, cp);
7015 					/* Don't fail hard if can't bind rodata. */
7016 				}
7017 			}
7018 		}
7019 
7020 		*prog_fd = ret;
7021 		ret = 0;
7022 		goto out;
7023 	}
7024 
7025 	if (log_level == 0) {
7026 		log_level = 1;
7027 		goto retry_load;
7028 	}
7029 	/* On ENOSPC, increase log buffer size and retry, unless custom
7030 	 * log_buf is specified.
7031 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7032 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7033 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7034 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7035 	 */
7036 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7037 		goto retry_load;
7038 
7039 	ret = -errno;
7040 
7041 	/* post-process verifier log to improve error descriptions */
7042 	fixup_verifier_log(prog, log_buf, log_buf_size);
7043 
7044 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7045 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7046 	pr_perm_msg(ret);
7047 
7048 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7049 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7050 			prog->name, log_buf);
7051 	}
7052 
7053 out:
7054 	if (own_log_buf)
7055 		free(log_buf);
7056 	return ret;
7057 }
7058 
find_prev_line(char * buf,char * cur)7059 static char *find_prev_line(char *buf, char *cur)
7060 {
7061 	char *p;
7062 
7063 	if (cur == buf) /* end of a log buf */
7064 		return NULL;
7065 
7066 	p = cur - 1;
7067 	while (p - 1 >= buf && *(p - 1) != '\n')
7068 		p--;
7069 
7070 	return p;
7071 }
7072 
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)7073 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7074 		      char *orig, size_t orig_sz, const char *patch)
7075 {
7076 	/* size of the remaining log content to the right from the to-be-replaced part */
7077 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7078 	size_t patch_sz = strlen(patch);
7079 
7080 	if (patch_sz != orig_sz) {
7081 		/* If patch line(s) are longer than original piece of verifier log,
7082 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7083 		 * starting from after to-be-replaced part of the log.
7084 		 *
7085 		 * If patch line(s) are shorter than original piece of verifier log,
7086 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7087 		 * starting from after to-be-replaced part of the log
7088 		 *
7089 		 * We need to be careful about not overflowing available
7090 		 * buf_sz capacity. If that's the case, we'll truncate the end
7091 		 * of the original log, as necessary.
7092 		 */
7093 		if (patch_sz > orig_sz) {
7094 			if (orig + patch_sz >= buf + buf_sz) {
7095 				/* patch is big enough to cover remaining space completely */
7096 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7097 				rem_sz = 0;
7098 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7099 				/* patch causes part of remaining log to be truncated */
7100 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7101 			}
7102 		}
7103 		/* shift remaining log to the right by calculated amount */
7104 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7105 	}
7106 
7107 	memcpy(orig, patch, patch_sz);
7108 }
7109 
fixup_log_failed_core_relo(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7110 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7111 				       char *buf, size_t buf_sz, size_t log_sz,
7112 				       char *line1, char *line2, char *line3)
7113 {
7114 	/* Expected log for failed and not properly guarded CO-RE relocation:
7115 	 * line1 -> 123: (85) call unknown#195896080
7116 	 * line2 -> invalid func unknown#195896080
7117 	 * line3 -> <anything else or end of buffer>
7118 	 *
7119 	 * "123" is the index of the instruction that was poisoned. We extract
7120 	 * instruction index to find corresponding CO-RE relocation and
7121 	 * replace this part of the log with more relevant information about
7122 	 * failed CO-RE relocation.
7123 	 */
7124 	const struct bpf_core_relo *relo;
7125 	struct bpf_core_spec spec;
7126 	char patch[512], spec_buf[256];
7127 	int insn_idx, err, spec_len;
7128 
7129 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7130 		return;
7131 
7132 	relo = find_relo_core(prog, insn_idx);
7133 	if (!relo)
7134 		return;
7135 
7136 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7137 	if (err)
7138 		return;
7139 
7140 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7141 	snprintf(patch, sizeof(patch),
7142 		 "%d: <invalid CO-RE relocation>\n"
7143 		 "failed to resolve CO-RE relocation %s%s\n",
7144 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7145 
7146 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7147 }
7148 
fixup_log_missing_map_load(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7149 static void fixup_log_missing_map_load(struct bpf_program *prog,
7150 				       char *buf, size_t buf_sz, size_t log_sz,
7151 				       char *line1, char *line2, char *line3)
7152 {
7153 	/* Expected log for failed and not properly guarded map reference:
7154 	 * line1 -> 123: (85) call unknown#2001000345
7155 	 * line2 -> invalid func unknown#2001000345
7156 	 * line3 -> <anything else or end of buffer>
7157 	 *
7158 	 * "123" is the index of the instruction that was poisoned.
7159 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7160 	 */
7161 	struct bpf_object *obj = prog->obj;
7162 	const struct bpf_map *map;
7163 	int insn_idx, map_idx;
7164 	char patch[128];
7165 
7166 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7167 		return;
7168 
7169 	map_idx -= POISON_LDIMM64_MAP_BASE;
7170 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7171 		return;
7172 	map = &obj->maps[map_idx];
7173 
7174 	snprintf(patch, sizeof(patch),
7175 		 "%d: <invalid BPF map reference>\n"
7176 		 "BPF map '%s' is referenced but wasn't created\n",
7177 		 insn_idx, map->name);
7178 
7179 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7180 }
7181 
fixup_log_missing_kfunc_call(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7182 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7183 					 char *buf, size_t buf_sz, size_t log_sz,
7184 					 char *line1, char *line2, char *line3)
7185 {
7186 	/* Expected log for failed and not properly guarded kfunc call:
7187 	 * line1 -> 123: (85) call unknown#2002000345
7188 	 * line2 -> invalid func unknown#2002000345
7189 	 * line3 -> <anything else or end of buffer>
7190 	 *
7191 	 * "123" is the index of the instruction that was poisoned.
7192 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7193 	 */
7194 	struct bpf_object *obj = prog->obj;
7195 	const struct extern_desc *ext;
7196 	int insn_idx, ext_idx;
7197 	char patch[128];
7198 
7199 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7200 		return;
7201 
7202 	ext_idx -= POISON_CALL_KFUNC_BASE;
7203 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7204 		return;
7205 	ext = &obj->externs[ext_idx];
7206 
7207 	snprintf(patch, sizeof(patch),
7208 		 "%d: <invalid kfunc call>\n"
7209 		 "kfunc '%s' is referenced but wasn't resolved\n",
7210 		 insn_idx, ext->name);
7211 
7212 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7213 }
7214 
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7215 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7216 {
7217 	/* look for familiar error patterns in last N lines of the log */
7218 	const size_t max_last_line_cnt = 10;
7219 	char *prev_line, *cur_line, *next_line;
7220 	size_t log_sz;
7221 	int i;
7222 
7223 	if (!buf)
7224 		return;
7225 
7226 	log_sz = strlen(buf) + 1;
7227 	next_line = buf + log_sz - 1;
7228 
7229 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7230 		cur_line = find_prev_line(buf, next_line);
7231 		if (!cur_line)
7232 			return;
7233 
7234 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7235 			prev_line = find_prev_line(buf, cur_line);
7236 			if (!prev_line)
7237 				continue;
7238 
7239 			/* failed CO-RE relocation case */
7240 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7241 						   prev_line, cur_line, next_line);
7242 			return;
7243 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7244 			prev_line = find_prev_line(buf, cur_line);
7245 			if (!prev_line)
7246 				continue;
7247 
7248 			/* reference to uncreated BPF map */
7249 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7250 						   prev_line, cur_line, next_line);
7251 			return;
7252 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7253 			prev_line = find_prev_line(buf, cur_line);
7254 			if (!prev_line)
7255 				continue;
7256 
7257 			/* reference to unresolved kfunc */
7258 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7259 						     prev_line, cur_line, next_line);
7260 			return;
7261 		}
7262 	}
7263 }
7264 
bpf_program_record_relos(struct bpf_program * prog)7265 static int bpf_program_record_relos(struct bpf_program *prog)
7266 {
7267 	struct bpf_object *obj = prog->obj;
7268 	int i;
7269 
7270 	for (i = 0; i < prog->nr_reloc; i++) {
7271 		struct reloc_desc *relo = &prog->reloc_desc[i];
7272 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7273 		int kind;
7274 
7275 		switch (relo->type) {
7276 		case RELO_EXTERN_LD64:
7277 			if (ext->type != EXT_KSYM)
7278 				continue;
7279 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7280 				BTF_KIND_VAR : BTF_KIND_FUNC;
7281 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7282 					       ext->is_weak, !ext->ksym.type_id,
7283 					       true, kind, relo->insn_idx);
7284 			break;
7285 		case RELO_EXTERN_CALL:
7286 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7287 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7288 					       relo->insn_idx);
7289 			break;
7290 		case RELO_CORE: {
7291 			struct bpf_core_relo cr = {
7292 				.insn_off = relo->insn_idx * 8,
7293 				.type_id = relo->core_relo->type_id,
7294 				.access_str_off = relo->core_relo->access_str_off,
7295 				.kind = relo->core_relo->kind,
7296 			};
7297 
7298 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7299 			break;
7300 		}
7301 		default:
7302 			continue;
7303 		}
7304 	}
7305 	return 0;
7306 }
7307 
7308 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7309 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7310 {
7311 	struct bpf_program *prog;
7312 	size_t i;
7313 	int err;
7314 
7315 	for (i = 0; i < obj->nr_programs; i++) {
7316 		prog = &obj->programs[i];
7317 		err = bpf_object__sanitize_prog(obj, prog);
7318 		if (err)
7319 			return err;
7320 	}
7321 
7322 	for (i = 0; i < obj->nr_programs; i++) {
7323 		prog = &obj->programs[i];
7324 		if (prog_is_subprog(obj, prog))
7325 			continue;
7326 		if (!prog->autoload) {
7327 			pr_debug("prog '%s': skipped loading\n", prog->name);
7328 			continue;
7329 		}
7330 		prog->log_level |= log_level;
7331 
7332 		if (obj->gen_loader)
7333 			bpf_program_record_relos(prog);
7334 
7335 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7336 					   obj->license, obj->kern_version, &prog->fd);
7337 		if (err) {
7338 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7339 			return err;
7340 		}
7341 	}
7342 
7343 	bpf_object__free_relocs(obj);
7344 	return 0;
7345 }
7346 
7347 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7348 
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7349 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7350 {
7351 	struct bpf_program *prog;
7352 	int err;
7353 
7354 	bpf_object__for_each_program(prog, obj) {
7355 		prog->sec_def = find_sec_def(prog->sec_name);
7356 		if (!prog->sec_def) {
7357 			/* couldn't guess, but user might manually specify */
7358 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7359 				prog->name, prog->sec_name);
7360 			continue;
7361 		}
7362 
7363 		prog->type = prog->sec_def->prog_type;
7364 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7365 
7366 		/* sec_def can have custom callback which should be called
7367 		 * after bpf_program is initialized to adjust its properties
7368 		 */
7369 		if (prog->sec_def->prog_setup_fn) {
7370 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7371 			if (err < 0) {
7372 				pr_warn("prog '%s': failed to initialize: %d\n",
7373 					prog->name, err);
7374 				return err;
7375 			}
7376 		}
7377 	}
7378 
7379 	return 0;
7380 }
7381 
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7382 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7383 					  const struct bpf_object_open_opts *opts)
7384 {
7385 	const char *obj_name, *kconfig, *btf_tmp_path;
7386 	struct bpf_object *obj;
7387 	char tmp_name[64];
7388 	int err;
7389 	char *log_buf;
7390 	size_t log_size;
7391 	__u32 log_level;
7392 
7393 	if (elf_version(EV_CURRENT) == EV_NONE) {
7394 		pr_warn("failed to init libelf for %s\n",
7395 			path ? : "(mem buf)");
7396 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7397 	}
7398 
7399 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7400 		return ERR_PTR(-EINVAL);
7401 
7402 	obj_name = OPTS_GET(opts, object_name, NULL);
7403 	if (obj_buf) {
7404 		if (!obj_name) {
7405 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7406 				 (unsigned long)obj_buf,
7407 				 (unsigned long)obj_buf_sz);
7408 			obj_name = tmp_name;
7409 		}
7410 		path = obj_name;
7411 		pr_debug("loading object '%s' from buffer\n", obj_name);
7412 	}
7413 
7414 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7415 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7416 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7417 	if (log_size > UINT_MAX)
7418 		return ERR_PTR(-EINVAL);
7419 	if (log_size && !log_buf)
7420 		return ERR_PTR(-EINVAL);
7421 
7422 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7423 	if (IS_ERR(obj))
7424 		return obj;
7425 
7426 	obj->log_buf = log_buf;
7427 	obj->log_size = log_size;
7428 	obj->log_level = log_level;
7429 
7430 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7431 	if (btf_tmp_path) {
7432 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7433 			err = -ENAMETOOLONG;
7434 			goto out;
7435 		}
7436 		obj->btf_custom_path = strdup(btf_tmp_path);
7437 		if (!obj->btf_custom_path) {
7438 			err = -ENOMEM;
7439 			goto out;
7440 		}
7441 	}
7442 
7443 	kconfig = OPTS_GET(opts, kconfig, NULL);
7444 	if (kconfig) {
7445 		obj->kconfig = strdup(kconfig);
7446 		if (!obj->kconfig) {
7447 			err = -ENOMEM;
7448 			goto out;
7449 		}
7450 	}
7451 
7452 	err = bpf_object__elf_init(obj);
7453 	err = err ? : bpf_object__check_endianness(obj);
7454 	err = err ? : bpf_object__elf_collect(obj);
7455 	err = err ? : bpf_object__collect_externs(obj);
7456 	err = err ? : bpf_object_fixup_btf(obj);
7457 	err = err ? : bpf_object__init_maps(obj, opts);
7458 	err = err ? : bpf_object_init_progs(obj, opts);
7459 	err = err ? : bpf_object__collect_relos(obj);
7460 	if (err)
7461 		goto out;
7462 
7463 	bpf_object__elf_finish(obj);
7464 
7465 	return obj;
7466 out:
7467 	bpf_object__close(obj);
7468 	return ERR_PTR(err);
7469 }
7470 
7471 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)7472 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7473 {
7474 	if (!path)
7475 		return libbpf_err_ptr(-EINVAL);
7476 
7477 	pr_debug("loading %s\n", path);
7478 
7479 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7480 }
7481 
bpf_object__open(const char * path)7482 struct bpf_object *bpf_object__open(const char *path)
7483 {
7484 	return bpf_object__open_file(path, NULL);
7485 }
7486 
7487 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7488 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7489 		     const struct bpf_object_open_opts *opts)
7490 {
7491 	if (!obj_buf || obj_buf_sz == 0)
7492 		return libbpf_err_ptr(-EINVAL);
7493 
7494 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7495 }
7496 
bpf_object_unload(struct bpf_object * obj)7497 static int bpf_object_unload(struct bpf_object *obj)
7498 {
7499 	size_t i;
7500 
7501 	if (!obj)
7502 		return libbpf_err(-EINVAL);
7503 
7504 	for (i = 0; i < obj->nr_maps; i++) {
7505 		zclose(obj->maps[i].fd);
7506 		if (obj->maps[i].st_ops)
7507 			zfree(&obj->maps[i].st_ops->kern_vdata);
7508 	}
7509 
7510 	for (i = 0; i < obj->nr_programs; i++)
7511 		bpf_program__unload(&obj->programs[i]);
7512 
7513 	return 0;
7514 }
7515 
bpf_object__sanitize_maps(struct bpf_object * obj)7516 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7517 {
7518 	struct bpf_map *m;
7519 
7520 	bpf_object__for_each_map(m, obj) {
7521 		if (!bpf_map__is_internal(m))
7522 			continue;
7523 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7524 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7525 	}
7526 
7527 	return 0;
7528 }
7529 
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)7530 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7531 {
7532 	char sym_type, sym_name[500];
7533 	unsigned long long sym_addr;
7534 	int ret, err = 0;
7535 	FILE *f;
7536 
7537 	f = fopen("/proc/kallsyms", "re");
7538 	if (!f) {
7539 		err = -errno;
7540 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7541 		return err;
7542 	}
7543 
7544 	while (true) {
7545 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7546 			     &sym_addr, &sym_type, sym_name);
7547 		if (ret == EOF && feof(f))
7548 			break;
7549 		if (ret != 3) {
7550 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7551 			err = -EINVAL;
7552 			break;
7553 		}
7554 
7555 		err = cb(sym_addr, sym_type, sym_name, ctx);
7556 		if (err)
7557 			break;
7558 	}
7559 
7560 	fclose(f);
7561 	return err;
7562 }
7563 
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)7564 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7565 		       const char *sym_name, void *ctx)
7566 {
7567 	struct bpf_object *obj = ctx;
7568 	const struct btf_type *t;
7569 	struct extern_desc *ext;
7570 
7571 	ext = find_extern_by_name(obj, sym_name);
7572 	if (!ext || ext->type != EXT_KSYM)
7573 		return 0;
7574 
7575 	t = btf__type_by_id(obj->btf, ext->btf_id);
7576 	if (!btf_is_var(t))
7577 		return 0;
7578 
7579 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7580 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7581 			sym_name, ext->ksym.addr, sym_addr);
7582 		return -EINVAL;
7583 	}
7584 	if (!ext->is_set) {
7585 		ext->is_set = true;
7586 		ext->ksym.addr = sym_addr;
7587 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7588 	}
7589 	return 0;
7590 }
7591 
bpf_object__read_kallsyms_file(struct bpf_object * obj)7592 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7593 {
7594 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7595 }
7596 
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)7597 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7598 			    __u16 kind, struct btf **res_btf,
7599 			    struct module_btf **res_mod_btf)
7600 {
7601 	struct module_btf *mod_btf;
7602 	struct btf *btf;
7603 	int i, id, err;
7604 
7605 	btf = obj->btf_vmlinux;
7606 	mod_btf = NULL;
7607 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7608 
7609 	if (id == -ENOENT) {
7610 		err = load_module_btfs(obj);
7611 		if (err)
7612 			return err;
7613 
7614 		for (i = 0; i < obj->btf_module_cnt; i++) {
7615 			/* we assume module_btf's BTF FD is always >0 */
7616 			mod_btf = &obj->btf_modules[i];
7617 			btf = mod_btf->btf;
7618 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7619 			if (id != -ENOENT)
7620 				break;
7621 		}
7622 	}
7623 	if (id <= 0)
7624 		return -ESRCH;
7625 
7626 	*res_btf = btf;
7627 	*res_mod_btf = mod_btf;
7628 	return id;
7629 }
7630 
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)7631 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7632 					       struct extern_desc *ext)
7633 {
7634 	const struct btf_type *targ_var, *targ_type;
7635 	__u32 targ_type_id, local_type_id;
7636 	struct module_btf *mod_btf = NULL;
7637 	const char *targ_var_name;
7638 	struct btf *btf = NULL;
7639 	int id, err;
7640 
7641 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7642 	if (id < 0) {
7643 		if (id == -ESRCH && ext->is_weak)
7644 			return 0;
7645 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7646 			ext->name);
7647 		return id;
7648 	}
7649 
7650 	/* find local type_id */
7651 	local_type_id = ext->ksym.type_id;
7652 
7653 	/* find target type_id */
7654 	targ_var = btf__type_by_id(btf, id);
7655 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7656 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7657 
7658 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7659 					btf, targ_type_id);
7660 	if (err <= 0) {
7661 		const struct btf_type *local_type;
7662 		const char *targ_name, *local_name;
7663 
7664 		local_type = btf__type_by_id(obj->btf, local_type_id);
7665 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7666 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7667 
7668 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7669 			ext->name, local_type_id,
7670 			btf_kind_str(local_type), local_name, targ_type_id,
7671 			btf_kind_str(targ_type), targ_name);
7672 		return -EINVAL;
7673 	}
7674 
7675 	ext->is_set = true;
7676 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7677 	ext->ksym.kernel_btf_id = id;
7678 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7679 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7680 
7681 	return 0;
7682 }
7683 
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)7684 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7685 						struct extern_desc *ext)
7686 {
7687 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7688 	struct module_btf *mod_btf = NULL;
7689 	const struct btf_type *kern_func;
7690 	struct btf *kern_btf = NULL;
7691 	int ret;
7692 
7693 	local_func_proto_id = ext->ksym.type_id;
7694 
7695 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7696 				    &mod_btf);
7697 	if (kfunc_id < 0) {
7698 		if (kfunc_id == -ESRCH && ext->is_weak)
7699 			return 0;
7700 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7701 			ext->name);
7702 		return kfunc_id;
7703 	}
7704 
7705 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7706 	kfunc_proto_id = kern_func->type;
7707 
7708 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7709 					kern_btf, kfunc_proto_id);
7710 	if (ret <= 0) {
7711 		if (ext->is_weak)
7712 			return 0;
7713 
7714 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7715 			ext->name, local_func_proto_id,
7716 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7717 		return -EINVAL;
7718 	}
7719 
7720 	/* set index for module BTF fd in fd_array, if unset */
7721 	if (mod_btf && !mod_btf->fd_array_idx) {
7722 		/* insn->off is s16 */
7723 		if (obj->fd_array_cnt == INT16_MAX) {
7724 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7725 				ext->name, mod_btf->fd_array_idx);
7726 			return -E2BIG;
7727 		}
7728 		/* Cannot use index 0 for module BTF fd */
7729 		if (!obj->fd_array_cnt)
7730 			obj->fd_array_cnt = 1;
7731 
7732 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7733 					obj->fd_array_cnt + 1);
7734 		if (ret)
7735 			return ret;
7736 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7737 		/* we assume module BTF FD is always >0 */
7738 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7739 	}
7740 
7741 	ext->is_set = true;
7742 	ext->ksym.kernel_btf_id = kfunc_id;
7743 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7744 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7745 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7746 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7747 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7748 	 */
7749 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7750 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7751 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7752 
7753 	return 0;
7754 }
7755 
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)7756 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7757 {
7758 	const struct btf_type *t;
7759 	struct extern_desc *ext;
7760 	int i, err;
7761 
7762 	for (i = 0; i < obj->nr_extern; i++) {
7763 		ext = &obj->externs[i];
7764 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7765 			continue;
7766 
7767 		if (obj->gen_loader) {
7768 			ext->is_set = true;
7769 			ext->ksym.kernel_btf_obj_fd = 0;
7770 			ext->ksym.kernel_btf_id = 0;
7771 			continue;
7772 		}
7773 		t = btf__type_by_id(obj->btf, ext->btf_id);
7774 		if (btf_is_var(t))
7775 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7776 		else
7777 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7778 		if (err)
7779 			return err;
7780 	}
7781 	return 0;
7782 }
7783 
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)7784 static int bpf_object__resolve_externs(struct bpf_object *obj,
7785 				       const char *extra_kconfig)
7786 {
7787 	bool need_config = false, need_kallsyms = false;
7788 	bool need_vmlinux_btf = false;
7789 	struct extern_desc *ext;
7790 	void *kcfg_data = NULL;
7791 	int err, i;
7792 
7793 	if (obj->nr_extern == 0)
7794 		return 0;
7795 
7796 	if (obj->kconfig_map_idx >= 0)
7797 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7798 
7799 	for (i = 0; i < obj->nr_extern; i++) {
7800 		ext = &obj->externs[i];
7801 
7802 		if (ext->type == EXT_KSYM) {
7803 			if (ext->ksym.type_id)
7804 				need_vmlinux_btf = true;
7805 			else
7806 				need_kallsyms = true;
7807 			continue;
7808 		} else if (ext->type == EXT_KCFG) {
7809 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7810 			__u64 value = 0;
7811 
7812 			/* Kconfig externs need actual /proc/config.gz */
7813 			if (str_has_pfx(ext->name, "CONFIG_")) {
7814 				need_config = true;
7815 				continue;
7816 			}
7817 
7818 			/* Virtual kcfg externs are customly handled by libbpf */
7819 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7820 				value = get_kernel_version();
7821 				if (!value) {
7822 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7823 					return -EINVAL;
7824 				}
7825 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7826 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7827 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7828 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7829 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7830 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7831 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7832 				 * customly by libbpf (their values don't come from Kconfig).
7833 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7834 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7835 				 * externs.
7836 				 */
7837 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7838 				return -EINVAL;
7839 			}
7840 
7841 			err = set_kcfg_value_num(ext, ext_ptr, value);
7842 			if (err)
7843 				return err;
7844 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7845 				 ext->name, (long long)value);
7846 		} else {
7847 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7848 			return -EINVAL;
7849 		}
7850 	}
7851 	if (need_config && extra_kconfig) {
7852 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7853 		if (err)
7854 			return -EINVAL;
7855 		need_config = false;
7856 		for (i = 0; i < obj->nr_extern; i++) {
7857 			ext = &obj->externs[i];
7858 			if (ext->type == EXT_KCFG && !ext->is_set) {
7859 				need_config = true;
7860 				break;
7861 			}
7862 		}
7863 	}
7864 	if (need_config) {
7865 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7866 		if (err)
7867 			return -EINVAL;
7868 	}
7869 	if (need_kallsyms) {
7870 		err = bpf_object__read_kallsyms_file(obj);
7871 		if (err)
7872 			return -EINVAL;
7873 	}
7874 	if (need_vmlinux_btf) {
7875 		err = bpf_object__resolve_ksyms_btf_id(obj);
7876 		if (err)
7877 			return -EINVAL;
7878 	}
7879 	for (i = 0; i < obj->nr_extern; i++) {
7880 		ext = &obj->externs[i];
7881 
7882 		if (!ext->is_set && !ext->is_weak) {
7883 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7884 			return -ESRCH;
7885 		} else if (!ext->is_set) {
7886 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7887 				 ext->name);
7888 		}
7889 	}
7890 
7891 	return 0;
7892 }
7893 
bpf_map_prepare_vdata(const struct bpf_map * map)7894 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7895 {
7896 	struct bpf_struct_ops *st_ops;
7897 	__u32 i;
7898 
7899 	st_ops = map->st_ops;
7900 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7901 		struct bpf_program *prog = st_ops->progs[i];
7902 		void *kern_data;
7903 		int prog_fd;
7904 
7905 		if (!prog)
7906 			continue;
7907 
7908 		prog_fd = bpf_program__fd(prog);
7909 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7910 		*(unsigned long *)kern_data = prog_fd;
7911 	}
7912 }
7913 
bpf_object_prepare_struct_ops(struct bpf_object * obj)7914 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7915 {
7916 	int i;
7917 
7918 	for (i = 0; i < obj->nr_maps; i++)
7919 		if (bpf_map__is_struct_ops(&obj->maps[i]))
7920 			bpf_map_prepare_vdata(&obj->maps[i]);
7921 
7922 	return 0;
7923 }
7924 
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)7925 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7926 {
7927 	int err, i;
7928 
7929 	if (!obj)
7930 		return libbpf_err(-EINVAL);
7931 
7932 	if (obj->loaded) {
7933 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7934 		return libbpf_err(-EINVAL);
7935 	}
7936 
7937 	if (obj->gen_loader)
7938 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7939 
7940 	err = bpf_object__probe_loading(obj);
7941 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7942 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7943 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7944 	err = err ? : bpf_object__sanitize_maps(obj);
7945 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7946 	err = err ? : bpf_object__create_maps(obj);
7947 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7948 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7949 	err = err ? : bpf_object_init_prog_arrays(obj);
7950 	err = err ? : bpf_object_prepare_struct_ops(obj);
7951 
7952 	if (obj->gen_loader) {
7953 		/* reset FDs */
7954 		if (obj->btf)
7955 			btf__set_fd(obj->btf, -1);
7956 		for (i = 0; i < obj->nr_maps; i++)
7957 			obj->maps[i].fd = -1;
7958 		if (!err)
7959 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7960 	}
7961 
7962 	/* clean up fd_array */
7963 	zfree(&obj->fd_array);
7964 
7965 	/* clean up module BTFs */
7966 	for (i = 0; i < obj->btf_module_cnt; i++) {
7967 		close(obj->btf_modules[i].fd);
7968 		btf__free(obj->btf_modules[i].btf);
7969 		free(obj->btf_modules[i].name);
7970 	}
7971 	free(obj->btf_modules);
7972 
7973 	/* clean up vmlinux BTF */
7974 	btf__free(obj->btf_vmlinux);
7975 	obj->btf_vmlinux = NULL;
7976 
7977 	obj->loaded = true; /* doesn't matter if successfully or not */
7978 
7979 	if (err)
7980 		goto out;
7981 
7982 	return 0;
7983 out:
7984 	/* unpin any maps that were auto-pinned during load */
7985 	for (i = 0; i < obj->nr_maps; i++)
7986 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7987 			bpf_map__unpin(&obj->maps[i], NULL);
7988 
7989 	bpf_object_unload(obj);
7990 	pr_warn("failed to load object '%s'\n", obj->path);
7991 	return libbpf_err(err);
7992 }
7993 
bpf_object__load(struct bpf_object * obj)7994 int bpf_object__load(struct bpf_object *obj)
7995 {
7996 	return bpf_object_load(obj, 0, NULL);
7997 }
7998 
make_parent_dir(const char * path)7999 static int make_parent_dir(const char *path)
8000 {
8001 	char *cp, errmsg[STRERR_BUFSIZE];
8002 	char *dname, *dir;
8003 	int err = 0;
8004 
8005 	dname = strdup(path);
8006 	if (dname == NULL)
8007 		return -ENOMEM;
8008 
8009 	dir = dirname(dname);
8010 	if (mkdir(dir, 0700) && errno != EEXIST)
8011 		err = -errno;
8012 
8013 	free(dname);
8014 	if (err) {
8015 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8016 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8017 	}
8018 	return err;
8019 }
8020 
check_path(const char * path)8021 static int check_path(const char *path)
8022 {
8023 	char *cp, errmsg[STRERR_BUFSIZE];
8024 	struct statfs st_fs;
8025 	char *dname, *dir;
8026 	int err = 0;
8027 
8028 	if (path == NULL)
8029 		return -EINVAL;
8030 
8031 	dname = strdup(path);
8032 	if (dname == NULL)
8033 		return -ENOMEM;
8034 
8035 	dir = dirname(dname);
8036 	if (statfs(dir, &st_fs)) {
8037 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8038 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8039 		err = -errno;
8040 	}
8041 	free(dname);
8042 
8043 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8044 		pr_warn("specified path %s is not on BPF FS\n", path);
8045 		err = -EINVAL;
8046 	}
8047 
8048 	return err;
8049 }
8050 
bpf_program__pin(struct bpf_program * prog,const char * path)8051 int bpf_program__pin(struct bpf_program *prog, const char *path)
8052 {
8053 	char *cp, errmsg[STRERR_BUFSIZE];
8054 	int err;
8055 
8056 	if (prog->fd < 0) {
8057 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8058 		return libbpf_err(-EINVAL);
8059 	}
8060 
8061 	err = make_parent_dir(path);
8062 	if (err)
8063 		return libbpf_err(err);
8064 
8065 	err = check_path(path);
8066 	if (err)
8067 		return libbpf_err(err);
8068 
8069 	if (bpf_obj_pin(prog->fd, path)) {
8070 		err = -errno;
8071 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8072 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8073 		return libbpf_err(err);
8074 	}
8075 
8076 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8077 	return 0;
8078 }
8079 
bpf_program__unpin(struct bpf_program * prog,const char * path)8080 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8081 {
8082 	int err;
8083 
8084 	if (prog->fd < 0) {
8085 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8086 		return libbpf_err(-EINVAL);
8087 	}
8088 
8089 	err = check_path(path);
8090 	if (err)
8091 		return libbpf_err(err);
8092 
8093 	err = unlink(path);
8094 	if (err)
8095 		return libbpf_err(-errno);
8096 
8097 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8098 	return 0;
8099 }
8100 
bpf_map__pin(struct bpf_map * map,const char * path)8101 int bpf_map__pin(struct bpf_map *map, const char *path)
8102 {
8103 	char *cp, errmsg[STRERR_BUFSIZE];
8104 	int err;
8105 
8106 	if (map == NULL) {
8107 		pr_warn("invalid map pointer\n");
8108 		return libbpf_err(-EINVAL);
8109 	}
8110 
8111 	if (map->pin_path) {
8112 		if (path && strcmp(path, map->pin_path)) {
8113 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8114 				bpf_map__name(map), map->pin_path, path);
8115 			return libbpf_err(-EINVAL);
8116 		} else if (map->pinned) {
8117 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8118 				 bpf_map__name(map), map->pin_path);
8119 			return 0;
8120 		}
8121 	} else {
8122 		if (!path) {
8123 			pr_warn("missing a path to pin map '%s' at\n",
8124 				bpf_map__name(map));
8125 			return libbpf_err(-EINVAL);
8126 		} else if (map->pinned) {
8127 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8128 			return libbpf_err(-EEXIST);
8129 		}
8130 
8131 		map->pin_path = strdup(path);
8132 		if (!map->pin_path) {
8133 			err = -errno;
8134 			goto out_err;
8135 		}
8136 	}
8137 
8138 	err = make_parent_dir(map->pin_path);
8139 	if (err)
8140 		return libbpf_err(err);
8141 
8142 	err = check_path(map->pin_path);
8143 	if (err)
8144 		return libbpf_err(err);
8145 
8146 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8147 		err = -errno;
8148 		goto out_err;
8149 	}
8150 
8151 	map->pinned = true;
8152 	pr_debug("pinned map '%s'\n", map->pin_path);
8153 
8154 	return 0;
8155 
8156 out_err:
8157 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8158 	pr_warn("failed to pin map: %s\n", cp);
8159 	return libbpf_err(err);
8160 }
8161 
bpf_map__unpin(struct bpf_map * map,const char * path)8162 int bpf_map__unpin(struct bpf_map *map, const char *path)
8163 {
8164 	int err;
8165 
8166 	if (map == NULL) {
8167 		pr_warn("invalid map pointer\n");
8168 		return libbpf_err(-EINVAL);
8169 	}
8170 
8171 	if (map->pin_path) {
8172 		if (path && strcmp(path, map->pin_path)) {
8173 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8174 				bpf_map__name(map), map->pin_path, path);
8175 			return libbpf_err(-EINVAL);
8176 		}
8177 		path = map->pin_path;
8178 	} else if (!path) {
8179 		pr_warn("no path to unpin map '%s' from\n",
8180 			bpf_map__name(map));
8181 		return libbpf_err(-EINVAL);
8182 	}
8183 
8184 	err = check_path(path);
8185 	if (err)
8186 		return libbpf_err(err);
8187 
8188 	err = unlink(path);
8189 	if (err != 0)
8190 		return libbpf_err(-errno);
8191 
8192 	map->pinned = false;
8193 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8194 
8195 	return 0;
8196 }
8197 
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8198 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8199 {
8200 	char *new = NULL;
8201 
8202 	if (path) {
8203 		new = strdup(path);
8204 		if (!new)
8205 			return libbpf_err(-errno);
8206 	}
8207 
8208 	free(map->pin_path);
8209 	map->pin_path = new;
8210 	return 0;
8211 }
8212 
8213 __alias(bpf_map__pin_path)
8214 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8215 
bpf_map__pin_path(const struct bpf_map * map)8216 const char *bpf_map__pin_path(const struct bpf_map *map)
8217 {
8218 	return map->pin_path;
8219 }
8220 
bpf_map__is_pinned(const struct bpf_map * map)8221 bool bpf_map__is_pinned(const struct bpf_map *map)
8222 {
8223 	return map->pinned;
8224 }
8225 
sanitize_pin_path(char * s)8226 static void sanitize_pin_path(char *s)
8227 {
8228 	/* bpffs disallows periods in path names */
8229 	while (*s) {
8230 		if (*s == '.')
8231 			*s = '_';
8232 		s++;
8233 	}
8234 }
8235 
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8236 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8237 {
8238 	struct bpf_map *map;
8239 	int err;
8240 
8241 	if (!obj)
8242 		return libbpf_err(-ENOENT);
8243 
8244 	if (!obj->loaded) {
8245 		pr_warn("object not yet loaded; load it first\n");
8246 		return libbpf_err(-ENOENT);
8247 	}
8248 
8249 	bpf_object__for_each_map(map, obj) {
8250 		char *pin_path = NULL;
8251 		char buf[PATH_MAX];
8252 
8253 		if (!map->autocreate)
8254 			continue;
8255 
8256 		if (path) {
8257 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8258 			if (err)
8259 				goto err_unpin_maps;
8260 			sanitize_pin_path(buf);
8261 			pin_path = buf;
8262 		} else if (!map->pin_path) {
8263 			continue;
8264 		}
8265 
8266 		err = bpf_map__pin(map, pin_path);
8267 		if (err)
8268 			goto err_unpin_maps;
8269 	}
8270 
8271 	return 0;
8272 
8273 err_unpin_maps:
8274 	while ((map = bpf_object__prev_map(obj, map))) {
8275 		if (!map->pin_path)
8276 			continue;
8277 
8278 		bpf_map__unpin(map, NULL);
8279 	}
8280 
8281 	return libbpf_err(err);
8282 }
8283 
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8284 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8285 {
8286 	struct bpf_map *map;
8287 	int err;
8288 
8289 	if (!obj)
8290 		return libbpf_err(-ENOENT);
8291 
8292 	bpf_object__for_each_map(map, obj) {
8293 		char *pin_path = NULL;
8294 		char buf[PATH_MAX];
8295 
8296 		if (path) {
8297 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8298 			if (err)
8299 				return libbpf_err(err);
8300 			sanitize_pin_path(buf);
8301 			pin_path = buf;
8302 		} else if (!map->pin_path) {
8303 			continue;
8304 		}
8305 
8306 		err = bpf_map__unpin(map, pin_path);
8307 		if (err)
8308 			return libbpf_err(err);
8309 	}
8310 
8311 	return 0;
8312 }
8313 
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8314 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8315 {
8316 	struct bpf_program *prog;
8317 	char buf[PATH_MAX];
8318 	int err;
8319 
8320 	if (!obj)
8321 		return libbpf_err(-ENOENT);
8322 
8323 	if (!obj->loaded) {
8324 		pr_warn("object not yet loaded; load it first\n");
8325 		return libbpf_err(-ENOENT);
8326 	}
8327 
8328 	bpf_object__for_each_program(prog, obj) {
8329 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8330 		if (err)
8331 			goto err_unpin_programs;
8332 
8333 		err = bpf_program__pin(prog, buf);
8334 		if (err)
8335 			goto err_unpin_programs;
8336 	}
8337 
8338 	return 0;
8339 
8340 err_unpin_programs:
8341 	while ((prog = bpf_object__prev_program(obj, prog))) {
8342 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8343 			continue;
8344 
8345 		bpf_program__unpin(prog, buf);
8346 	}
8347 
8348 	return libbpf_err(err);
8349 }
8350 
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)8351 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8352 {
8353 	struct bpf_program *prog;
8354 	int err;
8355 
8356 	if (!obj)
8357 		return libbpf_err(-ENOENT);
8358 
8359 	bpf_object__for_each_program(prog, obj) {
8360 		char buf[PATH_MAX];
8361 
8362 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8363 		if (err)
8364 			return libbpf_err(err);
8365 
8366 		err = bpf_program__unpin(prog, buf);
8367 		if (err)
8368 			return libbpf_err(err);
8369 	}
8370 
8371 	return 0;
8372 }
8373 
bpf_object__pin(struct bpf_object * obj,const char * path)8374 int bpf_object__pin(struct bpf_object *obj, const char *path)
8375 {
8376 	int err;
8377 
8378 	err = bpf_object__pin_maps(obj, path);
8379 	if (err)
8380 		return libbpf_err(err);
8381 
8382 	err = bpf_object__pin_programs(obj, path);
8383 	if (err) {
8384 		bpf_object__unpin_maps(obj, path);
8385 		return libbpf_err(err);
8386 	}
8387 
8388 	return 0;
8389 }
8390 
bpf_object__unpin(struct bpf_object * obj,const char * path)8391 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8392 {
8393 	int err;
8394 
8395 	err = bpf_object__unpin_programs(obj, path);
8396 	if (err)
8397 		return libbpf_err(err);
8398 
8399 	err = bpf_object__unpin_maps(obj, path);
8400 	if (err)
8401 		return libbpf_err(err);
8402 
8403 	return 0;
8404 }
8405 
bpf_map__destroy(struct bpf_map * map)8406 static void bpf_map__destroy(struct bpf_map *map)
8407 {
8408 	if (map->inner_map) {
8409 		bpf_map__destroy(map->inner_map);
8410 		zfree(&map->inner_map);
8411 	}
8412 
8413 	zfree(&map->init_slots);
8414 	map->init_slots_sz = 0;
8415 
8416 	if (map->mmaped) {
8417 		size_t mmap_sz;
8418 
8419 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8420 		munmap(map->mmaped, mmap_sz);
8421 		map->mmaped = NULL;
8422 	}
8423 
8424 	if (map->st_ops) {
8425 		zfree(&map->st_ops->data);
8426 		zfree(&map->st_ops->progs);
8427 		zfree(&map->st_ops->kern_func_off);
8428 		zfree(&map->st_ops);
8429 	}
8430 
8431 	zfree(&map->name);
8432 	zfree(&map->real_name);
8433 	zfree(&map->pin_path);
8434 
8435 	if (map->fd >= 0)
8436 		zclose(map->fd);
8437 }
8438 
bpf_object__close(struct bpf_object * obj)8439 void bpf_object__close(struct bpf_object *obj)
8440 {
8441 	size_t i;
8442 
8443 	if (IS_ERR_OR_NULL(obj))
8444 		return;
8445 
8446 	usdt_manager_free(obj->usdt_man);
8447 	obj->usdt_man = NULL;
8448 
8449 	bpf_gen__free(obj->gen_loader);
8450 	bpf_object__elf_finish(obj);
8451 	bpf_object_unload(obj);
8452 	btf__free(obj->btf);
8453 	btf__free(obj->btf_vmlinux);
8454 	btf_ext__free(obj->btf_ext);
8455 
8456 	for (i = 0; i < obj->nr_maps; i++)
8457 		bpf_map__destroy(&obj->maps[i]);
8458 
8459 	zfree(&obj->btf_custom_path);
8460 	zfree(&obj->kconfig);
8461 
8462 	for (i = 0; i < obj->nr_extern; i++) {
8463 		zfree(&obj->externs[i].name);
8464 		zfree(&obj->externs[i].essent_name);
8465 	}
8466 
8467 	zfree(&obj->externs);
8468 	obj->nr_extern = 0;
8469 
8470 	zfree(&obj->maps);
8471 	obj->nr_maps = 0;
8472 
8473 	if (obj->programs && obj->nr_programs) {
8474 		for (i = 0; i < obj->nr_programs; i++)
8475 			bpf_program__exit(&obj->programs[i]);
8476 	}
8477 	zfree(&obj->programs);
8478 
8479 	free(obj);
8480 }
8481 
bpf_object__name(const struct bpf_object * obj)8482 const char *bpf_object__name(const struct bpf_object *obj)
8483 {
8484 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8485 }
8486 
bpf_object__kversion(const struct bpf_object * obj)8487 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8488 {
8489 	return obj ? obj->kern_version : 0;
8490 }
8491 
bpf_object__btf(const struct bpf_object * obj)8492 struct btf *bpf_object__btf(const struct bpf_object *obj)
8493 {
8494 	return obj ? obj->btf : NULL;
8495 }
8496 
bpf_object__btf_fd(const struct bpf_object * obj)8497 int bpf_object__btf_fd(const struct bpf_object *obj)
8498 {
8499 	return obj->btf ? btf__fd(obj->btf) : -1;
8500 }
8501 
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)8502 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8503 {
8504 	if (obj->loaded)
8505 		return libbpf_err(-EINVAL);
8506 
8507 	obj->kern_version = kern_version;
8508 
8509 	return 0;
8510 }
8511 
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)8512 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8513 {
8514 	struct bpf_gen *gen;
8515 
8516 	if (!opts)
8517 		return -EFAULT;
8518 	if (!OPTS_VALID(opts, gen_loader_opts))
8519 		return -EINVAL;
8520 	gen = calloc(sizeof(*gen), 1);
8521 	if (!gen)
8522 		return -ENOMEM;
8523 	gen->opts = opts;
8524 	obj->gen_loader = gen;
8525 	return 0;
8526 }
8527 
8528 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)8529 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8530 		    bool forward)
8531 {
8532 	size_t nr_programs = obj->nr_programs;
8533 	ssize_t idx;
8534 
8535 	if (!nr_programs)
8536 		return NULL;
8537 
8538 	if (!p)
8539 		/* Iter from the beginning */
8540 		return forward ? &obj->programs[0] :
8541 			&obj->programs[nr_programs - 1];
8542 
8543 	if (p->obj != obj) {
8544 		pr_warn("error: program handler doesn't match object\n");
8545 		return errno = EINVAL, NULL;
8546 	}
8547 
8548 	idx = (p - obj->programs) + (forward ? 1 : -1);
8549 	if (idx >= obj->nr_programs || idx < 0)
8550 		return NULL;
8551 	return &obj->programs[idx];
8552 }
8553 
8554 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)8555 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8556 {
8557 	struct bpf_program *prog = prev;
8558 
8559 	do {
8560 		prog = __bpf_program__iter(prog, obj, true);
8561 	} while (prog && prog_is_subprog(obj, prog));
8562 
8563 	return prog;
8564 }
8565 
8566 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)8567 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8568 {
8569 	struct bpf_program *prog = next;
8570 
8571 	do {
8572 		prog = __bpf_program__iter(prog, obj, false);
8573 	} while (prog && prog_is_subprog(obj, prog));
8574 
8575 	return prog;
8576 }
8577 
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)8578 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8579 {
8580 	prog->prog_ifindex = ifindex;
8581 }
8582 
bpf_program__name(const struct bpf_program * prog)8583 const char *bpf_program__name(const struct bpf_program *prog)
8584 {
8585 	return prog->name;
8586 }
8587 
bpf_program__section_name(const struct bpf_program * prog)8588 const char *bpf_program__section_name(const struct bpf_program *prog)
8589 {
8590 	return prog->sec_name;
8591 }
8592 
bpf_program__autoload(const struct bpf_program * prog)8593 bool bpf_program__autoload(const struct bpf_program *prog)
8594 {
8595 	return prog->autoload;
8596 }
8597 
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)8598 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8599 {
8600 	if (prog->obj->loaded)
8601 		return libbpf_err(-EINVAL);
8602 
8603 	prog->autoload = autoload;
8604 	return 0;
8605 }
8606 
bpf_program__autoattach(const struct bpf_program * prog)8607 bool bpf_program__autoattach(const struct bpf_program *prog)
8608 {
8609 	return prog->autoattach;
8610 }
8611 
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)8612 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8613 {
8614 	prog->autoattach = autoattach;
8615 }
8616 
bpf_program__insns(const struct bpf_program * prog)8617 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8618 {
8619 	return prog->insns;
8620 }
8621 
bpf_program__insn_cnt(const struct bpf_program * prog)8622 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8623 {
8624 	return prog->insns_cnt;
8625 }
8626 
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)8627 int bpf_program__set_insns(struct bpf_program *prog,
8628 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8629 {
8630 	struct bpf_insn *insns;
8631 
8632 	if (prog->obj->loaded)
8633 		return -EBUSY;
8634 
8635 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8636 	/* NULL is a valid return from reallocarray if the new count is zero */
8637 	if (!insns && new_insn_cnt) {
8638 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8639 		return -ENOMEM;
8640 	}
8641 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8642 
8643 	prog->insns = insns;
8644 	prog->insns_cnt = new_insn_cnt;
8645 	return 0;
8646 }
8647 
bpf_program__fd(const struct bpf_program * prog)8648 int bpf_program__fd(const struct bpf_program *prog)
8649 {
8650 	if (!prog)
8651 		return libbpf_err(-EINVAL);
8652 
8653 	if (prog->fd < 0)
8654 		return libbpf_err(-ENOENT);
8655 
8656 	return prog->fd;
8657 }
8658 
8659 __alias(bpf_program__type)
8660 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8661 
bpf_program__type(const struct bpf_program * prog)8662 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8663 {
8664 	return prog->type;
8665 }
8666 
8667 static size_t custom_sec_def_cnt;
8668 static struct bpf_sec_def *custom_sec_defs;
8669 static struct bpf_sec_def custom_fallback_def;
8670 static bool has_custom_fallback_def;
8671 static int last_custom_sec_def_handler_id;
8672 
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)8673 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8674 {
8675 	if (prog->obj->loaded)
8676 		return libbpf_err(-EBUSY);
8677 
8678 	/* if type is not changed, do nothing */
8679 	if (prog->type == type)
8680 		return 0;
8681 
8682 	prog->type = type;
8683 
8684 	/* If a program type was changed, we need to reset associated SEC()
8685 	 * handler, as it will be invalid now. The only exception is a generic
8686 	 * fallback handler, which by definition is program type-agnostic and
8687 	 * is a catch-all custom handler, optionally set by the application,
8688 	 * so should be able to handle any type of BPF program.
8689 	 */
8690 	if (prog->sec_def != &custom_fallback_def)
8691 		prog->sec_def = NULL;
8692 	return 0;
8693 }
8694 
8695 __alias(bpf_program__expected_attach_type)
8696 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8697 
bpf_program__expected_attach_type(const struct bpf_program * prog)8698 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8699 {
8700 	return prog->expected_attach_type;
8701 }
8702 
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)8703 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8704 					   enum bpf_attach_type type)
8705 {
8706 	if (prog->obj->loaded)
8707 		return libbpf_err(-EBUSY);
8708 
8709 	prog->expected_attach_type = type;
8710 	return 0;
8711 }
8712 
bpf_program__flags(const struct bpf_program * prog)8713 __u32 bpf_program__flags(const struct bpf_program *prog)
8714 {
8715 	return prog->prog_flags;
8716 }
8717 
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)8718 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8719 {
8720 	if (prog->obj->loaded)
8721 		return libbpf_err(-EBUSY);
8722 
8723 	prog->prog_flags = flags;
8724 	return 0;
8725 }
8726 
bpf_program__log_level(const struct bpf_program * prog)8727 __u32 bpf_program__log_level(const struct bpf_program *prog)
8728 {
8729 	return prog->log_level;
8730 }
8731 
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)8732 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8733 {
8734 	if (prog->obj->loaded)
8735 		return libbpf_err(-EBUSY);
8736 
8737 	prog->log_level = log_level;
8738 	return 0;
8739 }
8740 
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)8741 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8742 {
8743 	*log_size = prog->log_size;
8744 	return prog->log_buf;
8745 }
8746 
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)8747 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8748 {
8749 	if (log_size && !log_buf)
8750 		return -EINVAL;
8751 	if (prog->log_size > UINT_MAX)
8752 		return -EINVAL;
8753 	if (prog->obj->loaded)
8754 		return -EBUSY;
8755 
8756 	prog->log_buf = log_buf;
8757 	prog->log_size = log_size;
8758 	return 0;
8759 }
8760 
8761 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8762 	.sec = (char *)sec_pfx,						    \
8763 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8764 	.expected_attach_type = atype,					    \
8765 	.cookie = (long)(flags),					    \
8766 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8767 	__VA_ARGS__							    \
8768 }
8769 
8770 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8771 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8772 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8773 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8774 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8775 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8776 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8777 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8778 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8779 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8780 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8781 
8782 static const struct bpf_sec_def section_defs[] = {
8783 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8784 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8785 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8786 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8787 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8788 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8789 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8790 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8791 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8792 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8793 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8794 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8795 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8796 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8797 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8798 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8799 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8800 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
8801 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8802 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8803 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8804 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8805 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8806 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8807 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8808 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8809 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8810 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8811 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8812 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8813 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8814 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8815 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8816 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8817 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8818 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8819 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8820 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8821 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8822 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8823 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8824 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8825 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8826 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8827 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8828 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8829 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8830 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8831 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8832 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8833 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8834 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8835 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8836 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8837 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8838 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8839 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8840 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8841 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8842 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8843 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8844 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8845 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8846 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8847 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8848 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8849 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8850 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8851 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8852 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8853 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8854 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8855 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8856 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8857 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8858 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8859 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8860 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8861 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8862 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8863 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8864 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8865 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8866 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8867 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8868 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8869 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8870 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8871 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8872 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8873 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8874 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8875 };
8876 
libbpf_register_prog_handler(const char * sec,enum bpf_prog_type prog_type,enum bpf_attach_type exp_attach_type,const struct libbpf_prog_handler_opts * opts)8877 int libbpf_register_prog_handler(const char *sec,
8878 				 enum bpf_prog_type prog_type,
8879 				 enum bpf_attach_type exp_attach_type,
8880 				 const struct libbpf_prog_handler_opts *opts)
8881 {
8882 	struct bpf_sec_def *sec_def;
8883 
8884 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8885 		return libbpf_err(-EINVAL);
8886 
8887 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8888 		return libbpf_err(-E2BIG);
8889 
8890 	if (sec) {
8891 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8892 					      sizeof(*sec_def));
8893 		if (!sec_def)
8894 			return libbpf_err(-ENOMEM);
8895 
8896 		custom_sec_defs = sec_def;
8897 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8898 	} else {
8899 		if (has_custom_fallback_def)
8900 			return libbpf_err(-EBUSY);
8901 
8902 		sec_def = &custom_fallback_def;
8903 	}
8904 
8905 	sec_def->sec = sec ? strdup(sec) : NULL;
8906 	if (sec && !sec_def->sec)
8907 		return libbpf_err(-ENOMEM);
8908 
8909 	sec_def->prog_type = prog_type;
8910 	sec_def->expected_attach_type = exp_attach_type;
8911 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8912 
8913 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8914 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8915 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8916 
8917 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8918 
8919 	if (sec)
8920 		custom_sec_def_cnt++;
8921 	else
8922 		has_custom_fallback_def = true;
8923 
8924 	return sec_def->handler_id;
8925 }
8926 
libbpf_unregister_prog_handler(int handler_id)8927 int libbpf_unregister_prog_handler(int handler_id)
8928 {
8929 	struct bpf_sec_def *sec_defs;
8930 	int i;
8931 
8932 	if (handler_id <= 0)
8933 		return libbpf_err(-EINVAL);
8934 
8935 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8936 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8937 		has_custom_fallback_def = false;
8938 		return 0;
8939 	}
8940 
8941 	for (i = 0; i < custom_sec_def_cnt; i++) {
8942 		if (custom_sec_defs[i].handler_id == handler_id)
8943 			break;
8944 	}
8945 
8946 	if (i == custom_sec_def_cnt)
8947 		return libbpf_err(-ENOENT);
8948 
8949 	free(custom_sec_defs[i].sec);
8950 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8951 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8952 	custom_sec_def_cnt--;
8953 
8954 	/* try to shrink the array, but it's ok if we couldn't */
8955 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8956 	/* if new count is zero, reallocarray can return a valid NULL result;
8957 	 * in this case the previous pointer will be freed, so we *have to*
8958 	 * reassign old pointer to the new value (even if it's NULL)
8959 	 */
8960 	if (sec_defs || custom_sec_def_cnt == 0)
8961 		custom_sec_defs = sec_defs;
8962 
8963 	return 0;
8964 }
8965 
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)8966 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8967 {
8968 	size_t len = strlen(sec_def->sec);
8969 
8970 	/* "type/" always has to have proper SEC("type/extras") form */
8971 	if (sec_def->sec[len - 1] == '/') {
8972 		if (str_has_pfx(sec_name, sec_def->sec))
8973 			return true;
8974 		return false;
8975 	}
8976 
8977 	/* "type+" means it can be either exact SEC("type") or
8978 	 * well-formed SEC("type/extras") with proper '/' separator
8979 	 */
8980 	if (sec_def->sec[len - 1] == '+') {
8981 		len--;
8982 		/* not even a prefix */
8983 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8984 			return false;
8985 		/* exact match or has '/' separator */
8986 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8987 			return true;
8988 		return false;
8989 	}
8990 
8991 	return strcmp(sec_name, sec_def->sec) == 0;
8992 }
8993 
find_sec_def(const char * sec_name)8994 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8995 {
8996 	const struct bpf_sec_def *sec_def;
8997 	int i, n;
8998 
8999 	n = custom_sec_def_cnt;
9000 	for (i = 0; i < n; i++) {
9001 		sec_def = &custom_sec_defs[i];
9002 		if (sec_def_matches(sec_def, sec_name))
9003 			return sec_def;
9004 	}
9005 
9006 	n = ARRAY_SIZE(section_defs);
9007 	for (i = 0; i < n; i++) {
9008 		sec_def = &section_defs[i];
9009 		if (sec_def_matches(sec_def, sec_name))
9010 			return sec_def;
9011 	}
9012 
9013 	if (has_custom_fallback_def)
9014 		return &custom_fallback_def;
9015 
9016 	return NULL;
9017 }
9018 
9019 #define MAX_TYPE_NAME_SIZE 32
9020 
libbpf_get_type_names(bool attach_type)9021 static char *libbpf_get_type_names(bool attach_type)
9022 {
9023 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9024 	char *buf;
9025 
9026 	buf = malloc(len);
9027 	if (!buf)
9028 		return NULL;
9029 
9030 	buf[0] = '\0';
9031 	/* Forge string buf with all available names */
9032 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9033 		const struct bpf_sec_def *sec_def = &section_defs[i];
9034 
9035 		if (attach_type) {
9036 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9037 				continue;
9038 
9039 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9040 				continue;
9041 		}
9042 
9043 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9044 			free(buf);
9045 			return NULL;
9046 		}
9047 		strcat(buf, " ");
9048 		strcat(buf, section_defs[i].sec);
9049 	}
9050 
9051 	return buf;
9052 }
9053 
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9054 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9055 			     enum bpf_attach_type *expected_attach_type)
9056 {
9057 	const struct bpf_sec_def *sec_def;
9058 	char *type_names;
9059 
9060 	if (!name)
9061 		return libbpf_err(-EINVAL);
9062 
9063 	sec_def = find_sec_def(name);
9064 	if (sec_def) {
9065 		*prog_type = sec_def->prog_type;
9066 		*expected_attach_type = sec_def->expected_attach_type;
9067 		return 0;
9068 	}
9069 
9070 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9071 	type_names = libbpf_get_type_names(false);
9072 	if (type_names != NULL) {
9073 		pr_debug("supported section(type) names are:%s\n", type_names);
9074 		free(type_names);
9075 	}
9076 
9077 	return libbpf_err(-ESRCH);
9078 }
9079 
libbpf_bpf_attach_type_str(enum bpf_attach_type t)9080 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9081 {
9082 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9083 		return NULL;
9084 
9085 	return attach_type_name[t];
9086 }
9087 
libbpf_bpf_link_type_str(enum bpf_link_type t)9088 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9089 {
9090 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9091 		return NULL;
9092 
9093 	return link_type_name[t];
9094 }
9095 
libbpf_bpf_map_type_str(enum bpf_map_type t)9096 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9097 {
9098 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9099 		return NULL;
9100 
9101 	return map_type_name[t];
9102 }
9103 
libbpf_bpf_prog_type_str(enum bpf_prog_type t)9104 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9105 {
9106 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9107 		return NULL;
9108 
9109 	return prog_type_name[t];
9110 }
9111 
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)9112 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9113 						     int sec_idx,
9114 						     size_t offset)
9115 {
9116 	struct bpf_map *map;
9117 	size_t i;
9118 
9119 	for (i = 0; i < obj->nr_maps; i++) {
9120 		map = &obj->maps[i];
9121 		if (!bpf_map__is_struct_ops(map))
9122 			continue;
9123 		if (map->sec_idx == sec_idx &&
9124 		    map->sec_offset <= offset &&
9125 		    offset - map->sec_offset < map->def.value_size)
9126 			return map;
9127 	}
9128 
9129 	return NULL;
9130 }
9131 
9132 /* Collect the reloc from ELF and populate the st_ops->progs[] */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)9133 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9134 					    Elf64_Shdr *shdr, Elf_Data *data)
9135 {
9136 	const struct btf_member *member;
9137 	struct bpf_struct_ops *st_ops;
9138 	struct bpf_program *prog;
9139 	unsigned int shdr_idx;
9140 	const struct btf *btf;
9141 	struct bpf_map *map;
9142 	unsigned int moff, insn_idx;
9143 	const char *name;
9144 	__u32 member_idx;
9145 	Elf64_Sym *sym;
9146 	Elf64_Rel *rel;
9147 	int i, nrels;
9148 
9149 	btf = obj->btf;
9150 	nrels = shdr->sh_size / shdr->sh_entsize;
9151 	for (i = 0; i < nrels; i++) {
9152 		rel = elf_rel_by_idx(data, i);
9153 		if (!rel) {
9154 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9155 			return -LIBBPF_ERRNO__FORMAT;
9156 		}
9157 
9158 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9159 		if (!sym) {
9160 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9161 				(size_t)ELF64_R_SYM(rel->r_info));
9162 			return -LIBBPF_ERRNO__FORMAT;
9163 		}
9164 
9165 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9166 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9167 		if (!map) {
9168 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9169 				(size_t)rel->r_offset);
9170 			return -EINVAL;
9171 		}
9172 
9173 		moff = rel->r_offset - map->sec_offset;
9174 		shdr_idx = sym->st_shndx;
9175 		st_ops = map->st_ops;
9176 		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",
9177 			 map->name,
9178 			 (long long)(rel->r_info >> 32),
9179 			 (long long)sym->st_value,
9180 			 shdr_idx, (size_t)rel->r_offset,
9181 			 map->sec_offset, sym->st_name, name);
9182 
9183 		if (shdr_idx >= SHN_LORESERVE) {
9184 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9185 				map->name, (size_t)rel->r_offset, shdr_idx);
9186 			return -LIBBPF_ERRNO__RELOC;
9187 		}
9188 		if (sym->st_value % BPF_INSN_SZ) {
9189 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9190 				map->name, (unsigned long long)sym->st_value);
9191 			return -LIBBPF_ERRNO__FORMAT;
9192 		}
9193 		insn_idx = sym->st_value / BPF_INSN_SZ;
9194 
9195 		member = find_member_by_offset(st_ops->type, moff * 8);
9196 		if (!member) {
9197 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9198 				map->name, moff);
9199 			return -EINVAL;
9200 		}
9201 		member_idx = member - btf_members(st_ops->type);
9202 		name = btf__name_by_offset(btf, member->name_off);
9203 
9204 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9205 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9206 				map->name, name);
9207 			return -EINVAL;
9208 		}
9209 
9210 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9211 		if (!prog) {
9212 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9213 				map->name, shdr_idx, name);
9214 			return -EINVAL;
9215 		}
9216 
9217 		/* prevent the use of BPF prog with invalid type */
9218 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9219 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9220 				map->name, prog->name);
9221 			return -EINVAL;
9222 		}
9223 
9224 		/* if we haven't yet processed this BPF program, record proper
9225 		 * attach_btf_id and member_idx
9226 		 */
9227 		if (!prog->attach_btf_id) {
9228 			prog->attach_btf_id = st_ops->type_id;
9229 			prog->expected_attach_type = member_idx;
9230 		}
9231 
9232 		/* struct_ops BPF prog can be re-used between multiple
9233 		 * .struct_ops & .struct_ops.link as long as it's the
9234 		 * same struct_ops struct definition and the same
9235 		 * function pointer field
9236 		 */
9237 		if (prog->attach_btf_id != st_ops->type_id ||
9238 		    prog->expected_attach_type != member_idx) {
9239 			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",
9240 				map->name, prog->name, prog->sec_name, prog->type,
9241 				prog->attach_btf_id, prog->expected_attach_type, name);
9242 			return -EINVAL;
9243 		}
9244 
9245 		st_ops->progs[member_idx] = prog;
9246 	}
9247 
9248 	return 0;
9249 }
9250 
9251 #define BTF_TRACE_PREFIX "btf_trace_"
9252 #define BTF_LSM_PREFIX "bpf_lsm_"
9253 #define BTF_ITER_PREFIX "bpf_iter_"
9254 #define BTF_MAX_NAME_SIZE 128
9255 
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9256 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9257 				const char **prefix, int *kind)
9258 {
9259 	switch (attach_type) {
9260 	case BPF_TRACE_RAW_TP:
9261 		*prefix = BTF_TRACE_PREFIX;
9262 		*kind = BTF_KIND_TYPEDEF;
9263 		break;
9264 	case BPF_LSM_MAC:
9265 	case BPF_LSM_CGROUP:
9266 		*prefix = BTF_LSM_PREFIX;
9267 		*kind = BTF_KIND_FUNC;
9268 		break;
9269 	case BPF_TRACE_ITER:
9270 		*prefix = BTF_ITER_PREFIX;
9271 		*kind = BTF_KIND_FUNC;
9272 		break;
9273 	default:
9274 		*prefix = "";
9275 		*kind = BTF_KIND_FUNC;
9276 	}
9277 }
9278 
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)9279 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9280 				   const char *name, __u32 kind)
9281 {
9282 	char btf_type_name[BTF_MAX_NAME_SIZE];
9283 	int ret;
9284 
9285 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9286 		       "%s%s", prefix, name);
9287 	/* snprintf returns the number of characters written excluding the
9288 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9289 	 * indicates truncation.
9290 	 */
9291 	if (ret < 0 || ret >= sizeof(btf_type_name))
9292 		return -ENAMETOOLONG;
9293 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9294 }
9295 
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)9296 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9297 				     enum bpf_attach_type attach_type)
9298 {
9299 	const char *prefix;
9300 	int kind;
9301 
9302 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9303 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9304 }
9305 
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)9306 int libbpf_find_vmlinux_btf_id(const char *name,
9307 			       enum bpf_attach_type attach_type)
9308 {
9309 	struct btf *btf;
9310 	int err;
9311 
9312 	btf = btf__load_vmlinux_btf();
9313 	err = libbpf_get_error(btf);
9314 	if (err) {
9315 		pr_warn("vmlinux BTF is not found\n");
9316 		return libbpf_err(err);
9317 	}
9318 
9319 	err = find_attach_btf_id(btf, name, attach_type);
9320 	if (err <= 0)
9321 		pr_warn("%s is not found in vmlinux BTF\n", name);
9322 
9323 	btf__free(btf);
9324 	return libbpf_err(err);
9325 }
9326 
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd)9327 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9328 {
9329 	struct bpf_prog_info info;
9330 	__u32 info_len = sizeof(info);
9331 	struct btf *btf;
9332 	int err;
9333 
9334 	memset(&info, 0, info_len);
9335 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9336 	if (err) {
9337 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9338 			attach_prog_fd, err);
9339 		return err;
9340 	}
9341 
9342 	err = -EINVAL;
9343 	if (!info.btf_id) {
9344 		pr_warn("The target program doesn't have BTF\n");
9345 		goto out;
9346 	}
9347 	btf = btf__load_from_kernel_by_id(info.btf_id);
9348 	err = libbpf_get_error(btf);
9349 	if (err) {
9350 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9351 		goto out;
9352 	}
9353 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9354 	btf__free(btf);
9355 	if (err <= 0) {
9356 		pr_warn("%s is not found in prog's BTF\n", name);
9357 		goto out;
9358 	}
9359 out:
9360 	return err;
9361 }
9362 
find_kernel_btf_id(struct bpf_object * obj,const char * attach_name,enum bpf_attach_type attach_type,int * btf_obj_fd,int * btf_type_id)9363 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9364 			      enum bpf_attach_type attach_type,
9365 			      int *btf_obj_fd, int *btf_type_id)
9366 {
9367 	int ret, i;
9368 
9369 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9370 	if (ret > 0) {
9371 		*btf_obj_fd = 0; /* vmlinux BTF */
9372 		*btf_type_id = ret;
9373 		return 0;
9374 	}
9375 	if (ret != -ENOENT)
9376 		return ret;
9377 
9378 	ret = load_module_btfs(obj);
9379 	if (ret)
9380 		return ret;
9381 
9382 	for (i = 0; i < obj->btf_module_cnt; i++) {
9383 		const struct module_btf *mod = &obj->btf_modules[i];
9384 
9385 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9386 		if (ret > 0) {
9387 			*btf_obj_fd = mod->fd;
9388 			*btf_type_id = ret;
9389 			return 0;
9390 		}
9391 		if (ret == -ENOENT)
9392 			continue;
9393 
9394 		return ret;
9395 	}
9396 
9397 	return -ESRCH;
9398 }
9399 
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)9400 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9401 				     int *btf_obj_fd, int *btf_type_id)
9402 {
9403 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9404 	__u32 attach_prog_fd = prog->attach_prog_fd;
9405 	int err = 0;
9406 
9407 	/* BPF program's BTF ID */
9408 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9409 		if (!attach_prog_fd) {
9410 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9411 			return -EINVAL;
9412 		}
9413 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9414 		if (err < 0) {
9415 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9416 				 prog->name, attach_prog_fd, attach_name, err);
9417 			return err;
9418 		}
9419 		*btf_obj_fd = 0;
9420 		*btf_type_id = err;
9421 		return 0;
9422 	}
9423 
9424 	/* kernel/module BTF ID */
9425 	if (prog->obj->gen_loader) {
9426 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9427 		*btf_obj_fd = 0;
9428 		*btf_type_id = 1;
9429 	} else {
9430 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9431 	}
9432 	if (err) {
9433 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9434 			prog->name, attach_name, err);
9435 		return err;
9436 	}
9437 	return 0;
9438 }
9439 
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)9440 int libbpf_attach_type_by_name(const char *name,
9441 			       enum bpf_attach_type *attach_type)
9442 {
9443 	char *type_names;
9444 	const struct bpf_sec_def *sec_def;
9445 
9446 	if (!name)
9447 		return libbpf_err(-EINVAL);
9448 
9449 	sec_def = find_sec_def(name);
9450 	if (!sec_def) {
9451 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9452 		type_names = libbpf_get_type_names(true);
9453 		if (type_names != NULL) {
9454 			pr_debug("attachable section(type) names are:%s\n", type_names);
9455 			free(type_names);
9456 		}
9457 
9458 		return libbpf_err(-EINVAL);
9459 	}
9460 
9461 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9462 		return libbpf_err(-EINVAL);
9463 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9464 		return libbpf_err(-EINVAL);
9465 
9466 	*attach_type = sec_def->expected_attach_type;
9467 	return 0;
9468 }
9469 
bpf_map__fd(const struct bpf_map * map)9470 int bpf_map__fd(const struct bpf_map *map)
9471 {
9472 	return map ? map->fd : libbpf_err(-EINVAL);
9473 }
9474 
map_uses_real_name(const struct bpf_map * map)9475 static bool map_uses_real_name(const struct bpf_map *map)
9476 {
9477 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9478 	 * their user-visible name differs from kernel-visible name. Users see
9479 	 * such map's corresponding ELF section name as a map name.
9480 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9481 	 * maps to know which name has to be returned to the user.
9482 	 */
9483 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9484 		return true;
9485 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9486 		return true;
9487 	return false;
9488 }
9489 
bpf_map__name(const struct bpf_map * map)9490 const char *bpf_map__name(const struct bpf_map *map)
9491 {
9492 	if (!map)
9493 		return NULL;
9494 
9495 	if (map_uses_real_name(map))
9496 		return map->real_name;
9497 
9498 	return map->name;
9499 }
9500 
bpf_map__type(const struct bpf_map * map)9501 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9502 {
9503 	return map->def.type;
9504 }
9505 
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)9506 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9507 {
9508 	if (map->fd >= 0)
9509 		return libbpf_err(-EBUSY);
9510 	map->def.type = type;
9511 	return 0;
9512 }
9513 
bpf_map__map_flags(const struct bpf_map * map)9514 __u32 bpf_map__map_flags(const struct bpf_map *map)
9515 {
9516 	return map->def.map_flags;
9517 }
9518 
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)9519 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9520 {
9521 	if (map->fd >= 0)
9522 		return libbpf_err(-EBUSY);
9523 	map->def.map_flags = flags;
9524 	return 0;
9525 }
9526 
bpf_map__map_extra(const struct bpf_map * map)9527 __u64 bpf_map__map_extra(const struct bpf_map *map)
9528 {
9529 	return map->map_extra;
9530 }
9531 
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)9532 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9533 {
9534 	if (map->fd >= 0)
9535 		return libbpf_err(-EBUSY);
9536 	map->map_extra = map_extra;
9537 	return 0;
9538 }
9539 
bpf_map__numa_node(const struct bpf_map * map)9540 __u32 bpf_map__numa_node(const struct bpf_map *map)
9541 {
9542 	return map->numa_node;
9543 }
9544 
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)9545 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9546 {
9547 	if (map->fd >= 0)
9548 		return libbpf_err(-EBUSY);
9549 	map->numa_node = numa_node;
9550 	return 0;
9551 }
9552 
bpf_map__key_size(const struct bpf_map * map)9553 __u32 bpf_map__key_size(const struct bpf_map *map)
9554 {
9555 	return map->def.key_size;
9556 }
9557 
bpf_map__set_key_size(struct bpf_map * map,__u32 size)9558 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9559 {
9560 	if (map->fd >= 0)
9561 		return libbpf_err(-EBUSY);
9562 	map->def.key_size = size;
9563 	return 0;
9564 }
9565 
bpf_map__value_size(const struct bpf_map * map)9566 __u32 bpf_map__value_size(const struct bpf_map *map)
9567 {
9568 	return map->def.value_size;
9569 }
9570 
map_btf_datasec_resize(struct bpf_map * map,__u32 size)9571 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9572 {
9573 	struct btf *btf;
9574 	struct btf_type *datasec_type, *var_type;
9575 	struct btf_var_secinfo *var;
9576 	const struct btf_type *array_type;
9577 	const struct btf_array *array;
9578 	int vlen, element_sz, new_array_id;
9579 	__u32 nr_elements;
9580 
9581 	/* check btf existence */
9582 	btf = bpf_object__btf(map->obj);
9583 	if (!btf)
9584 		return -ENOENT;
9585 
9586 	/* verify map is datasec */
9587 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9588 	if (!btf_is_datasec(datasec_type)) {
9589 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9590 			bpf_map__name(map));
9591 		return -EINVAL;
9592 	}
9593 
9594 	/* verify datasec has at least one var */
9595 	vlen = btf_vlen(datasec_type);
9596 	if (vlen == 0) {
9597 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9598 			bpf_map__name(map));
9599 		return -EINVAL;
9600 	}
9601 
9602 	/* verify last var in the datasec is an array */
9603 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9604 	var_type = btf_type_by_id(btf, var->type);
9605 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9606 	if (!btf_is_array(array_type)) {
9607 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9608 			bpf_map__name(map));
9609 		return -EINVAL;
9610 	}
9611 
9612 	/* verify request size aligns with array */
9613 	array = btf_array(array_type);
9614 	element_sz = btf__resolve_size(btf, array->type);
9615 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9616 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9617 			bpf_map__name(map), element_sz, size);
9618 		return -EINVAL;
9619 	}
9620 
9621 	/* create a new array based on the existing array, but with new length */
9622 	nr_elements = (size - var->offset) / element_sz;
9623 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9624 	if (new_array_id < 0)
9625 		return new_array_id;
9626 
9627 	/* adding a new btf type invalidates existing pointers to btf objects,
9628 	 * so refresh pointers before proceeding
9629 	 */
9630 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9631 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9632 	var_type = btf_type_by_id(btf, var->type);
9633 
9634 	/* finally update btf info */
9635 	datasec_type->size = size;
9636 	var->size = size - var->offset;
9637 	var_type->type = new_array_id;
9638 
9639 	return 0;
9640 }
9641 
bpf_map__set_value_size(struct bpf_map * map,__u32 size)9642 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9643 {
9644 	if (map->fd >= 0)
9645 		return libbpf_err(-EBUSY);
9646 
9647 	if (map->mmaped) {
9648 		int err;
9649 		size_t mmap_old_sz, mmap_new_sz;
9650 
9651 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9652 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9653 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9654 		if (err) {
9655 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9656 				bpf_map__name(map), err);
9657 			return err;
9658 		}
9659 		err = map_btf_datasec_resize(map, size);
9660 		if (err && err != -ENOENT) {
9661 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9662 				bpf_map__name(map), err);
9663 			map->btf_value_type_id = 0;
9664 			map->btf_key_type_id = 0;
9665 		}
9666 	}
9667 
9668 	map->def.value_size = size;
9669 	return 0;
9670 }
9671 
bpf_map__btf_key_type_id(const struct bpf_map * map)9672 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9673 {
9674 	return map ? map->btf_key_type_id : 0;
9675 }
9676 
bpf_map__btf_value_type_id(const struct bpf_map * map)9677 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9678 {
9679 	return map ? map->btf_value_type_id : 0;
9680 }
9681 
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)9682 int bpf_map__set_initial_value(struct bpf_map *map,
9683 			       const void *data, size_t size)
9684 {
9685 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9686 	    size != map->def.value_size || map->fd >= 0)
9687 		return libbpf_err(-EINVAL);
9688 
9689 	memcpy(map->mmaped, data, size);
9690 	return 0;
9691 }
9692 
bpf_map__initial_value(struct bpf_map * map,size_t * psize)9693 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9694 {
9695 	if (!map->mmaped)
9696 		return NULL;
9697 	*psize = map->def.value_size;
9698 	return map->mmaped;
9699 }
9700 
bpf_map__is_internal(const struct bpf_map * map)9701 bool bpf_map__is_internal(const struct bpf_map *map)
9702 {
9703 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9704 }
9705 
bpf_map__ifindex(const struct bpf_map * map)9706 __u32 bpf_map__ifindex(const struct bpf_map *map)
9707 {
9708 	return map->map_ifindex;
9709 }
9710 
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)9711 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9712 {
9713 	if (map->fd >= 0)
9714 		return libbpf_err(-EBUSY);
9715 	map->map_ifindex = ifindex;
9716 	return 0;
9717 }
9718 
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)9719 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9720 {
9721 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9722 		pr_warn("error: unsupported map type\n");
9723 		return libbpf_err(-EINVAL);
9724 	}
9725 	if (map->inner_map_fd != -1) {
9726 		pr_warn("error: inner_map_fd already specified\n");
9727 		return libbpf_err(-EINVAL);
9728 	}
9729 	if (map->inner_map) {
9730 		bpf_map__destroy(map->inner_map);
9731 		zfree(&map->inner_map);
9732 	}
9733 	map->inner_map_fd = fd;
9734 	return 0;
9735 }
9736 
9737 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)9738 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9739 {
9740 	ssize_t idx;
9741 	struct bpf_map *s, *e;
9742 
9743 	if (!obj || !obj->maps)
9744 		return errno = EINVAL, NULL;
9745 
9746 	s = obj->maps;
9747 	e = obj->maps + obj->nr_maps;
9748 
9749 	if ((m < s) || (m >= e)) {
9750 		pr_warn("error in %s: map handler doesn't belong to object\n",
9751 			 __func__);
9752 		return errno = EINVAL, NULL;
9753 	}
9754 
9755 	idx = (m - obj->maps) + i;
9756 	if (idx >= obj->nr_maps || idx < 0)
9757 		return NULL;
9758 	return &obj->maps[idx];
9759 }
9760 
9761 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)9762 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9763 {
9764 	if (prev == NULL && obj != NULL)
9765 		return obj->maps;
9766 
9767 	return __bpf_map__iter(prev, obj, 1);
9768 }
9769 
9770 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)9771 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9772 {
9773 	if (next == NULL && obj != NULL) {
9774 		if (!obj->nr_maps)
9775 			return NULL;
9776 		return obj->maps + obj->nr_maps - 1;
9777 	}
9778 
9779 	return __bpf_map__iter(next, obj, -1);
9780 }
9781 
9782 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)9783 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9784 {
9785 	struct bpf_map *pos;
9786 
9787 	bpf_object__for_each_map(pos, obj) {
9788 		/* if it's a special internal map name (which always starts
9789 		 * with dot) then check if that special name matches the
9790 		 * real map name (ELF section name)
9791 		 */
9792 		if (name[0] == '.') {
9793 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9794 				return pos;
9795 			continue;
9796 		}
9797 		/* otherwise map name has to be an exact match */
9798 		if (map_uses_real_name(pos)) {
9799 			if (strcmp(pos->real_name, name) == 0)
9800 				return pos;
9801 			continue;
9802 		}
9803 		if (strcmp(pos->name, name) == 0)
9804 			return pos;
9805 	}
9806 	return errno = ENOENT, NULL;
9807 }
9808 
9809 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)9810 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9811 {
9812 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9813 }
9814 
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)9815 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9816 			   size_t value_sz, bool check_value_sz)
9817 {
9818 	if (map->fd <= 0)
9819 		return -ENOENT;
9820 
9821 	if (map->def.key_size != key_sz) {
9822 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9823 			map->name, key_sz, map->def.key_size);
9824 		return -EINVAL;
9825 	}
9826 
9827 	if (!check_value_sz)
9828 		return 0;
9829 
9830 	switch (map->def.type) {
9831 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9832 	case BPF_MAP_TYPE_PERCPU_HASH:
9833 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9834 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9835 		int num_cpu = libbpf_num_possible_cpus();
9836 		size_t elem_sz = roundup(map->def.value_size, 8);
9837 
9838 		if (value_sz != num_cpu * elem_sz) {
9839 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9840 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9841 			return -EINVAL;
9842 		}
9843 		break;
9844 	}
9845 	default:
9846 		if (map->def.value_size != value_sz) {
9847 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9848 				map->name, value_sz, map->def.value_size);
9849 			return -EINVAL;
9850 		}
9851 		break;
9852 	}
9853 	return 0;
9854 }
9855 
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)9856 int bpf_map__lookup_elem(const struct bpf_map *map,
9857 			 const void *key, size_t key_sz,
9858 			 void *value, size_t value_sz, __u64 flags)
9859 {
9860 	int err;
9861 
9862 	err = validate_map_op(map, key_sz, value_sz, true);
9863 	if (err)
9864 		return libbpf_err(err);
9865 
9866 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9867 }
9868 
bpf_map__update_elem(const struct bpf_map * map,const void * key,size_t key_sz,const void * value,size_t value_sz,__u64 flags)9869 int bpf_map__update_elem(const struct bpf_map *map,
9870 			 const void *key, size_t key_sz,
9871 			 const void *value, size_t value_sz, __u64 flags)
9872 {
9873 	int err;
9874 
9875 	err = validate_map_op(map, key_sz, value_sz, true);
9876 	if (err)
9877 		return libbpf_err(err);
9878 
9879 	return bpf_map_update_elem(map->fd, key, value, flags);
9880 }
9881 
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)9882 int bpf_map__delete_elem(const struct bpf_map *map,
9883 			 const void *key, size_t key_sz, __u64 flags)
9884 {
9885 	int err;
9886 
9887 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9888 	if (err)
9889 		return libbpf_err(err);
9890 
9891 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9892 }
9893 
bpf_map__lookup_and_delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)9894 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9895 				    const void *key, size_t key_sz,
9896 				    void *value, size_t value_sz, __u64 flags)
9897 {
9898 	int err;
9899 
9900 	err = validate_map_op(map, key_sz, value_sz, true);
9901 	if (err)
9902 		return libbpf_err(err);
9903 
9904 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9905 }
9906 
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)9907 int bpf_map__get_next_key(const struct bpf_map *map,
9908 			  const void *cur_key, void *next_key, size_t key_sz)
9909 {
9910 	int err;
9911 
9912 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9913 	if (err)
9914 		return libbpf_err(err);
9915 
9916 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9917 }
9918 
libbpf_get_error(const void * ptr)9919 long libbpf_get_error(const void *ptr)
9920 {
9921 	if (!IS_ERR_OR_NULL(ptr))
9922 		return 0;
9923 
9924 	if (IS_ERR(ptr))
9925 		errno = -PTR_ERR(ptr);
9926 
9927 	/* If ptr == NULL, then errno should be already set by the failing
9928 	 * API, because libbpf never returns NULL on success and it now always
9929 	 * sets errno on error. So no extra errno handling for ptr == NULL
9930 	 * case.
9931 	 */
9932 	return -errno;
9933 }
9934 
9935 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)9936 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9937 {
9938 	int ret;
9939 
9940 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9941 	return libbpf_err_errno(ret);
9942 }
9943 
9944 /* Release "ownership" of underlying BPF resource (typically, BPF program
9945  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9946  * link, when destructed through bpf_link__destroy() call won't attempt to
9947  * detach/unregisted that BPF resource. This is useful in situations where,
9948  * say, attached BPF program has to outlive userspace program that attached it
9949  * in the system. Depending on type of BPF program, though, there might be
9950  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9951  * exit of userspace program doesn't trigger automatic detachment and clean up
9952  * inside the kernel.
9953  */
bpf_link__disconnect(struct bpf_link * link)9954 void bpf_link__disconnect(struct bpf_link *link)
9955 {
9956 	link->disconnected = true;
9957 }
9958 
bpf_link__destroy(struct bpf_link * link)9959 int bpf_link__destroy(struct bpf_link *link)
9960 {
9961 	int err = 0;
9962 
9963 	if (IS_ERR_OR_NULL(link))
9964 		return 0;
9965 
9966 	if (!link->disconnected && link->detach)
9967 		err = link->detach(link);
9968 	if (link->pin_path)
9969 		free(link->pin_path);
9970 	if (link->dealloc)
9971 		link->dealloc(link);
9972 	else
9973 		free(link);
9974 
9975 	return libbpf_err(err);
9976 }
9977 
bpf_link__fd(const struct bpf_link * link)9978 int bpf_link__fd(const struct bpf_link *link)
9979 {
9980 	return link->fd;
9981 }
9982 
bpf_link__pin_path(const struct bpf_link * link)9983 const char *bpf_link__pin_path(const struct bpf_link *link)
9984 {
9985 	return link->pin_path;
9986 }
9987 
bpf_link__detach_fd(struct bpf_link * link)9988 static int bpf_link__detach_fd(struct bpf_link *link)
9989 {
9990 	return libbpf_err_errno(close(link->fd));
9991 }
9992 
bpf_link__open(const char * path)9993 struct bpf_link *bpf_link__open(const char *path)
9994 {
9995 	struct bpf_link *link;
9996 	int fd;
9997 
9998 	fd = bpf_obj_get(path);
9999 	if (fd < 0) {
10000 		fd = -errno;
10001 		pr_warn("failed to open link at %s: %d\n", path, fd);
10002 		return libbpf_err_ptr(fd);
10003 	}
10004 
10005 	link = calloc(1, sizeof(*link));
10006 	if (!link) {
10007 		close(fd);
10008 		return libbpf_err_ptr(-ENOMEM);
10009 	}
10010 	link->detach = &bpf_link__detach_fd;
10011 	link->fd = fd;
10012 
10013 	link->pin_path = strdup(path);
10014 	if (!link->pin_path) {
10015 		bpf_link__destroy(link);
10016 		return libbpf_err_ptr(-ENOMEM);
10017 	}
10018 
10019 	return link;
10020 }
10021 
bpf_link__detach(struct bpf_link * link)10022 int bpf_link__detach(struct bpf_link *link)
10023 {
10024 	return bpf_link_detach(link->fd) ? -errno : 0;
10025 }
10026 
bpf_link__pin(struct bpf_link * link,const char * path)10027 int bpf_link__pin(struct bpf_link *link, const char *path)
10028 {
10029 	int err;
10030 
10031 	if (link->pin_path)
10032 		return libbpf_err(-EBUSY);
10033 	err = make_parent_dir(path);
10034 	if (err)
10035 		return libbpf_err(err);
10036 	err = check_path(path);
10037 	if (err)
10038 		return libbpf_err(err);
10039 
10040 	link->pin_path = strdup(path);
10041 	if (!link->pin_path)
10042 		return libbpf_err(-ENOMEM);
10043 
10044 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10045 		err = -errno;
10046 		zfree(&link->pin_path);
10047 		return libbpf_err(err);
10048 	}
10049 
10050 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10051 	return 0;
10052 }
10053 
bpf_link__unpin(struct bpf_link * link)10054 int bpf_link__unpin(struct bpf_link *link)
10055 {
10056 	int err;
10057 
10058 	if (!link->pin_path)
10059 		return libbpf_err(-EINVAL);
10060 
10061 	err = unlink(link->pin_path);
10062 	if (err != 0)
10063 		return -errno;
10064 
10065 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10066 	zfree(&link->pin_path);
10067 	return 0;
10068 }
10069 
10070 struct bpf_link_perf {
10071 	struct bpf_link link;
10072 	int perf_event_fd;
10073 	/* legacy kprobe support: keep track of probe identifier and type */
10074 	char *legacy_probe_name;
10075 	bool legacy_is_kprobe;
10076 	bool legacy_is_retprobe;
10077 };
10078 
10079 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10080 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10081 
bpf_link_perf_detach(struct bpf_link * link)10082 static int bpf_link_perf_detach(struct bpf_link *link)
10083 {
10084 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10085 	int err = 0;
10086 
10087 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10088 		err = -errno;
10089 
10090 	if (perf_link->perf_event_fd != link->fd)
10091 		close(perf_link->perf_event_fd);
10092 	close(link->fd);
10093 
10094 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10095 	if (perf_link->legacy_probe_name) {
10096 		if (perf_link->legacy_is_kprobe) {
10097 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10098 							 perf_link->legacy_is_retprobe);
10099 		} else {
10100 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10101 							 perf_link->legacy_is_retprobe);
10102 		}
10103 	}
10104 
10105 	return err;
10106 }
10107 
bpf_link_perf_dealloc(struct bpf_link * link)10108 static void bpf_link_perf_dealloc(struct bpf_link *link)
10109 {
10110 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10111 
10112 	free(perf_link->legacy_probe_name);
10113 	free(perf_link);
10114 }
10115 
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10116 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10117 						     const struct bpf_perf_event_opts *opts)
10118 {
10119 	char errmsg[STRERR_BUFSIZE];
10120 	struct bpf_link_perf *link;
10121 	int prog_fd, link_fd = -1, err;
10122 	bool force_ioctl_attach;
10123 
10124 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10125 		return libbpf_err_ptr(-EINVAL);
10126 
10127 	if (pfd < 0) {
10128 		pr_warn("prog '%s': invalid perf event FD %d\n",
10129 			prog->name, pfd);
10130 		return libbpf_err_ptr(-EINVAL);
10131 	}
10132 	prog_fd = bpf_program__fd(prog);
10133 	if (prog_fd < 0) {
10134 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10135 			prog->name);
10136 		return libbpf_err_ptr(-EINVAL);
10137 	}
10138 
10139 	link = calloc(1, sizeof(*link));
10140 	if (!link)
10141 		return libbpf_err_ptr(-ENOMEM);
10142 	link->link.detach = &bpf_link_perf_detach;
10143 	link->link.dealloc = &bpf_link_perf_dealloc;
10144 	link->perf_event_fd = pfd;
10145 
10146 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10147 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10148 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10149 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10150 
10151 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10152 		if (link_fd < 0) {
10153 			err = -errno;
10154 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10155 				prog->name, pfd,
10156 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10157 			goto err_out;
10158 		}
10159 		link->link.fd = link_fd;
10160 	} else {
10161 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10162 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10163 			err = -EOPNOTSUPP;
10164 			goto err_out;
10165 		}
10166 
10167 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10168 			err = -errno;
10169 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10170 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10171 			if (err == -EPROTO)
10172 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10173 					prog->name, pfd);
10174 			goto err_out;
10175 		}
10176 		link->link.fd = pfd;
10177 	}
10178 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10179 		err = -errno;
10180 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10181 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10182 		goto err_out;
10183 	}
10184 
10185 	return &link->link;
10186 err_out:
10187 	if (link_fd >= 0)
10188 		close(link_fd);
10189 	free(link);
10190 	return libbpf_err_ptr(err);
10191 }
10192 
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10193 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10194 {
10195 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10196 }
10197 
10198 /*
10199  * this function is expected to parse integer in the range of [0, 2^31-1] from
10200  * given file using scanf format string fmt. If actual parsed value is
10201  * negative, the result might be indistinguishable from error
10202  */
parse_uint_from_file(const char * file,const char * fmt)10203 static int parse_uint_from_file(const char *file, const char *fmt)
10204 {
10205 	char buf[STRERR_BUFSIZE];
10206 	int err, ret;
10207 	FILE *f;
10208 
10209 	f = fopen(file, "re");
10210 	if (!f) {
10211 		err = -errno;
10212 		pr_debug("failed to open '%s': %s\n", file,
10213 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10214 		return err;
10215 	}
10216 	err = fscanf(f, fmt, &ret);
10217 	if (err != 1) {
10218 		err = err == EOF ? -EIO : -errno;
10219 		pr_debug("failed to parse '%s': %s\n", file,
10220 			libbpf_strerror_r(err, buf, sizeof(buf)));
10221 		fclose(f);
10222 		return err;
10223 	}
10224 	fclose(f);
10225 	return ret;
10226 }
10227 
determine_kprobe_perf_type(void)10228 static int determine_kprobe_perf_type(void)
10229 {
10230 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10231 
10232 	return parse_uint_from_file(file, "%d\n");
10233 }
10234 
determine_uprobe_perf_type(void)10235 static int determine_uprobe_perf_type(void)
10236 {
10237 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10238 
10239 	return parse_uint_from_file(file, "%d\n");
10240 }
10241 
determine_kprobe_retprobe_bit(void)10242 static int determine_kprobe_retprobe_bit(void)
10243 {
10244 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10245 
10246 	return parse_uint_from_file(file, "config:%d\n");
10247 }
10248 
determine_uprobe_retprobe_bit(void)10249 static int determine_uprobe_retprobe_bit(void)
10250 {
10251 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10252 
10253 	return parse_uint_from_file(file, "config:%d\n");
10254 }
10255 
10256 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10257 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10258 
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)10259 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10260 				 uint64_t offset, int pid, size_t ref_ctr_off)
10261 {
10262 	const size_t attr_sz = sizeof(struct perf_event_attr);
10263 	struct perf_event_attr attr;
10264 	char errmsg[STRERR_BUFSIZE];
10265 	int type, pfd;
10266 
10267 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10268 		return -EINVAL;
10269 
10270 	memset(&attr, 0, attr_sz);
10271 
10272 	type = uprobe ? determine_uprobe_perf_type()
10273 		      : determine_kprobe_perf_type();
10274 	if (type < 0) {
10275 		pr_warn("failed to determine %s perf type: %s\n",
10276 			uprobe ? "uprobe" : "kprobe",
10277 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10278 		return type;
10279 	}
10280 	if (retprobe) {
10281 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10282 				 : determine_kprobe_retprobe_bit();
10283 
10284 		if (bit < 0) {
10285 			pr_warn("failed to determine %s retprobe bit: %s\n",
10286 				uprobe ? "uprobe" : "kprobe",
10287 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10288 			return bit;
10289 		}
10290 		attr.config |= 1 << bit;
10291 	}
10292 	attr.size = attr_sz;
10293 	attr.type = type;
10294 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10295 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10296 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10297 
10298 	/* pid filter is meaningful only for uprobes */
10299 	pfd = syscall(__NR_perf_event_open, &attr,
10300 		      pid < 0 ? -1 : pid /* pid */,
10301 		      pid == -1 ? 0 : -1 /* cpu */,
10302 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10303 	return pfd >= 0 ? pfd : -errno;
10304 }
10305 
append_to_file(const char * file,const char * fmt,...)10306 static int append_to_file(const char *file, const char *fmt, ...)
10307 {
10308 	int fd, n, err = 0;
10309 	va_list ap;
10310 	char buf[1024];
10311 
10312 	va_start(ap, fmt);
10313 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10314 	va_end(ap);
10315 
10316 	if (n < 0 || n >= sizeof(buf))
10317 		return -EINVAL;
10318 
10319 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10320 	if (fd < 0)
10321 		return -errno;
10322 
10323 	if (write(fd, buf, n) < 0)
10324 		err = -errno;
10325 
10326 	close(fd);
10327 	return err;
10328 }
10329 
10330 #define DEBUGFS "/sys/kernel/debug/tracing"
10331 #define TRACEFS "/sys/kernel/tracing"
10332 
use_debugfs(void)10333 static bool use_debugfs(void)
10334 {
10335 	static int has_debugfs = -1;
10336 
10337 	if (has_debugfs < 0)
10338 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10339 
10340 	return has_debugfs == 1;
10341 }
10342 
tracefs_path(void)10343 static const char *tracefs_path(void)
10344 {
10345 	return use_debugfs() ? DEBUGFS : TRACEFS;
10346 }
10347 
tracefs_kprobe_events(void)10348 static const char *tracefs_kprobe_events(void)
10349 {
10350 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10351 }
10352 
tracefs_uprobe_events(void)10353 static const char *tracefs_uprobe_events(void)
10354 {
10355 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10356 }
10357 
tracefs_available_filter_functions(void)10358 static const char *tracefs_available_filter_functions(void)
10359 {
10360 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10361 			     : TRACEFS"/available_filter_functions";
10362 }
10363 
tracefs_available_filter_functions_addrs(void)10364 static const char *tracefs_available_filter_functions_addrs(void)
10365 {
10366 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10367 			     : TRACEFS"/available_filter_functions_addrs";
10368 }
10369 
gen_kprobe_legacy_event_name(char * buf,size_t buf_sz,const char * kfunc_name,size_t offset)10370 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10371 					 const char *kfunc_name, size_t offset)
10372 {
10373 	static int index = 0;
10374 	int i;
10375 
10376 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10377 		 __sync_fetch_and_add(&index, 1));
10378 
10379 	/* sanitize binary_path in the probe name */
10380 	for (i = 0; buf[i]; i++) {
10381 		if (!isalnum(buf[i]))
10382 			buf[i] = '_';
10383 	}
10384 }
10385 
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)10386 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10387 				   const char *kfunc_name, size_t offset)
10388 {
10389 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10390 			      retprobe ? 'r' : 'p',
10391 			      retprobe ? "kretprobes" : "kprobes",
10392 			      probe_name, kfunc_name, offset);
10393 }
10394 
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)10395 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10396 {
10397 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10398 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10399 }
10400 
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)10401 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10402 {
10403 	char file[256];
10404 
10405 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10406 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10407 
10408 	return parse_uint_from_file(file, "%d\n");
10409 }
10410 
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)10411 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10412 					 const char *kfunc_name, size_t offset, int pid)
10413 {
10414 	const size_t attr_sz = sizeof(struct perf_event_attr);
10415 	struct perf_event_attr attr;
10416 	char errmsg[STRERR_BUFSIZE];
10417 	int type, pfd, err;
10418 
10419 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10420 	if (err < 0) {
10421 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10422 			kfunc_name, offset,
10423 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10424 		return err;
10425 	}
10426 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10427 	if (type < 0) {
10428 		err = type;
10429 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10430 			kfunc_name, offset,
10431 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10432 		goto err_clean_legacy;
10433 	}
10434 
10435 	memset(&attr, 0, attr_sz);
10436 	attr.size = attr_sz;
10437 	attr.config = type;
10438 	attr.type = PERF_TYPE_TRACEPOINT;
10439 
10440 	pfd = syscall(__NR_perf_event_open, &attr,
10441 		      pid < 0 ? -1 : pid, /* pid */
10442 		      pid == -1 ? 0 : -1, /* cpu */
10443 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10444 	if (pfd < 0) {
10445 		err = -errno;
10446 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10447 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10448 		goto err_clean_legacy;
10449 	}
10450 	return pfd;
10451 
10452 err_clean_legacy:
10453 	/* Clear the newly added legacy kprobe_event */
10454 	remove_kprobe_event_legacy(probe_name, retprobe);
10455 	return err;
10456 }
10457 
arch_specific_syscall_pfx(void)10458 static const char *arch_specific_syscall_pfx(void)
10459 {
10460 #if defined(__x86_64__)
10461 	return "x64";
10462 #elif defined(__i386__)
10463 	return "ia32";
10464 #elif defined(__s390x__)
10465 	return "s390x";
10466 #elif defined(__s390__)
10467 	return "s390";
10468 #elif defined(__arm__)
10469 	return "arm";
10470 #elif defined(__aarch64__)
10471 	return "arm64";
10472 #elif defined(__mips__)
10473 	return "mips";
10474 #elif defined(__riscv)
10475 	return "riscv";
10476 #elif defined(__powerpc__)
10477 	return "powerpc";
10478 #elif defined(__powerpc64__)
10479 	return "powerpc64";
10480 #else
10481 	return NULL;
10482 #endif
10483 }
10484 
probe_kern_syscall_wrapper(void)10485 static int probe_kern_syscall_wrapper(void)
10486 {
10487 	char syscall_name[64];
10488 	const char *ksys_pfx;
10489 
10490 	ksys_pfx = arch_specific_syscall_pfx();
10491 	if (!ksys_pfx)
10492 		return 0;
10493 
10494 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10495 
10496 	if (determine_kprobe_perf_type() >= 0) {
10497 		int pfd;
10498 
10499 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10500 		if (pfd >= 0)
10501 			close(pfd);
10502 
10503 		return pfd >= 0 ? 1 : 0;
10504 	} else { /* legacy mode */
10505 		char probe_name[128];
10506 
10507 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10508 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10509 			return 0;
10510 
10511 		(void)remove_kprobe_event_legacy(probe_name, false);
10512 		return 1;
10513 	}
10514 }
10515 
10516 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)10517 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10518 				const char *func_name,
10519 				const struct bpf_kprobe_opts *opts)
10520 {
10521 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10522 	enum probe_attach_mode attach_mode;
10523 	char errmsg[STRERR_BUFSIZE];
10524 	char *legacy_probe = NULL;
10525 	struct bpf_link *link;
10526 	size_t offset;
10527 	bool retprobe, legacy;
10528 	int pfd, err;
10529 
10530 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10531 		return libbpf_err_ptr(-EINVAL);
10532 
10533 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10534 	retprobe = OPTS_GET(opts, retprobe, false);
10535 	offset = OPTS_GET(opts, offset, 0);
10536 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10537 
10538 	legacy = determine_kprobe_perf_type() < 0;
10539 	switch (attach_mode) {
10540 	case PROBE_ATTACH_MODE_LEGACY:
10541 		legacy = true;
10542 		pe_opts.force_ioctl_attach = true;
10543 		break;
10544 	case PROBE_ATTACH_MODE_PERF:
10545 		if (legacy)
10546 			return libbpf_err_ptr(-ENOTSUP);
10547 		pe_opts.force_ioctl_attach = true;
10548 		break;
10549 	case PROBE_ATTACH_MODE_LINK:
10550 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10551 			return libbpf_err_ptr(-ENOTSUP);
10552 		break;
10553 	case PROBE_ATTACH_MODE_DEFAULT:
10554 		break;
10555 	default:
10556 		return libbpf_err_ptr(-EINVAL);
10557 	}
10558 
10559 	if (!legacy) {
10560 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10561 					    func_name, offset,
10562 					    -1 /* pid */, 0 /* ref_ctr_off */);
10563 	} else {
10564 		char probe_name[256];
10565 
10566 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10567 					     func_name, offset);
10568 
10569 		legacy_probe = strdup(probe_name);
10570 		if (!legacy_probe)
10571 			return libbpf_err_ptr(-ENOMEM);
10572 
10573 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10574 						    offset, -1 /* pid */);
10575 	}
10576 	if (pfd < 0) {
10577 		err = -errno;
10578 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10579 			prog->name, retprobe ? "kretprobe" : "kprobe",
10580 			func_name, offset,
10581 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10582 		goto err_out;
10583 	}
10584 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10585 	err = libbpf_get_error(link);
10586 	if (err) {
10587 		close(pfd);
10588 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10589 			prog->name, retprobe ? "kretprobe" : "kprobe",
10590 			func_name, offset,
10591 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10592 		goto err_clean_legacy;
10593 	}
10594 	if (legacy) {
10595 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10596 
10597 		perf_link->legacy_probe_name = legacy_probe;
10598 		perf_link->legacy_is_kprobe = true;
10599 		perf_link->legacy_is_retprobe = retprobe;
10600 	}
10601 
10602 	return link;
10603 
10604 err_clean_legacy:
10605 	if (legacy)
10606 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10607 err_out:
10608 	free(legacy_probe);
10609 	return libbpf_err_ptr(err);
10610 }
10611 
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)10612 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10613 					    bool retprobe,
10614 					    const char *func_name)
10615 {
10616 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10617 		.retprobe = retprobe,
10618 	);
10619 
10620 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10621 }
10622 
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)10623 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10624 					      const char *syscall_name,
10625 					      const struct bpf_ksyscall_opts *opts)
10626 {
10627 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10628 	char func_name[128];
10629 
10630 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10631 		return libbpf_err_ptr(-EINVAL);
10632 
10633 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10634 		/* arch_specific_syscall_pfx() should never return NULL here
10635 		 * because it is guarded by kernel_supports(). However, since
10636 		 * compiler does not know that we have an explicit conditional
10637 		 * as well.
10638 		 */
10639 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10640 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10641 	} else {
10642 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10643 	}
10644 
10645 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10646 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10647 
10648 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10649 }
10650 
10651 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)10652 bool glob_match(const char *str, const char *pat)
10653 {
10654 	while (*str && *pat && *pat != '*') {
10655 		if (*pat == '?') {      /* Matches any single character */
10656 			str++;
10657 			pat++;
10658 			continue;
10659 		}
10660 		if (*str != *pat)
10661 			return false;
10662 		str++;
10663 		pat++;
10664 	}
10665 	/* Check wild card */
10666 	if (*pat == '*') {
10667 		while (*pat == '*')
10668 			pat++;
10669 		if (!*pat) /* Tail wild card matches all */
10670 			return true;
10671 		while (*str)
10672 			if (glob_match(str++, pat))
10673 				return true;
10674 	}
10675 	return !*str && !*pat;
10676 }
10677 
10678 struct kprobe_multi_resolve {
10679 	const char *pattern;
10680 	unsigned long *addrs;
10681 	size_t cap;
10682 	size_t cnt;
10683 };
10684 
10685 struct avail_kallsyms_data {
10686 	char **syms;
10687 	size_t cnt;
10688 	struct kprobe_multi_resolve *res;
10689 };
10690 
avail_func_cmp(const void * a,const void * b)10691 static int avail_func_cmp(const void *a, const void *b)
10692 {
10693 	return strcmp(*(const char **)a, *(const char **)b);
10694 }
10695 
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)10696 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10697 			     const char *sym_name, void *ctx)
10698 {
10699 	struct avail_kallsyms_data *data = ctx;
10700 	struct kprobe_multi_resolve *res = data->res;
10701 	int err;
10702 
10703 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10704 		return 0;
10705 
10706 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10707 	if (err)
10708 		return err;
10709 
10710 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10711 	return 0;
10712 }
10713 
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)10714 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10715 {
10716 	const char *available_functions_file = tracefs_available_filter_functions();
10717 	struct avail_kallsyms_data data;
10718 	char sym_name[500];
10719 	FILE *f;
10720 	int err = 0, ret, i;
10721 	char **syms = NULL;
10722 	size_t cap = 0, cnt = 0;
10723 
10724 	f = fopen(available_functions_file, "re");
10725 	if (!f) {
10726 		err = -errno;
10727 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10728 		return err;
10729 	}
10730 
10731 	while (true) {
10732 		char *name;
10733 
10734 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10735 		if (ret == EOF && feof(f))
10736 			break;
10737 
10738 		if (ret != 1) {
10739 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10740 			err = -EINVAL;
10741 			goto cleanup;
10742 		}
10743 
10744 		if (!glob_match(sym_name, res->pattern))
10745 			continue;
10746 
10747 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10748 		if (err)
10749 			goto cleanup;
10750 
10751 		name = strdup(sym_name);
10752 		if (!name) {
10753 			err = -errno;
10754 			goto cleanup;
10755 		}
10756 
10757 		syms[cnt++] = name;
10758 	}
10759 
10760 	/* no entries found, bail out */
10761 	if (cnt == 0) {
10762 		err = -ENOENT;
10763 		goto cleanup;
10764 	}
10765 
10766 	/* sort available functions */
10767 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10768 
10769 	data.syms = syms;
10770 	data.res = res;
10771 	data.cnt = cnt;
10772 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10773 
10774 	if (res->cnt == 0)
10775 		err = -ENOENT;
10776 
10777 cleanup:
10778 	for (i = 0; i < cnt; i++)
10779 		free((char *)syms[i]);
10780 	free(syms);
10781 
10782 	fclose(f);
10783 	return err;
10784 }
10785 
has_available_filter_functions_addrs(void)10786 static bool has_available_filter_functions_addrs(void)
10787 {
10788 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10789 }
10790 
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)10791 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10792 {
10793 	const char *available_path = tracefs_available_filter_functions_addrs();
10794 	char sym_name[500];
10795 	FILE *f;
10796 	int ret, err = 0;
10797 	unsigned long long sym_addr;
10798 
10799 	f = fopen(available_path, "re");
10800 	if (!f) {
10801 		err = -errno;
10802 		pr_warn("failed to open %s: %d\n", available_path, err);
10803 		return err;
10804 	}
10805 
10806 	while (true) {
10807 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10808 		if (ret == EOF && feof(f))
10809 			break;
10810 
10811 		if (ret != 2) {
10812 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10813 				ret);
10814 			err = -EINVAL;
10815 			goto cleanup;
10816 		}
10817 
10818 		if (!glob_match(sym_name, res->pattern))
10819 			continue;
10820 
10821 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10822 					sizeof(*res->addrs), res->cnt + 1);
10823 		if (err)
10824 			goto cleanup;
10825 
10826 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10827 	}
10828 
10829 	if (res->cnt == 0)
10830 		err = -ENOENT;
10831 
10832 cleanup:
10833 	fclose(f);
10834 	return err;
10835 }
10836 
10837 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)10838 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10839 				      const char *pattern,
10840 				      const struct bpf_kprobe_multi_opts *opts)
10841 {
10842 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10843 	struct kprobe_multi_resolve res = {
10844 		.pattern = pattern,
10845 	};
10846 	struct bpf_link *link = NULL;
10847 	char errmsg[STRERR_BUFSIZE];
10848 	const unsigned long *addrs;
10849 	int err, link_fd, prog_fd;
10850 	const __u64 *cookies;
10851 	const char **syms;
10852 	bool retprobe;
10853 	size_t cnt;
10854 
10855 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10856 		return libbpf_err_ptr(-EINVAL);
10857 
10858 	syms    = OPTS_GET(opts, syms, false);
10859 	addrs   = OPTS_GET(opts, addrs, false);
10860 	cnt     = OPTS_GET(opts, cnt, false);
10861 	cookies = OPTS_GET(opts, cookies, false);
10862 
10863 	if (!pattern && !addrs && !syms)
10864 		return libbpf_err_ptr(-EINVAL);
10865 	if (pattern && (addrs || syms || cookies || cnt))
10866 		return libbpf_err_ptr(-EINVAL);
10867 	if (!pattern && !cnt)
10868 		return libbpf_err_ptr(-EINVAL);
10869 	if (addrs && syms)
10870 		return libbpf_err_ptr(-EINVAL);
10871 
10872 	if (pattern) {
10873 		if (has_available_filter_functions_addrs())
10874 			err = libbpf_available_kprobes_parse(&res);
10875 		else
10876 			err = libbpf_available_kallsyms_parse(&res);
10877 		if (err)
10878 			goto error;
10879 		addrs = res.addrs;
10880 		cnt = res.cnt;
10881 	}
10882 
10883 	retprobe = OPTS_GET(opts, retprobe, false);
10884 
10885 	lopts.kprobe_multi.syms = syms;
10886 	lopts.kprobe_multi.addrs = addrs;
10887 	lopts.kprobe_multi.cookies = cookies;
10888 	lopts.kprobe_multi.cnt = cnt;
10889 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10890 
10891 	link = calloc(1, sizeof(*link));
10892 	if (!link) {
10893 		err = -ENOMEM;
10894 		goto error;
10895 	}
10896 	link->detach = &bpf_link__detach_fd;
10897 
10898 	prog_fd = bpf_program__fd(prog);
10899 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10900 	if (link_fd < 0) {
10901 		err = -errno;
10902 		pr_warn("prog '%s': failed to attach: %s\n",
10903 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10904 		goto error;
10905 	}
10906 	link->fd = link_fd;
10907 	free(res.addrs);
10908 	return link;
10909 
10910 error:
10911 	free(link);
10912 	free(res.addrs);
10913 	return libbpf_err_ptr(err);
10914 }
10915 
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10916 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10917 {
10918 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10919 	unsigned long offset = 0;
10920 	const char *func_name;
10921 	char *func;
10922 	int n;
10923 
10924 	*link = NULL;
10925 
10926 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10927 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10928 		return 0;
10929 
10930 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10931 	if (opts.retprobe)
10932 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10933 	else
10934 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10935 
10936 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10937 	if (n < 1) {
10938 		pr_warn("kprobe name is invalid: %s\n", func_name);
10939 		return -EINVAL;
10940 	}
10941 	if (opts.retprobe && offset != 0) {
10942 		free(func);
10943 		pr_warn("kretprobes do not support offset specification\n");
10944 		return -EINVAL;
10945 	}
10946 
10947 	opts.offset = offset;
10948 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10949 	free(func);
10950 	return libbpf_get_error(*link);
10951 }
10952 
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10953 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10954 {
10955 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10956 	const char *syscall_name;
10957 
10958 	*link = NULL;
10959 
10960 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10961 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10962 		return 0;
10963 
10964 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10965 	if (opts.retprobe)
10966 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10967 	else
10968 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10969 
10970 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10971 	return *link ? 0 : -errno;
10972 }
10973 
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10974 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10975 {
10976 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10977 	const char *spec;
10978 	char *pattern;
10979 	int n;
10980 
10981 	*link = NULL;
10982 
10983 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10984 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10985 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10986 		return 0;
10987 
10988 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10989 	if (opts.retprobe)
10990 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10991 	else
10992 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10993 
10994 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10995 	if (n < 1) {
10996 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
10997 		return -EINVAL;
10998 	}
10999 
11000 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11001 	free(pattern);
11002 	return libbpf_get_error(*link);
11003 }
11004 
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11005 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11006 {
11007 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11008 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11009 	int n, ret = -EINVAL;
11010 
11011 	*link = NULL;
11012 
11013 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%ms",
11014 		   &probe_type, &binary_path, &func_name);
11015 	switch (n) {
11016 	case 1:
11017 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11018 		ret = 0;
11019 		break;
11020 	case 3:
11021 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11022 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11023 		ret = libbpf_get_error(*link);
11024 		break;
11025 	default:
11026 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11027 			prog->sec_name);
11028 		break;
11029 	}
11030 	free(probe_type);
11031 	free(binary_path);
11032 	free(func_name);
11033 	return ret;
11034 }
11035 
gen_uprobe_legacy_event_name(char * buf,size_t buf_sz,const char * binary_path,uint64_t offset)11036 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11037 					 const char *binary_path, uint64_t offset)
11038 {
11039 	int i;
11040 
11041 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11042 
11043 	/* sanitize binary_path in the probe name */
11044 	for (i = 0; buf[i]; i++) {
11045 		if (!isalnum(buf[i]))
11046 			buf[i] = '_';
11047 	}
11048 }
11049 
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)11050 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11051 					  const char *binary_path, size_t offset)
11052 {
11053 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11054 			      retprobe ? 'r' : 'p',
11055 			      retprobe ? "uretprobes" : "uprobes",
11056 			      probe_name, binary_path, offset);
11057 }
11058 
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)11059 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11060 {
11061 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11062 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11063 }
11064 
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)11065 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11066 {
11067 	char file[512];
11068 
11069 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11070 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11071 
11072 	return parse_uint_from_file(file, "%d\n");
11073 }
11074 
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)11075 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11076 					 const char *binary_path, size_t offset, int pid)
11077 {
11078 	const size_t attr_sz = sizeof(struct perf_event_attr);
11079 	struct perf_event_attr attr;
11080 	int type, pfd, err;
11081 
11082 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11083 	if (err < 0) {
11084 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11085 			binary_path, (size_t)offset, err);
11086 		return err;
11087 	}
11088 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11089 	if (type < 0) {
11090 		err = type;
11091 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11092 			binary_path, offset, err);
11093 		goto err_clean_legacy;
11094 	}
11095 
11096 	memset(&attr, 0, attr_sz);
11097 	attr.size = attr_sz;
11098 	attr.config = type;
11099 	attr.type = PERF_TYPE_TRACEPOINT;
11100 
11101 	pfd = syscall(__NR_perf_event_open, &attr,
11102 		      pid < 0 ? -1 : pid, /* pid */
11103 		      pid == -1 ? 0 : -1, /* cpu */
11104 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11105 	if (pfd < 0) {
11106 		err = -errno;
11107 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11108 		goto err_clean_legacy;
11109 	}
11110 	return pfd;
11111 
11112 err_clean_legacy:
11113 	/* Clear the newly added legacy uprobe_event */
11114 	remove_uprobe_event_legacy(probe_name, retprobe);
11115 	return err;
11116 }
11117 
11118 /* Find offset of function name in archive specified by path. Currently
11119  * supported are .zip files that do not compress their contents, as used on
11120  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11121  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11122  * library functions.
11123  *
11124  * An overview of the APK format specifically provided here:
11125  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11126  */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)11127 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11128 					      const char *func_name)
11129 {
11130 	struct zip_archive *archive;
11131 	struct zip_entry entry;
11132 	long ret;
11133 	Elf *elf;
11134 
11135 	archive = zip_archive_open(archive_path);
11136 	if (IS_ERR(archive)) {
11137 		ret = PTR_ERR(archive);
11138 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11139 		return ret;
11140 	}
11141 
11142 	ret = zip_archive_find_entry(archive, file_name, &entry);
11143 	if (ret) {
11144 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11145 			archive_path, ret);
11146 		goto out;
11147 	}
11148 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11149 		 (unsigned long)entry.data_offset);
11150 
11151 	if (entry.compression) {
11152 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11153 			archive_path);
11154 		ret = -LIBBPF_ERRNO__FORMAT;
11155 		goto out;
11156 	}
11157 
11158 	elf = elf_memory((void *)entry.data, entry.data_length);
11159 	if (!elf) {
11160 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11161 			elf_errmsg(-1));
11162 		ret = -LIBBPF_ERRNO__LIBELF;
11163 		goto out;
11164 	}
11165 
11166 	ret = elf_find_func_offset(elf, file_name, func_name);
11167 	if (ret > 0) {
11168 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11169 			 func_name, file_name, archive_path, entry.data_offset, ret,
11170 			 ret + entry.data_offset);
11171 		ret += entry.data_offset;
11172 	}
11173 	elf_end(elf);
11174 
11175 out:
11176 	zip_archive_close(archive);
11177 	return ret;
11178 }
11179 
arch_specific_lib_paths(void)11180 static const char *arch_specific_lib_paths(void)
11181 {
11182 	/*
11183 	 * Based on https://packages.debian.org/sid/libc6.
11184 	 *
11185 	 * Assume that the traced program is built for the same architecture
11186 	 * as libbpf, which should cover the vast majority of cases.
11187 	 */
11188 #if defined(__x86_64__)
11189 	return "/lib/x86_64-linux-gnu";
11190 #elif defined(__i386__)
11191 	return "/lib/i386-linux-gnu";
11192 #elif defined(__s390x__)
11193 	return "/lib/s390x-linux-gnu";
11194 #elif defined(__s390__)
11195 	return "/lib/s390-linux-gnu";
11196 #elif defined(__arm__) && defined(__SOFTFP__)
11197 	return "/lib/arm-linux-gnueabi";
11198 #elif defined(__arm__) && !defined(__SOFTFP__)
11199 	return "/lib/arm-linux-gnueabihf";
11200 #elif defined(__aarch64__)
11201 	return "/lib/aarch64-linux-gnu";
11202 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11203 	return "/lib/mips64el-linux-gnuabi64";
11204 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11205 	return "/lib/mipsel-linux-gnu";
11206 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11207 	return "/lib/powerpc64le-linux-gnu";
11208 #elif defined(__sparc__) && defined(__arch64__)
11209 	return "/lib/sparc64-linux-gnu";
11210 #elif defined(__riscv) && __riscv_xlen == 64
11211 	return "/lib/riscv64-linux-gnu";
11212 #else
11213 	return NULL;
11214 #endif
11215 }
11216 
11217 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)11218 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11219 {
11220 	const char *search_paths[3] = {};
11221 	int i, perm;
11222 
11223 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11224 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11225 		search_paths[1] = "/usr/lib64:/usr/lib";
11226 		search_paths[2] = arch_specific_lib_paths();
11227 		perm = R_OK;
11228 	} else {
11229 		search_paths[0] = getenv("PATH");
11230 		search_paths[1] = "/usr/bin:/usr/sbin";
11231 		perm = R_OK | X_OK;
11232 	}
11233 
11234 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11235 		const char *s;
11236 
11237 		if (!search_paths[i])
11238 			continue;
11239 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11240 			char *next_path;
11241 			int seg_len;
11242 
11243 			if (s[0] == ':')
11244 				s++;
11245 			next_path = strchr(s, ':');
11246 			seg_len = next_path ? next_path - s : strlen(s);
11247 			if (!seg_len)
11248 				continue;
11249 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11250 			/* ensure it has required permissions */
11251 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11252 				continue;
11253 			pr_debug("resolved '%s' to '%s'\n", file, result);
11254 			return 0;
11255 		}
11256 	}
11257 	return -ENOENT;
11258 }
11259 
11260 struct bpf_link *
bpf_program__attach_uprobe_multi(const struct bpf_program * prog,pid_t pid,const char * path,const char * func_pattern,const struct bpf_uprobe_multi_opts * opts)11261 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11262 				 pid_t pid,
11263 				 const char *path,
11264 				 const char *func_pattern,
11265 				 const struct bpf_uprobe_multi_opts *opts)
11266 {
11267 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11268 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11269 	unsigned long *resolved_offsets = NULL;
11270 	int err = 0, link_fd, prog_fd;
11271 	struct bpf_link *link = NULL;
11272 	char errmsg[STRERR_BUFSIZE];
11273 	char full_path[PATH_MAX];
11274 	const __u64 *cookies;
11275 	const char **syms;
11276 	size_t cnt;
11277 
11278 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11279 		return libbpf_err_ptr(-EINVAL);
11280 
11281 	syms = OPTS_GET(opts, syms, NULL);
11282 	offsets = OPTS_GET(opts, offsets, NULL);
11283 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11284 	cookies = OPTS_GET(opts, cookies, NULL);
11285 	cnt = OPTS_GET(opts, cnt, 0);
11286 
11287 	/*
11288 	 * User can specify 2 mutually exclusive set of inputs:
11289 	 *
11290 	 * 1) use only path/func_pattern/pid arguments
11291 	 *
11292 	 * 2) use path/pid with allowed combinations of:
11293 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11294 	 *
11295 	 *    - syms and offsets are mutually exclusive
11296 	 *    - ref_ctr_offsets and cookies are optional
11297 	 *
11298 	 * Any other usage results in error.
11299 	 */
11300 
11301 	if (!path)
11302 		return libbpf_err_ptr(-EINVAL);
11303 	if (!func_pattern && cnt == 0)
11304 		return libbpf_err_ptr(-EINVAL);
11305 
11306 	if (func_pattern) {
11307 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11308 			return libbpf_err_ptr(-EINVAL);
11309 	} else {
11310 		if (!!syms == !!offsets)
11311 			return libbpf_err_ptr(-EINVAL);
11312 	}
11313 
11314 	if (func_pattern) {
11315 		if (!strchr(path, '/')) {
11316 			err = resolve_full_path(path, full_path, sizeof(full_path));
11317 			if (err) {
11318 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11319 					prog->name, path, err);
11320 				return libbpf_err_ptr(err);
11321 			}
11322 			path = full_path;
11323 		}
11324 
11325 		err = elf_resolve_pattern_offsets(path, func_pattern,
11326 						  &resolved_offsets, &cnt);
11327 		if (err < 0)
11328 			return libbpf_err_ptr(err);
11329 		offsets = resolved_offsets;
11330 	} else if (syms) {
11331 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11332 		if (err < 0)
11333 			return libbpf_err_ptr(err);
11334 		offsets = resolved_offsets;
11335 	}
11336 
11337 	lopts.uprobe_multi.path = path;
11338 	lopts.uprobe_multi.offsets = offsets;
11339 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11340 	lopts.uprobe_multi.cookies = cookies;
11341 	lopts.uprobe_multi.cnt = cnt;
11342 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11343 
11344 	if (pid == 0)
11345 		pid = getpid();
11346 	if (pid > 0)
11347 		lopts.uprobe_multi.pid = pid;
11348 
11349 	link = calloc(1, sizeof(*link));
11350 	if (!link) {
11351 		err = -ENOMEM;
11352 		goto error;
11353 	}
11354 	link->detach = &bpf_link__detach_fd;
11355 
11356 	prog_fd = bpf_program__fd(prog);
11357 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11358 	if (link_fd < 0) {
11359 		err = -errno;
11360 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11361 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11362 		goto error;
11363 	}
11364 	link->fd = link_fd;
11365 	free(resolved_offsets);
11366 	return link;
11367 
11368 error:
11369 	free(resolved_offsets);
11370 	free(link);
11371 	return libbpf_err_ptr(err);
11372 }
11373 
11374 LIBBPF_API struct bpf_link *
bpf_program__attach_uprobe_opts(const struct bpf_program * prog,pid_t pid,const char * binary_path,size_t func_offset,const struct bpf_uprobe_opts * opts)11375 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11376 				const char *binary_path, size_t func_offset,
11377 				const struct bpf_uprobe_opts *opts)
11378 {
11379 	const char *archive_path = NULL, *archive_sep = NULL;
11380 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11381 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11382 	enum probe_attach_mode attach_mode;
11383 	char full_path[PATH_MAX];
11384 	struct bpf_link *link;
11385 	size_t ref_ctr_off;
11386 	int pfd, err;
11387 	bool retprobe, legacy;
11388 	const char *func_name;
11389 
11390 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11391 		return libbpf_err_ptr(-EINVAL);
11392 
11393 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11394 	retprobe = OPTS_GET(opts, retprobe, false);
11395 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11396 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11397 
11398 	if (!binary_path)
11399 		return libbpf_err_ptr(-EINVAL);
11400 
11401 	/* Check if "binary_path" refers to an archive. */
11402 	archive_sep = strstr(binary_path, "!/");
11403 	if (archive_sep) {
11404 		full_path[0] = '\0';
11405 		libbpf_strlcpy(full_path, binary_path,
11406 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11407 		archive_path = full_path;
11408 		binary_path = archive_sep + 2;
11409 	} else if (!strchr(binary_path, '/')) {
11410 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11411 		if (err) {
11412 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11413 				prog->name, binary_path, err);
11414 			return libbpf_err_ptr(err);
11415 		}
11416 		binary_path = full_path;
11417 	}
11418 	func_name = OPTS_GET(opts, func_name, NULL);
11419 	if (func_name) {
11420 		long sym_off;
11421 
11422 		if (archive_path) {
11423 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11424 								    func_name);
11425 			binary_path = archive_path;
11426 		} else {
11427 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11428 		}
11429 		if (sym_off < 0)
11430 			return libbpf_err_ptr(sym_off);
11431 		func_offset += sym_off;
11432 	}
11433 
11434 	legacy = determine_uprobe_perf_type() < 0;
11435 	switch (attach_mode) {
11436 	case PROBE_ATTACH_MODE_LEGACY:
11437 		legacy = true;
11438 		pe_opts.force_ioctl_attach = true;
11439 		break;
11440 	case PROBE_ATTACH_MODE_PERF:
11441 		if (legacy)
11442 			return libbpf_err_ptr(-ENOTSUP);
11443 		pe_opts.force_ioctl_attach = true;
11444 		break;
11445 	case PROBE_ATTACH_MODE_LINK:
11446 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11447 			return libbpf_err_ptr(-ENOTSUP);
11448 		break;
11449 	case PROBE_ATTACH_MODE_DEFAULT:
11450 		break;
11451 	default:
11452 		return libbpf_err_ptr(-EINVAL);
11453 	}
11454 
11455 	if (!legacy) {
11456 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11457 					    func_offset, pid, ref_ctr_off);
11458 	} else {
11459 		char probe_name[PATH_MAX + 64];
11460 
11461 		if (ref_ctr_off)
11462 			return libbpf_err_ptr(-EINVAL);
11463 
11464 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11465 					     binary_path, func_offset);
11466 
11467 		legacy_probe = strdup(probe_name);
11468 		if (!legacy_probe)
11469 			return libbpf_err_ptr(-ENOMEM);
11470 
11471 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11472 						    binary_path, func_offset, pid);
11473 	}
11474 	if (pfd < 0) {
11475 		err = -errno;
11476 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11477 			prog->name, retprobe ? "uretprobe" : "uprobe",
11478 			binary_path, func_offset,
11479 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11480 		goto err_out;
11481 	}
11482 
11483 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11484 	err = libbpf_get_error(link);
11485 	if (err) {
11486 		close(pfd);
11487 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11488 			prog->name, retprobe ? "uretprobe" : "uprobe",
11489 			binary_path, func_offset,
11490 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11491 		goto err_clean_legacy;
11492 	}
11493 	if (legacy) {
11494 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11495 
11496 		perf_link->legacy_probe_name = legacy_probe;
11497 		perf_link->legacy_is_kprobe = false;
11498 		perf_link->legacy_is_retprobe = retprobe;
11499 	}
11500 	return link;
11501 
11502 err_clean_legacy:
11503 	if (legacy)
11504 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11505 err_out:
11506 	free(legacy_probe);
11507 	return libbpf_err_ptr(err);
11508 }
11509 
11510 /* Format of u[ret]probe section definition supporting auto-attach:
11511  * u[ret]probe/binary:function[+offset]
11512  *
11513  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11514  * full binary path via bpf_program__attach_uprobe_opts.
11515  *
11516  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11517  * specified (and auto-attach is not possible) or the above format is specified for
11518  * auto-attach.
11519  */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11520 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11521 {
11522 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11523 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11524 	int n, ret = -EINVAL;
11525 	long offset = 0;
11526 
11527 	*link = NULL;
11528 
11529 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11530 		   &probe_type, &binary_path, &func_name, &offset);
11531 	switch (n) {
11532 	case 1:
11533 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11534 		ret = 0;
11535 		break;
11536 	case 2:
11537 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11538 			prog->name, prog->sec_name);
11539 		break;
11540 	case 3:
11541 	case 4:
11542 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11543 				strcmp(probe_type, "uretprobe.s") == 0;
11544 		if (opts.retprobe && offset != 0) {
11545 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11546 				prog->name);
11547 			break;
11548 		}
11549 		opts.func_name = func_name;
11550 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11551 		ret = libbpf_get_error(*link);
11552 		break;
11553 	default:
11554 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11555 			prog->sec_name);
11556 		break;
11557 	}
11558 	free(probe_type);
11559 	free(binary_path);
11560 	free(func_name);
11561 
11562 	return ret;
11563 }
11564 
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)11565 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11566 					    bool retprobe, pid_t pid,
11567 					    const char *binary_path,
11568 					    size_t func_offset)
11569 {
11570 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11571 
11572 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11573 }
11574 
bpf_program__attach_usdt(const struct bpf_program * prog,pid_t pid,const char * binary_path,const char * usdt_provider,const char * usdt_name,const struct bpf_usdt_opts * opts)11575 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11576 					  pid_t pid, const char *binary_path,
11577 					  const char *usdt_provider, const char *usdt_name,
11578 					  const struct bpf_usdt_opts *opts)
11579 {
11580 	char resolved_path[512];
11581 	struct bpf_object *obj = prog->obj;
11582 	struct bpf_link *link;
11583 	__u64 usdt_cookie;
11584 	int err;
11585 
11586 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11587 		return libbpf_err_ptr(-EINVAL);
11588 
11589 	if (bpf_program__fd(prog) < 0) {
11590 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11591 			prog->name);
11592 		return libbpf_err_ptr(-EINVAL);
11593 	}
11594 
11595 	if (!binary_path)
11596 		return libbpf_err_ptr(-EINVAL);
11597 
11598 	if (!strchr(binary_path, '/')) {
11599 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11600 		if (err) {
11601 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11602 				prog->name, binary_path, err);
11603 			return libbpf_err_ptr(err);
11604 		}
11605 		binary_path = resolved_path;
11606 	}
11607 
11608 	/* USDT manager is instantiated lazily on first USDT attach. It will
11609 	 * be destroyed together with BPF object in bpf_object__close().
11610 	 */
11611 	if (IS_ERR(obj->usdt_man))
11612 		return libbpf_ptr(obj->usdt_man);
11613 	if (!obj->usdt_man) {
11614 		obj->usdt_man = usdt_manager_new(obj);
11615 		if (IS_ERR(obj->usdt_man))
11616 			return libbpf_ptr(obj->usdt_man);
11617 	}
11618 
11619 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11620 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11621 					usdt_provider, usdt_name, usdt_cookie);
11622 	err = libbpf_get_error(link);
11623 	if (err)
11624 		return libbpf_err_ptr(err);
11625 	return link;
11626 }
11627 
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11628 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11629 {
11630 	char *path = NULL, *provider = NULL, *name = NULL;
11631 	const char *sec_name;
11632 	int n, err;
11633 
11634 	sec_name = bpf_program__section_name(prog);
11635 	if (strcmp(sec_name, "usdt") == 0) {
11636 		/* no auto-attach for just SEC("usdt") */
11637 		*link = NULL;
11638 		return 0;
11639 	}
11640 
11641 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11642 	if (n != 3) {
11643 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11644 			sec_name);
11645 		err = -EINVAL;
11646 	} else {
11647 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11648 						 provider, name, NULL);
11649 		err = libbpf_get_error(*link);
11650 	}
11651 	free(path);
11652 	free(provider);
11653 	free(name);
11654 	return err;
11655 }
11656 
determine_tracepoint_id(const char * tp_category,const char * tp_name)11657 static int determine_tracepoint_id(const char *tp_category,
11658 				   const char *tp_name)
11659 {
11660 	char file[PATH_MAX];
11661 	int ret;
11662 
11663 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11664 		       tracefs_path(), tp_category, tp_name);
11665 	if (ret < 0)
11666 		return -errno;
11667 	if (ret >= sizeof(file)) {
11668 		pr_debug("tracepoint %s/%s path is too long\n",
11669 			 tp_category, tp_name);
11670 		return -E2BIG;
11671 	}
11672 	return parse_uint_from_file(file, "%d\n");
11673 }
11674 
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)11675 static int perf_event_open_tracepoint(const char *tp_category,
11676 				      const char *tp_name)
11677 {
11678 	const size_t attr_sz = sizeof(struct perf_event_attr);
11679 	struct perf_event_attr attr;
11680 	char errmsg[STRERR_BUFSIZE];
11681 	int tp_id, pfd, err;
11682 
11683 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11684 	if (tp_id < 0) {
11685 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11686 			tp_category, tp_name,
11687 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11688 		return tp_id;
11689 	}
11690 
11691 	memset(&attr, 0, attr_sz);
11692 	attr.type = PERF_TYPE_TRACEPOINT;
11693 	attr.size = attr_sz;
11694 	attr.config = tp_id;
11695 
11696 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11697 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11698 	if (pfd < 0) {
11699 		err = -errno;
11700 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11701 			tp_category, tp_name,
11702 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11703 		return err;
11704 	}
11705 	return pfd;
11706 }
11707 
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)11708 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11709 						     const char *tp_category,
11710 						     const char *tp_name,
11711 						     const struct bpf_tracepoint_opts *opts)
11712 {
11713 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11714 	char errmsg[STRERR_BUFSIZE];
11715 	struct bpf_link *link;
11716 	int pfd, err;
11717 
11718 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11719 		return libbpf_err_ptr(-EINVAL);
11720 
11721 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11722 
11723 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11724 	if (pfd < 0) {
11725 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11726 			prog->name, tp_category, tp_name,
11727 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11728 		return libbpf_err_ptr(pfd);
11729 	}
11730 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11731 	err = libbpf_get_error(link);
11732 	if (err) {
11733 		close(pfd);
11734 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11735 			prog->name, tp_category, tp_name,
11736 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11737 		return libbpf_err_ptr(err);
11738 	}
11739 	return link;
11740 }
11741 
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)11742 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11743 						const char *tp_category,
11744 						const char *tp_name)
11745 {
11746 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11747 }
11748 
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11749 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11750 {
11751 	char *sec_name, *tp_cat, *tp_name;
11752 
11753 	*link = NULL;
11754 
11755 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11756 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11757 		return 0;
11758 
11759 	sec_name = strdup(prog->sec_name);
11760 	if (!sec_name)
11761 		return -ENOMEM;
11762 
11763 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11764 	if (str_has_pfx(prog->sec_name, "tp/"))
11765 		tp_cat = sec_name + sizeof("tp/") - 1;
11766 	else
11767 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11768 	tp_name = strchr(tp_cat, '/');
11769 	if (!tp_name) {
11770 		free(sec_name);
11771 		return -EINVAL;
11772 	}
11773 	*tp_name = '\0';
11774 	tp_name++;
11775 
11776 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11777 	free(sec_name);
11778 	return libbpf_get_error(*link);
11779 }
11780 
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)11781 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11782 						    const char *tp_name)
11783 {
11784 	char errmsg[STRERR_BUFSIZE];
11785 	struct bpf_link *link;
11786 	int prog_fd, pfd;
11787 
11788 	prog_fd = bpf_program__fd(prog);
11789 	if (prog_fd < 0) {
11790 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11791 		return libbpf_err_ptr(-EINVAL);
11792 	}
11793 
11794 	link = calloc(1, sizeof(*link));
11795 	if (!link)
11796 		return libbpf_err_ptr(-ENOMEM);
11797 	link->detach = &bpf_link__detach_fd;
11798 
11799 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11800 	if (pfd < 0) {
11801 		pfd = -errno;
11802 		free(link);
11803 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11804 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11805 		return libbpf_err_ptr(pfd);
11806 	}
11807 	link->fd = pfd;
11808 	return link;
11809 }
11810 
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11811 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11812 {
11813 	static const char *const prefixes[] = {
11814 		"raw_tp",
11815 		"raw_tracepoint",
11816 		"raw_tp.w",
11817 		"raw_tracepoint.w",
11818 	};
11819 	size_t i;
11820 	const char *tp_name = NULL;
11821 
11822 	*link = NULL;
11823 
11824 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11825 		size_t pfx_len;
11826 
11827 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11828 			continue;
11829 
11830 		pfx_len = strlen(prefixes[i]);
11831 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11832 		if (prog->sec_name[pfx_len] == '\0')
11833 			return 0;
11834 
11835 		if (prog->sec_name[pfx_len] != '/')
11836 			continue;
11837 
11838 		tp_name = prog->sec_name + pfx_len + 1;
11839 		break;
11840 	}
11841 
11842 	if (!tp_name) {
11843 		pr_warn("prog '%s': invalid section name '%s'\n",
11844 			prog->name, prog->sec_name);
11845 		return -EINVAL;
11846 	}
11847 
11848 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11849 	return libbpf_get_error(*link);
11850 }
11851 
11852 /* Common logic for all BPF program types that attach to a btf_id */
bpf_program__attach_btf_id(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11853 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11854 						   const struct bpf_trace_opts *opts)
11855 {
11856 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11857 	char errmsg[STRERR_BUFSIZE];
11858 	struct bpf_link *link;
11859 	int prog_fd, pfd;
11860 
11861 	if (!OPTS_VALID(opts, bpf_trace_opts))
11862 		return libbpf_err_ptr(-EINVAL);
11863 
11864 	prog_fd = bpf_program__fd(prog);
11865 	if (prog_fd < 0) {
11866 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11867 		return libbpf_err_ptr(-EINVAL);
11868 	}
11869 
11870 	link = calloc(1, sizeof(*link));
11871 	if (!link)
11872 		return libbpf_err_ptr(-ENOMEM);
11873 	link->detach = &bpf_link__detach_fd;
11874 
11875 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11876 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11877 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11878 	if (pfd < 0) {
11879 		pfd = -errno;
11880 		free(link);
11881 		pr_warn("prog '%s': failed to attach: %s\n",
11882 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11883 		return libbpf_err_ptr(pfd);
11884 	}
11885 	link->fd = pfd;
11886 	return link;
11887 }
11888 
bpf_program__attach_trace(const struct bpf_program * prog)11889 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11890 {
11891 	return bpf_program__attach_btf_id(prog, NULL);
11892 }
11893 
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11894 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11895 						const struct bpf_trace_opts *opts)
11896 {
11897 	return bpf_program__attach_btf_id(prog, opts);
11898 }
11899 
bpf_program__attach_lsm(const struct bpf_program * prog)11900 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11901 {
11902 	return bpf_program__attach_btf_id(prog, NULL);
11903 }
11904 
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11905 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11906 {
11907 	*link = bpf_program__attach_trace(prog);
11908 	return libbpf_get_error(*link);
11909 }
11910 
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11911 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11912 {
11913 	*link = bpf_program__attach_lsm(prog);
11914 	return libbpf_get_error(*link);
11915 }
11916 
11917 static struct bpf_link *
bpf_program_attach_fd(const struct bpf_program * prog,int target_fd,const char * target_name,const struct bpf_link_create_opts * opts)11918 bpf_program_attach_fd(const struct bpf_program *prog,
11919 		      int target_fd, const char *target_name,
11920 		      const struct bpf_link_create_opts *opts)
11921 {
11922 	enum bpf_attach_type attach_type;
11923 	char errmsg[STRERR_BUFSIZE];
11924 	struct bpf_link *link;
11925 	int prog_fd, link_fd;
11926 
11927 	prog_fd = bpf_program__fd(prog);
11928 	if (prog_fd < 0) {
11929 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11930 		return libbpf_err_ptr(-EINVAL);
11931 	}
11932 
11933 	link = calloc(1, sizeof(*link));
11934 	if (!link)
11935 		return libbpf_err_ptr(-ENOMEM);
11936 	link->detach = &bpf_link__detach_fd;
11937 
11938 	attach_type = bpf_program__expected_attach_type(prog);
11939 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
11940 	if (link_fd < 0) {
11941 		link_fd = -errno;
11942 		free(link);
11943 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11944 			prog->name, target_name,
11945 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11946 		return libbpf_err_ptr(link_fd);
11947 	}
11948 	link->fd = link_fd;
11949 	return link;
11950 }
11951 
11952 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)11953 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11954 {
11955 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
11956 }
11957 
11958 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)11959 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11960 {
11961 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
11962 }
11963 
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)11964 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11965 {
11966 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11967 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
11968 }
11969 
11970 struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)11971 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
11972 			const struct bpf_tcx_opts *opts)
11973 {
11974 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11975 	__u32 relative_id;
11976 	int relative_fd;
11977 
11978 	if (!OPTS_VALID(opts, bpf_tcx_opts))
11979 		return libbpf_err_ptr(-EINVAL);
11980 
11981 	relative_id = OPTS_GET(opts, relative_id, 0);
11982 	relative_fd = OPTS_GET(opts, relative_fd, 0);
11983 
11984 	/* validate we don't have unexpected combinations of non-zero fields */
11985 	if (!ifindex) {
11986 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
11987 			prog->name);
11988 		return libbpf_err_ptr(-EINVAL);
11989 	}
11990 	if (relative_fd && relative_id) {
11991 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
11992 			prog->name);
11993 		return libbpf_err_ptr(-EINVAL);
11994 	}
11995 
11996 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
11997 	link_create_opts.tcx.relative_fd = relative_fd;
11998 	link_create_opts.tcx.relative_id = relative_id;
11999 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12000 
12001 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12002 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12003 }
12004 
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)12005 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12006 					      int target_fd,
12007 					      const char *attach_func_name)
12008 {
12009 	int btf_id;
12010 
12011 	if (!!target_fd != !!attach_func_name) {
12012 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12013 			prog->name);
12014 		return libbpf_err_ptr(-EINVAL);
12015 	}
12016 
12017 	if (prog->type != BPF_PROG_TYPE_EXT) {
12018 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12019 			prog->name);
12020 		return libbpf_err_ptr(-EINVAL);
12021 	}
12022 
12023 	if (target_fd) {
12024 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12025 
12026 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12027 		if (btf_id < 0)
12028 			return libbpf_err_ptr(btf_id);
12029 
12030 		target_opts.target_btf_id = btf_id;
12031 
12032 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12033 					     &target_opts);
12034 	} else {
12035 		/* no target, so use raw_tracepoint_open for compatibility
12036 		 * with old kernels
12037 		 */
12038 		return bpf_program__attach_trace(prog);
12039 	}
12040 }
12041 
12042 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)12043 bpf_program__attach_iter(const struct bpf_program *prog,
12044 			 const struct bpf_iter_attach_opts *opts)
12045 {
12046 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12047 	char errmsg[STRERR_BUFSIZE];
12048 	struct bpf_link *link;
12049 	int prog_fd, link_fd;
12050 	__u32 target_fd = 0;
12051 
12052 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12053 		return libbpf_err_ptr(-EINVAL);
12054 
12055 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12056 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12057 
12058 	prog_fd = bpf_program__fd(prog);
12059 	if (prog_fd < 0) {
12060 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12061 		return libbpf_err_ptr(-EINVAL);
12062 	}
12063 
12064 	link = calloc(1, sizeof(*link));
12065 	if (!link)
12066 		return libbpf_err_ptr(-ENOMEM);
12067 	link->detach = &bpf_link__detach_fd;
12068 
12069 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12070 				  &link_create_opts);
12071 	if (link_fd < 0) {
12072 		link_fd = -errno;
12073 		free(link);
12074 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12075 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12076 		return libbpf_err_ptr(link_fd);
12077 	}
12078 	link->fd = link_fd;
12079 	return link;
12080 }
12081 
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12082 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12083 {
12084 	*link = bpf_program__attach_iter(prog, NULL);
12085 	return libbpf_get_error(*link);
12086 }
12087 
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)12088 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12089 					       const struct bpf_netfilter_opts *opts)
12090 {
12091 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12092 	struct bpf_link *link;
12093 	int prog_fd, link_fd;
12094 
12095 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12096 		return libbpf_err_ptr(-EINVAL);
12097 
12098 	prog_fd = bpf_program__fd(prog);
12099 	if (prog_fd < 0) {
12100 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12101 		return libbpf_err_ptr(-EINVAL);
12102 	}
12103 
12104 	link = calloc(1, sizeof(*link));
12105 	if (!link)
12106 		return libbpf_err_ptr(-ENOMEM);
12107 
12108 	link->detach = &bpf_link__detach_fd;
12109 
12110 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12111 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12112 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12113 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12114 
12115 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12116 	if (link_fd < 0) {
12117 		char errmsg[STRERR_BUFSIZE];
12118 
12119 		link_fd = -errno;
12120 		free(link);
12121 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12122 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12123 		return libbpf_err_ptr(link_fd);
12124 	}
12125 	link->fd = link_fd;
12126 
12127 	return link;
12128 }
12129 
bpf_program__attach(const struct bpf_program * prog)12130 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12131 {
12132 	struct bpf_link *link = NULL;
12133 	int err;
12134 
12135 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12136 		return libbpf_err_ptr(-EOPNOTSUPP);
12137 
12138 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12139 	if (err)
12140 		return libbpf_err_ptr(err);
12141 
12142 	/* When calling bpf_program__attach() explicitly, auto-attach support
12143 	 * is expected to work, so NULL returned link is considered an error.
12144 	 * This is different for skeleton's attach, see comment in
12145 	 * bpf_object__attach_skeleton().
12146 	 */
12147 	if (!link)
12148 		return libbpf_err_ptr(-EOPNOTSUPP);
12149 
12150 	return link;
12151 }
12152 
12153 struct bpf_link_struct_ops {
12154 	struct bpf_link link;
12155 	int map_fd;
12156 };
12157 
bpf_link__detach_struct_ops(struct bpf_link * link)12158 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12159 {
12160 	struct bpf_link_struct_ops *st_link;
12161 	__u32 zero = 0;
12162 
12163 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12164 
12165 	if (st_link->map_fd < 0)
12166 		/* w/o a real link */
12167 		return bpf_map_delete_elem(link->fd, &zero);
12168 
12169 	return close(link->fd);
12170 }
12171 
bpf_map__attach_struct_ops(const struct bpf_map * map)12172 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12173 {
12174 	struct bpf_link_struct_ops *link;
12175 	__u32 zero = 0;
12176 	int err, fd;
12177 
12178 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12179 		return libbpf_err_ptr(-EINVAL);
12180 
12181 	link = calloc(1, sizeof(*link));
12182 	if (!link)
12183 		return libbpf_err_ptr(-EINVAL);
12184 
12185 	/* kern_vdata should be prepared during the loading phase. */
12186 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12187 	/* It can be EBUSY if the map has been used to create or
12188 	 * update a link before.  We don't allow updating the value of
12189 	 * a struct_ops once it is set.  That ensures that the value
12190 	 * never changed.  So, it is safe to skip EBUSY.
12191 	 */
12192 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12193 		free(link);
12194 		return libbpf_err_ptr(err);
12195 	}
12196 
12197 	link->link.detach = bpf_link__detach_struct_ops;
12198 
12199 	if (!(map->def.map_flags & BPF_F_LINK)) {
12200 		/* w/o a real link */
12201 		link->link.fd = map->fd;
12202 		link->map_fd = -1;
12203 		return &link->link;
12204 	}
12205 
12206 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12207 	if (fd < 0) {
12208 		free(link);
12209 		return libbpf_err_ptr(fd);
12210 	}
12211 
12212 	link->link.fd = fd;
12213 	link->map_fd = map->fd;
12214 
12215 	return &link->link;
12216 }
12217 
12218 /*
12219  * Swap the back struct_ops of a link with a new struct_ops map.
12220  */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)12221 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12222 {
12223 	struct bpf_link_struct_ops *st_ops_link;
12224 	__u32 zero = 0;
12225 	int err;
12226 
12227 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12228 		return -EINVAL;
12229 
12230 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12231 	/* Ensure the type of a link is correct */
12232 	if (st_ops_link->map_fd < 0)
12233 		return -EINVAL;
12234 
12235 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12236 	/* It can be EBUSY if the map has been used to create or
12237 	 * update a link before.  We don't allow updating the value of
12238 	 * a struct_ops once it is set.  That ensures that the value
12239 	 * never changed.  So, it is safe to skip EBUSY.
12240 	 */
12241 	if (err && err != -EBUSY)
12242 		return err;
12243 
12244 	err = bpf_link_update(link->fd, map->fd, NULL);
12245 	if (err < 0)
12246 		return err;
12247 
12248 	st_ops_link->map_fd = map->fd;
12249 
12250 	return 0;
12251 }
12252 
12253 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12254 							  void *private_data);
12255 
12256 static enum bpf_perf_event_ret
12257 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12258 		       void **copy_mem, size_t *copy_size,
12259 		       bpf_perf_event_print_t fn, void *private_data)
12260 {
12261 	struct perf_event_mmap_page *header = mmap_mem;
12262 	__u64 data_head = ring_buffer_read_head(header);
12263 	__u64 data_tail = header->data_tail;
12264 	void *base = ((__u8 *)header) + page_size;
12265 	int ret = LIBBPF_PERF_EVENT_CONT;
12266 	struct perf_event_header *ehdr;
12267 	size_t ehdr_size;
12268 
12269 	while (data_head != data_tail) {
12270 		ehdr = base + (data_tail & (mmap_size - 1));
12271 		ehdr_size = ehdr->size;
12272 
12273 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12274 			void *copy_start = ehdr;
12275 			size_t len_first = base + mmap_size - copy_start;
12276 			size_t len_secnd = ehdr_size - len_first;
12277 
12278 			if (*copy_size < ehdr_size) {
12279 				free(*copy_mem);
12280 				*copy_mem = malloc(ehdr_size);
12281 				if (!*copy_mem) {
12282 					*copy_size = 0;
12283 					ret = LIBBPF_PERF_EVENT_ERROR;
12284 					break;
12285 				}
12286 				*copy_size = ehdr_size;
12287 			}
12288 
12289 			memcpy(*copy_mem, copy_start, len_first);
12290 			memcpy(*copy_mem + len_first, base, len_secnd);
12291 			ehdr = *copy_mem;
12292 		}
12293 
12294 		ret = fn(ehdr, private_data);
12295 		data_tail += ehdr_size;
12296 		if (ret != LIBBPF_PERF_EVENT_CONT)
12297 			break;
12298 	}
12299 
12300 	ring_buffer_write_tail(header, data_tail);
12301 	return libbpf_err(ret);
12302 }
12303 
12304 struct perf_buffer;
12305 
12306 struct perf_buffer_params {
12307 	struct perf_event_attr *attr;
12308 	/* if event_cb is specified, it takes precendence */
12309 	perf_buffer_event_fn event_cb;
12310 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12311 	perf_buffer_sample_fn sample_cb;
12312 	perf_buffer_lost_fn lost_cb;
12313 	void *ctx;
12314 	int cpu_cnt;
12315 	int *cpus;
12316 	int *map_keys;
12317 };
12318 
12319 struct perf_cpu_buf {
12320 	struct perf_buffer *pb;
12321 	void *base; /* mmap()'ed memory */
12322 	void *buf; /* for reconstructing segmented data */
12323 	size_t buf_size;
12324 	int fd;
12325 	int cpu;
12326 	int map_key;
12327 };
12328 
12329 struct perf_buffer {
12330 	perf_buffer_event_fn event_cb;
12331 	perf_buffer_sample_fn sample_cb;
12332 	perf_buffer_lost_fn lost_cb;
12333 	void *ctx; /* passed into callbacks */
12334 
12335 	size_t page_size;
12336 	size_t mmap_size;
12337 	struct perf_cpu_buf **cpu_bufs;
12338 	struct epoll_event *events;
12339 	int cpu_cnt; /* number of allocated CPU buffers */
12340 	int epoll_fd; /* perf event FD */
12341 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12342 };
12343 
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12344 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12345 				      struct perf_cpu_buf *cpu_buf)
12346 {
12347 	if (!cpu_buf)
12348 		return;
12349 	if (cpu_buf->base &&
12350 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12351 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12352 	if (cpu_buf->fd >= 0) {
12353 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12354 		close(cpu_buf->fd);
12355 	}
12356 	free(cpu_buf->buf);
12357 	free(cpu_buf);
12358 }
12359 
perf_buffer__free(struct perf_buffer * pb)12360 void perf_buffer__free(struct perf_buffer *pb)
12361 {
12362 	int i;
12363 
12364 	if (IS_ERR_OR_NULL(pb))
12365 		return;
12366 	if (pb->cpu_bufs) {
12367 		for (i = 0; i < pb->cpu_cnt; i++) {
12368 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12369 
12370 			if (!cpu_buf)
12371 				continue;
12372 
12373 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12374 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12375 		}
12376 		free(pb->cpu_bufs);
12377 	}
12378 	if (pb->epoll_fd >= 0)
12379 		close(pb->epoll_fd);
12380 	free(pb->events);
12381 	free(pb);
12382 }
12383 
12384 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)12385 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12386 			  int cpu, int map_key)
12387 {
12388 	struct perf_cpu_buf *cpu_buf;
12389 	char msg[STRERR_BUFSIZE];
12390 	int err;
12391 
12392 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12393 	if (!cpu_buf)
12394 		return ERR_PTR(-ENOMEM);
12395 
12396 	cpu_buf->pb = pb;
12397 	cpu_buf->cpu = cpu;
12398 	cpu_buf->map_key = map_key;
12399 
12400 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12401 			      -1, PERF_FLAG_FD_CLOEXEC);
12402 	if (cpu_buf->fd < 0) {
12403 		err = -errno;
12404 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12405 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12406 		goto error;
12407 	}
12408 
12409 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12410 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12411 			     cpu_buf->fd, 0);
12412 	if (cpu_buf->base == MAP_FAILED) {
12413 		cpu_buf->base = NULL;
12414 		err = -errno;
12415 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12416 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12417 		goto error;
12418 	}
12419 
12420 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12421 		err = -errno;
12422 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12423 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12424 		goto error;
12425 	}
12426 
12427 	return cpu_buf;
12428 
12429 error:
12430 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12431 	return (struct perf_cpu_buf *)ERR_PTR(err);
12432 }
12433 
12434 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12435 					      struct perf_buffer_params *p);
12436 
perf_buffer__new(int map_fd,size_t page_cnt,perf_buffer_sample_fn sample_cb,perf_buffer_lost_fn lost_cb,void * ctx,const struct perf_buffer_opts * opts)12437 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12438 				     perf_buffer_sample_fn sample_cb,
12439 				     perf_buffer_lost_fn lost_cb,
12440 				     void *ctx,
12441 				     const struct perf_buffer_opts *opts)
12442 {
12443 	const size_t attr_sz = sizeof(struct perf_event_attr);
12444 	struct perf_buffer_params p = {};
12445 	struct perf_event_attr attr;
12446 	__u32 sample_period;
12447 
12448 	if (!OPTS_VALID(opts, perf_buffer_opts))
12449 		return libbpf_err_ptr(-EINVAL);
12450 
12451 	sample_period = OPTS_GET(opts, sample_period, 1);
12452 	if (!sample_period)
12453 		sample_period = 1;
12454 
12455 	memset(&attr, 0, attr_sz);
12456 	attr.size = attr_sz;
12457 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12458 	attr.type = PERF_TYPE_SOFTWARE;
12459 	attr.sample_type = PERF_SAMPLE_RAW;
12460 	attr.wakeup_events = sample_period;
12461 
12462 	p.attr = &attr;
12463 	p.sample_cb = sample_cb;
12464 	p.lost_cb = lost_cb;
12465 	p.ctx = ctx;
12466 
12467 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12468 }
12469 
perf_buffer__new_raw(int map_fd,size_t page_cnt,struct perf_event_attr * attr,perf_buffer_event_fn event_cb,void * ctx,const struct perf_buffer_raw_opts * opts)12470 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12471 					 struct perf_event_attr *attr,
12472 					 perf_buffer_event_fn event_cb, void *ctx,
12473 					 const struct perf_buffer_raw_opts *opts)
12474 {
12475 	struct perf_buffer_params p = {};
12476 
12477 	if (!attr)
12478 		return libbpf_err_ptr(-EINVAL);
12479 
12480 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12481 		return libbpf_err_ptr(-EINVAL);
12482 
12483 	p.attr = attr;
12484 	p.event_cb = event_cb;
12485 	p.ctx = ctx;
12486 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12487 	p.cpus = OPTS_GET(opts, cpus, NULL);
12488 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12489 
12490 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12491 }
12492 
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)12493 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12494 					      struct perf_buffer_params *p)
12495 {
12496 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12497 	struct bpf_map_info map;
12498 	char msg[STRERR_BUFSIZE];
12499 	struct perf_buffer *pb;
12500 	bool *online = NULL;
12501 	__u32 map_info_len;
12502 	int err, i, j, n;
12503 
12504 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12505 		pr_warn("page count should be power of two, but is %zu\n",
12506 			page_cnt);
12507 		return ERR_PTR(-EINVAL);
12508 	}
12509 
12510 	/* best-effort sanity checks */
12511 	memset(&map, 0, sizeof(map));
12512 	map_info_len = sizeof(map);
12513 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12514 	if (err) {
12515 		err = -errno;
12516 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12517 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12518 		 */
12519 		if (err != -EINVAL) {
12520 			pr_warn("failed to get map info for map FD %d: %s\n",
12521 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12522 			return ERR_PTR(err);
12523 		}
12524 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12525 			 map_fd);
12526 	} else {
12527 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12528 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12529 				map.name);
12530 			return ERR_PTR(-EINVAL);
12531 		}
12532 	}
12533 
12534 	pb = calloc(1, sizeof(*pb));
12535 	if (!pb)
12536 		return ERR_PTR(-ENOMEM);
12537 
12538 	pb->event_cb = p->event_cb;
12539 	pb->sample_cb = p->sample_cb;
12540 	pb->lost_cb = p->lost_cb;
12541 	pb->ctx = p->ctx;
12542 
12543 	pb->page_size = getpagesize();
12544 	pb->mmap_size = pb->page_size * page_cnt;
12545 	pb->map_fd = map_fd;
12546 
12547 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12548 	if (pb->epoll_fd < 0) {
12549 		err = -errno;
12550 		pr_warn("failed to create epoll instance: %s\n",
12551 			libbpf_strerror_r(err, msg, sizeof(msg)));
12552 		goto error;
12553 	}
12554 
12555 	if (p->cpu_cnt > 0) {
12556 		pb->cpu_cnt = p->cpu_cnt;
12557 	} else {
12558 		pb->cpu_cnt = libbpf_num_possible_cpus();
12559 		if (pb->cpu_cnt < 0) {
12560 			err = pb->cpu_cnt;
12561 			goto error;
12562 		}
12563 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12564 			pb->cpu_cnt = map.max_entries;
12565 	}
12566 
12567 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12568 	if (!pb->events) {
12569 		err = -ENOMEM;
12570 		pr_warn("failed to allocate events: out of memory\n");
12571 		goto error;
12572 	}
12573 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12574 	if (!pb->cpu_bufs) {
12575 		err = -ENOMEM;
12576 		pr_warn("failed to allocate buffers: out of memory\n");
12577 		goto error;
12578 	}
12579 
12580 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12581 	if (err) {
12582 		pr_warn("failed to get online CPU mask: %d\n", err);
12583 		goto error;
12584 	}
12585 
12586 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12587 		struct perf_cpu_buf *cpu_buf;
12588 		int cpu, map_key;
12589 
12590 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12591 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12592 
12593 		/* in case user didn't explicitly requested particular CPUs to
12594 		 * be attached to, skip offline/not present CPUs
12595 		 */
12596 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12597 			continue;
12598 
12599 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12600 		if (IS_ERR(cpu_buf)) {
12601 			err = PTR_ERR(cpu_buf);
12602 			goto error;
12603 		}
12604 
12605 		pb->cpu_bufs[j] = cpu_buf;
12606 
12607 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12608 					  &cpu_buf->fd, 0);
12609 		if (err) {
12610 			err = -errno;
12611 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12612 				cpu, map_key, cpu_buf->fd,
12613 				libbpf_strerror_r(err, msg, sizeof(msg)));
12614 			goto error;
12615 		}
12616 
12617 		pb->events[j].events = EPOLLIN;
12618 		pb->events[j].data.ptr = cpu_buf;
12619 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12620 			      &pb->events[j]) < 0) {
12621 			err = -errno;
12622 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12623 				cpu, cpu_buf->fd,
12624 				libbpf_strerror_r(err, msg, sizeof(msg)));
12625 			goto error;
12626 		}
12627 		j++;
12628 	}
12629 	pb->cpu_cnt = j;
12630 	free(online);
12631 
12632 	return pb;
12633 
12634 error:
12635 	free(online);
12636 	if (pb)
12637 		perf_buffer__free(pb);
12638 	return ERR_PTR(err);
12639 }
12640 
12641 struct perf_sample_raw {
12642 	struct perf_event_header header;
12643 	uint32_t size;
12644 	char data[];
12645 };
12646 
12647 struct perf_sample_lost {
12648 	struct perf_event_header header;
12649 	uint64_t id;
12650 	uint64_t lost;
12651 	uint64_t sample_id;
12652 };
12653 
12654 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)12655 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12656 {
12657 	struct perf_cpu_buf *cpu_buf = ctx;
12658 	struct perf_buffer *pb = cpu_buf->pb;
12659 	void *data = e;
12660 
12661 	/* user wants full control over parsing perf event */
12662 	if (pb->event_cb)
12663 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12664 
12665 	switch (e->type) {
12666 	case PERF_RECORD_SAMPLE: {
12667 		struct perf_sample_raw *s = data;
12668 
12669 		if (pb->sample_cb)
12670 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12671 		break;
12672 	}
12673 	case PERF_RECORD_LOST: {
12674 		struct perf_sample_lost *s = data;
12675 
12676 		if (pb->lost_cb)
12677 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12678 		break;
12679 	}
12680 	default:
12681 		pr_warn("unknown perf sample type %d\n", e->type);
12682 		return LIBBPF_PERF_EVENT_ERROR;
12683 	}
12684 	return LIBBPF_PERF_EVENT_CONT;
12685 }
12686 
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12687 static int perf_buffer__process_records(struct perf_buffer *pb,
12688 					struct perf_cpu_buf *cpu_buf)
12689 {
12690 	enum bpf_perf_event_ret ret;
12691 
12692 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12693 				     pb->page_size, &cpu_buf->buf,
12694 				     &cpu_buf->buf_size,
12695 				     perf_buffer__process_record, cpu_buf);
12696 	if (ret != LIBBPF_PERF_EVENT_CONT)
12697 		return ret;
12698 	return 0;
12699 }
12700 
perf_buffer__epoll_fd(const struct perf_buffer * pb)12701 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12702 {
12703 	return pb->epoll_fd;
12704 }
12705 
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)12706 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12707 {
12708 	int i, cnt, err;
12709 
12710 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12711 	if (cnt < 0)
12712 		return -errno;
12713 
12714 	for (i = 0; i < cnt; i++) {
12715 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12716 
12717 		err = perf_buffer__process_records(pb, cpu_buf);
12718 		if (err) {
12719 			pr_warn("error while processing records: %d\n", err);
12720 			return libbpf_err(err);
12721 		}
12722 	}
12723 	return cnt;
12724 }
12725 
12726 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12727  * manager.
12728  */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)12729 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12730 {
12731 	return pb->cpu_cnt;
12732 }
12733 
12734 /*
12735  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12736  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12737  * select()/poll()/epoll() Linux syscalls.
12738  */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)12739 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12740 {
12741 	struct perf_cpu_buf *cpu_buf;
12742 
12743 	if (buf_idx >= pb->cpu_cnt)
12744 		return libbpf_err(-EINVAL);
12745 
12746 	cpu_buf = pb->cpu_bufs[buf_idx];
12747 	if (!cpu_buf)
12748 		return libbpf_err(-ENOENT);
12749 
12750 	return cpu_buf->fd;
12751 }
12752 
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)12753 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12754 {
12755 	struct perf_cpu_buf *cpu_buf;
12756 
12757 	if (buf_idx >= pb->cpu_cnt)
12758 		return libbpf_err(-EINVAL);
12759 
12760 	cpu_buf = pb->cpu_bufs[buf_idx];
12761 	if (!cpu_buf)
12762 		return libbpf_err(-ENOENT);
12763 
12764 	*buf = cpu_buf->base;
12765 	*buf_size = pb->mmap_size;
12766 	return 0;
12767 }
12768 
12769 /*
12770  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12771  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12772  * consume, do nothing and return success.
12773  * Returns:
12774  *   - 0 on success;
12775  *   - <0 on failure.
12776  */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)12777 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12778 {
12779 	struct perf_cpu_buf *cpu_buf;
12780 
12781 	if (buf_idx >= pb->cpu_cnt)
12782 		return libbpf_err(-EINVAL);
12783 
12784 	cpu_buf = pb->cpu_bufs[buf_idx];
12785 	if (!cpu_buf)
12786 		return libbpf_err(-ENOENT);
12787 
12788 	return perf_buffer__process_records(pb, cpu_buf);
12789 }
12790 
perf_buffer__consume(struct perf_buffer * pb)12791 int perf_buffer__consume(struct perf_buffer *pb)
12792 {
12793 	int i, err;
12794 
12795 	for (i = 0; i < pb->cpu_cnt; i++) {
12796 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12797 
12798 		if (!cpu_buf)
12799 			continue;
12800 
12801 		err = perf_buffer__process_records(pb, cpu_buf);
12802 		if (err) {
12803 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12804 			return libbpf_err(err);
12805 		}
12806 	}
12807 	return 0;
12808 }
12809 
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)12810 int bpf_program__set_attach_target(struct bpf_program *prog,
12811 				   int attach_prog_fd,
12812 				   const char *attach_func_name)
12813 {
12814 	int btf_obj_fd = 0, btf_id = 0, err;
12815 
12816 	if (!prog || attach_prog_fd < 0)
12817 		return libbpf_err(-EINVAL);
12818 
12819 	if (prog->obj->loaded)
12820 		return libbpf_err(-EINVAL);
12821 
12822 	if (attach_prog_fd && !attach_func_name) {
12823 		/* remember attach_prog_fd and let bpf_program__load() find
12824 		 * BTF ID during the program load
12825 		 */
12826 		prog->attach_prog_fd = attach_prog_fd;
12827 		return 0;
12828 	}
12829 
12830 	if (attach_prog_fd) {
12831 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12832 						 attach_prog_fd);
12833 		if (btf_id < 0)
12834 			return libbpf_err(btf_id);
12835 	} else {
12836 		if (!attach_func_name)
12837 			return libbpf_err(-EINVAL);
12838 
12839 		/* load btf_vmlinux, if not yet */
12840 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12841 		if (err)
12842 			return libbpf_err(err);
12843 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12844 					 prog->expected_attach_type,
12845 					 &btf_obj_fd, &btf_id);
12846 		if (err)
12847 			return libbpf_err(err);
12848 	}
12849 
12850 	prog->attach_btf_id = btf_id;
12851 	prog->attach_btf_obj_fd = btf_obj_fd;
12852 	prog->attach_prog_fd = attach_prog_fd;
12853 	return 0;
12854 }
12855 
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)12856 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12857 {
12858 	int err = 0, n, len, start, end = -1;
12859 	bool *tmp;
12860 
12861 	*mask = NULL;
12862 	*mask_sz = 0;
12863 
12864 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12865 	while (*s) {
12866 		if (*s == ',' || *s == '\n') {
12867 			s++;
12868 			continue;
12869 		}
12870 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12871 		if (n <= 0 || n > 2) {
12872 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12873 			err = -EINVAL;
12874 			goto cleanup;
12875 		} else if (n == 1) {
12876 			end = start;
12877 		}
12878 		if (start < 0 || start > end) {
12879 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12880 				start, end, s);
12881 			err = -EINVAL;
12882 			goto cleanup;
12883 		}
12884 		tmp = realloc(*mask, end + 1);
12885 		if (!tmp) {
12886 			err = -ENOMEM;
12887 			goto cleanup;
12888 		}
12889 		*mask = tmp;
12890 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12891 		memset(tmp + start, 1, end - start + 1);
12892 		*mask_sz = end + 1;
12893 		s += len;
12894 	}
12895 	if (!*mask_sz) {
12896 		pr_warn("Empty CPU range\n");
12897 		return -EINVAL;
12898 	}
12899 	return 0;
12900 cleanup:
12901 	free(*mask);
12902 	*mask = NULL;
12903 	return err;
12904 }
12905 
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)12906 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12907 {
12908 	int fd, err = 0, len;
12909 	char buf[128];
12910 
12911 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12912 	if (fd < 0) {
12913 		err = -errno;
12914 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12915 		return err;
12916 	}
12917 	len = read(fd, buf, sizeof(buf));
12918 	close(fd);
12919 	if (len <= 0) {
12920 		err = len ? -errno : -EINVAL;
12921 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12922 		return err;
12923 	}
12924 	if (len >= sizeof(buf)) {
12925 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12926 		return -E2BIG;
12927 	}
12928 	buf[len] = '\0';
12929 
12930 	return parse_cpu_mask_str(buf, mask, mask_sz);
12931 }
12932 
libbpf_num_possible_cpus(void)12933 int libbpf_num_possible_cpus(void)
12934 {
12935 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12936 	static int cpus;
12937 	int err, n, i, tmp_cpus;
12938 	bool *mask;
12939 
12940 	tmp_cpus = READ_ONCE(cpus);
12941 	if (tmp_cpus > 0)
12942 		return tmp_cpus;
12943 
12944 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12945 	if (err)
12946 		return libbpf_err(err);
12947 
12948 	tmp_cpus = 0;
12949 	for (i = 0; i < n; i++) {
12950 		if (mask[i])
12951 			tmp_cpus++;
12952 	}
12953 	free(mask);
12954 
12955 	WRITE_ONCE(cpus, tmp_cpus);
12956 	return tmp_cpus;
12957 }
12958 
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt)12959 static int populate_skeleton_maps(const struct bpf_object *obj,
12960 				  struct bpf_map_skeleton *maps,
12961 				  size_t map_cnt)
12962 {
12963 	int i;
12964 
12965 	for (i = 0; i < map_cnt; i++) {
12966 		struct bpf_map **map = maps[i].map;
12967 		const char *name = maps[i].name;
12968 		void **mmaped = maps[i].mmaped;
12969 
12970 		*map = bpf_object__find_map_by_name(obj, name);
12971 		if (!*map) {
12972 			pr_warn("failed to find skeleton map '%s'\n", name);
12973 			return -ESRCH;
12974 		}
12975 
12976 		/* externs shouldn't be pre-setup from user code */
12977 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12978 			*mmaped = (*map)->mmaped;
12979 	}
12980 	return 0;
12981 }
12982 
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt)12983 static int populate_skeleton_progs(const struct bpf_object *obj,
12984 				   struct bpf_prog_skeleton *progs,
12985 				   size_t prog_cnt)
12986 {
12987 	int i;
12988 
12989 	for (i = 0; i < prog_cnt; i++) {
12990 		struct bpf_program **prog = progs[i].prog;
12991 		const char *name = progs[i].name;
12992 
12993 		*prog = bpf_object__find_program_by_name(obj, name);
12994 		if (!*prog) {
12995 			pr_warn("failed to find skeleton program '%s'\n", name);
12996 			return -ESRCH;
12997 		}
12998 	}
12999 	return 0;
13000 }
13001 
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)13002 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13003 			      const struct bpf_object_open_opts *opts)
13004 {
13005 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13006 		.object_name = s->name,
13007 	);
13008 	struct bpf_object *obj;
13009 	int err;
13010 
13011 	/* Attempt to preserve opts->object_name, unless overriden by user
13012 	 * explicitly. Overwriting object name for skeletons is discouraged,
13013 	 * as it breaks global data maps, because they contain object name
13014 	 * prefix as their own map name prefix. When skeleton is generated,
13015 	 * bpftool is making an assumption that this name will stay the same.
13016 	 */
13017 	if (opts) {
13018 		memcpy(&skel_opts, opts, sizeof(*opts));
13019 		if (!opts->object_name)
13020 			skel_opts.object_name = s->name;
13021 	}
13022 
13023 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13024 	err = libbpf_get_error(obj);
13025 	if (err) {
13026 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13027 			s->name, err);
13028 		return libbpf_err(err);
13029 	}
13030 
13031 	*s->obj = obj;
13032 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13033 	if (err) {
13034 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13035 		return libbpf_err(err);
13036 	}
13037 
13038 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13039 	if (err) {
13040 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13041 		return libbpf_err(err);
13042 	}
13043 
13044 	return 0;
13045 }
13046 
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13047 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13048 {
13049 	int err, len, var_idx, i;
13050 	const char *var_name;
13051 	const struct bpf_map *map;
13052 	struct btf *btf;
13053 	__u32 map_type_id;
13054 	const struct btf_type *map_type, *var_type;
13055 	const struct bpf_var_skeleton *var_skel;
13056 	struct btf_var_secinfo *var;
13057 
13058 	if (!s->obj)
13059 		return libbpf_err(-EINVAL);
13060 
13061 	btf = bpf_object__btf(s->obj);
13062 	if (!btf) {
13063 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13064 			bpf_object__name(s->obj));
13065 		return libbpf_err(-errno);
13066 	}
13067 
13068 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13069 	if (err) {
13070 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13071 		return libbpf_err(err);
13072 	}
13073 
13074 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13075 	if (err) {
13076 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13077 		return libbpf_err(err);
13078 	}
13079 
13080 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13081 		var_skel = &s->vars[var_idx];
13082 		map = *var_skel->map;
13083 		map_type_id = bpf_map__btf_value_type_id(map);
13084 		map_type = btf__type_by_id(btf, map_type_id);
13085 
13086 		if (!btf_is_datasec(map_type)) {
13087 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13088 				bpf_map__name(map),
13089 				__btf_kind_str(btf_kind(map_type)));
13090 			return libbpf_err(-EINVAL);
13091 		}
13092 
13093 		len = btf_vlen(map_type);
13094 		var = btf_var_secinfos(map_type);
13095 		for (i = 0; i < len; i++, var++) {
13096 			var_type = btf__type_by_id(btf, var->type);
13097 			var_name = btf__name_by_offset(btf, var_type->name_off);
13098 			if (strcmp(var_name, var_skel->name) == 0) {
13099 				*var_skel->addr = map->mmaped + var->offset;
13100 				break;
13101 			}
13102 		}
13103 	}
13104 	return 0;
13105 }
13106 
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)13107 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13108 {
13109 	if (!s)
13110 		return;
13111 	free(s->maps);
13112 	free(s->progs);
13113 	free(s->vars);
13114 	free(s);
13115 }
13116 
bpf_object__load_skeleton(struct bpf_object_skeleton * s)13117 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13118 {
13119 	int i, err;
13120 
13121 	err = bpf_object__load(*s->obj);
13122 	if (err) {
13123 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13124 		return libbpf_err(err);
13125 	}
13126 
13127 	for (i = 0; i < s->map_cnt; i++) {
13128 		struct bpf_map *map = *s->maps[i].map;
13129 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13130 		int prot, map_fd = bpf_map__fd(map);
13131 		void **mmaped = s->maps[i].mmaped;
13132 
13133 		if (!mmaped)
13134 			continue;
13135 
13136 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13137 			*mmaped = NULL;
13138 			continue;
13139 		}
13140 
13141 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13142 			prot = PROT_READ;
13143 		else
13144 			prot = PROT_READ | PROT_WRITE;
13145 
13146 		/* Remap anonymous mmap()-ed "map initialization image" as
13147 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13148 		 * memory address. This will cause kernel to change process'
13149 		 * page table to point to a different piece of kernel memory,
13150 		 * but from userspace point of view memory address (and its
13151 		 * contents, being identical at this point) will stay the
13152 		 * same. This mapping will be released by bpf_object__close()
13153 		 * as per normal clean up procedure, so we don't need to worry
13154 		 * about it from skeleton's clean up perspective.
13155 		 */
13156 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13157 		if (*mmaped == MAP_FAILED) {
13158 			err = -errno;
13159 			*mmaped = NULL;
13160 			pr_warn("failed to re-mmap() map '%s': %d\n",
13161 				 bpf_map__name(map), err);
13162 			return libbpf_err(err);
13163 		}
13164 	}
13165 
13166 	return 0;
13167 }
13168 
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)13169 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13170 {
13171 	int i, err;
13172 
13173 	for (i = 0; i < s->prog_cnt; i++) {
13174 		struct bpf_program *prog = *s->progs[i].prog;
13175 		struct bpf_link **link = s->progs[i].link;
13176 
13177 		if (!prog->autoload || !prog->autoattach)
13178 			continue;
13179 
13180 		/* auto-attaching not supported for this program */
13181 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13182 			continue;
13183 
13184 		/* if user already set the link manually, don't attempt auto-attach */
13185 		if (*link)
13186 			continue;
13187 
13188 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13189 		if (err) {
13190 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13191 				bpf_program__name(prog), err);
13192 			return libbpf_err(err);
13193 		}
13194 
13195 		/* It's possible that for some SEC() definitions auto-attach
13196 		 * is supported in some cases (e.g., if definition completely
13197 		 * specifies target information), but is not in other cases.
13198 		 * SEC("uprobe") is one such case. If user specified target
13199 		 * binary and function name, such BPF program can be
13200 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13201 		 * attach to fail. It should just be skipped.
13202 		 * attach_fn signals such case with returning 0 (no error) and
13203 		 * setting link to NULL.
13204 		 */
13205 	}
13206 
13207 	return 0;
13208 }
13209 
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)13210 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13211 {
13212 	int i;
13213 
13214 	for (i = 0; i < s->prog_cnt; i++) {
13215 		struct bpf_link **link = s->progs[i].link;
13216 
13217 		bpf_link__destroy(*link);
13218 		*link = NULL;
13219 	}
13220 }
13221 
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)13222 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13223 {
13224 	if (!s)
13225 		return;
13226 
13227 	if (s->progs)
13228 		bpf_object__detach_skeleton(s);
13229 	if (s->obj)
13230 		bpf_object__close(*s->obj);
13231 	free(s->maps);
13232 	free(s->progs);
13233 	free(s);
13234 }
13235