xref: /linux/tools/lib/bpf/libbpf.c (revision 5a8cd539ac19f7a68e68e1d25ef9ca2ff55b8500)
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/bpf_perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.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 MAX_EVENT_NAME_LEN	64
63 
64 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
65 
66 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
67 
68 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
69  * compilation if user enables corresponding warning. Disable it explicitly.
70  */
71 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
72 
73 #define __printf(a, b)	__attribute__((format(printf, a, b)))
74 
75 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
76 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
77 static int map_set_def_max_entries(struct bpf_map *map);
78 
79 static const char * const attach_type_name[] = {
80 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
81 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
82 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
83 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
84 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
85 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
86 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
87 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
88 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
89 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
90 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
91 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
92 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
93 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
94 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
95 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
96 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
97 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
98 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
99 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
100 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
101 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
102 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
103 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
104 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
105 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
106 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
107 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
108 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
109 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
110 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
111 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
112 	[BPF_LIRC_MODE2]		= "lirc_mode2",
113 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
114 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
115 	[BPF_TRACE_FENTRY]		= "trace_fentry",
116 	[BPF_TRACE_FEXIT]		= "trace_fexit",
117 	[BPF_MODIFY_RETURN]		= "modify_return",
118 	[BPF_TRACE_FSESSION]		= "trace_fsession",
119 	[BPF_LSM_MAC]			= "lsm_mac",
120 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
121 	[BPF_SK_LOOKUP]			= "sk_lookup",
122 	[BPF_TRACE_ITER]		= "trace_iter",
123 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
124 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
125 	[BPF_XDP]			= "xdp",
126 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
127 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
128 	[BPF_PERF_EVENT]		= "perf_event",
129 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
130 	[BPF_STRUCT_OPS]		= "struct_ops",
131 	[BPF_NETFILTER]			= "netfilter",
132 	[BPF_TCX_INGRESS]		= "tcx_ingress",
133 	[BPF_TCX_EGRESS]		= "tcx_egress",
134 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
135 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
136 	[BPF_NETKIT_PEER]		= "netkit_peer",
137 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
138 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
139 	[BPF_TRACE_FENTRY_MULTI]	= "trace_fentry_multi",
140 	[BPF_TRACE_FEXIT_MULTI]		= "trace_fexit_multi",
141 	[BPF_TRACE_FSESSION_MULTI]	= "trace_fsession_multi",
142 };
143 
144 static const char * const link_type_name[] = {
145 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
146 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
147 	[BPF_LINK_TYPE_TRACING]			= "tracing",
148 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
149 	[BPF_LINK_TYPE_ITER]			= "iter",
150 	[BPF_LINK_TYPE_NETNS]			= "netns",
151 	[BPF_LINK_TYPE_XDP]			= "xdp",
152 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
153 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
154 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
155 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
156 	[BPF_LINK_TYPE_TCX]			= "tcx",
157 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
158 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
159 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
160 	[BPF_LINK_TYPE_TRACING_MULTI]		= "tracing_multi",
161 };
162 
163 static const char * const map_type_name[] = {
164 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
165 	[BPF_MAP_TYPE_HASH]			= "hash",
166 	[BPF_MAP_TYPE_ARRAY]			= "array",
167 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
168 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
169 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
170 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
171 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
172 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
173 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
174 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
175 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
176 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
177 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
178 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
179 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
180 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
181 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
182 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
183 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
184 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
185 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
186 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
187 	[BPF_MAP_TYPE_QUEUE]			= "queue",
188 	[BPF_MAP_TYPE_STACK]			= "stack",
189 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
190 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
191 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
192 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
193 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
194 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
195 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
196 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
197 	[BPF_MAP_TYPE_ARENA]			= "arena",
198 	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
199 	[BPF_MAP_TYPE_RHASH]			= "rhash",
200 };
201 
202 static const char * const prog_type_name[] = {
203 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
204 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
205 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
206 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
207 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
208 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
209 	[BPF_PROG_TYPE_XDP]			= "xdp",
210 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
211 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
212 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
213 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
214 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
215 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
216 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
217 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
218 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
219 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
220 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
221 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
222 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
223 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
224 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
225 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
226 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
227 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
228 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
229 	[BPF_PROG_TYPE_TRACING]			= "tracing",
230 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
231 	[BPF_PROG_TYPE_EXT]			= "ext",
232 	[BPF_PROG_TYPE_LSM]			= "lsm",
233 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
234 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
235 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
236 };
237 
__base_pr(enum libbpf_print_level level,const char * format,va_list args)238 static int __base_pr(enum libbpf_print_level level, const char *format,
239 		     va_list args)
240 {
241 	const char *env_var = "LIBBPF_LOG_LEVEL";
242 	static enum libbpf_print_level min_level = LIBBPF_INFO;
243 	static bool initialized;
244 
245 	if (!initialized) {
246 		char *verbosity;
247 
248 		initialized = true;
249 		verbosity = getenv(env_var);
250 		if (verbosity) {
251 			if (strcasecmp(verbosity, "warn") == 0)
252 				min_level = LIBBPF_WARN;
253 			else if (strcasecmp(verbosity, "debug") == 0)
254 				min_level = LIBBPF_DEBUG;
255 			else if (strcasecmp(verbosity, "info") == 0)
256 				min_level = LIBBPF_INFO;
257 			else
258 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
259 					env_var, verbosity);
260 		}
261 	}
262 
263 	/* if too verbose, skip logging  */
264 	if (level > min_level)
265 		return 0;
266 
267 	return vfprintf(stderr, format, args);
268 }
269 
270 static libbpf_print_fn_t __libbpf_pr = __base_pr;
271 
libbpf_set_print(libbpf_print_fn_t fn)272 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
273 {
274 	libbpf_print_fn_t old_print_fn;
275 
276 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
277 
278 	return old_print_fn;
279 }
280 
281 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)282 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
283 {
284 	va_list args;
285 	int old_errno;
286 	libbpf_print_fn_t print_fn;
287 
288 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
289 	if (!print_fn)
290 		return;
291 
292 	old_errno = errno;
293 
294 	va_start(args, format);
295 	print_fn(level, format, args);
296 	va_end(args);
297 
298 	errno = old_errno;
299 }
300 
pr_perm_msg(int err)301 static void pr_perm_msg(int err)
302 {
303 	struct rlimit limit;
304 	char buf[100];
305 
306 	if (err != -EPERM || geteuid() != 0)
307 		return;
308 
309 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
310 	if (err)
311 		return;
312 
313 	if (limit.rlim_cur == RLIM_INFINITY)
314 		return;
315 
316 	if (limit.rlim_cur < 1024)
317 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
318 	else if (limit.rlim_cur < 1024*1024)
319 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
320 	else
321 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
322 
323 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
324 		buf);
325 }
326 
327 /* Copied from tools/perf/util/util.h */
328 #ifndef zfree
329 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
330 #endif
331 
332 #ifndef zclose
333 # define zclose(fd) ({			\
334 	int ___err = 0;			\
335 	if ((fd) >= 0)			\
336 		___err = close((fd));	\
337 	fd = -1;			\
338 	___err; })
339 #endif
340 
ptr_to_u64(const void * ptr)341 static inline __u64 ptr_to_u64(const void *ptr)
342 {
343 	return (__u64) (unsigned long) ptr;
344 }
345 
libbpf_set_strict_mode(enum libbpf_strict_mode mode)346 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
347 {
348 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
349 	return 0;
350 }
351 
libbpf_major_version(void)352 __u32 libbpf_major_version(void)
353 {
354 	return LIBBPF_MAJOR_VERSION;
355 }
356 
libbpf_minor_version(void)357 __u32 libbpf_minor_version(void)
358 {
359 	return LIBBPF_MINOR_VERSION;
360 }
361 
libbpf_version_string(void)362 const char *libbpf_version_string(void)
363 {
364 #define __S(X) #X
365 #define _S(X) __S(X)
366 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
367 #undef _S
368 #undef __S
369 }
370 
371 enum reloc_type {
372 	RELO_LD64,
373 	RELO_CALL,
374 	RELO_DATA,
375 	RELO_EXTERN_LD64,
376 	RELO_EXTERN_CALL,
377 	RELO_SUBPROG_ADDR,
378 	RELO_CORE,
379 	RELO_INSN_ARRAY,
380 };
381 
382 struct reloc_desc {
383 	enum reloc_type type;
384 	int insn_idx;
385 	union {
386 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
387 		struct {
388 			int map_idx;
389 			unsigned int sym_off;
390 			/*
391 			 * The following two fields can be unionized, as the
392 			 * ext_idx field is used for extern symbols, and the
393 			 * sym_size is used for jump tables, which are never
394 			 * extern
395 			 */
396 			union {
397 				int ext_idx;
398 				int sym_size;
399 			};
400 		};
401 	};
402 };
403 
404 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
405 enum sec_def_flags {
406 	SEC_NONE = 0,
407 	/* expected_attach_type is optional, if kernel doesn't support that */
408 	SEC_EXP_ATTACH_OPT = 1,
409 	/* legacy, only used by libbpf_get_type_names() and
410 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
411 	 * This used to be associated with cgroup (and few other) BPF programs
412 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
413 	 * meaningless nowadays, though.
414 	 */
415 	SEC_ATTACHABLE = 2,
416 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
417 	/* attachment target is specified through BTF ID in either kernel or
418 	 * other BPF program's BTF object
419 	 */
420 	SEC_ATTACH_BTF = 4,
421 	/* BPF program type allows sleeping/blocking in kernel */
422 	SEC_SLEEPABLE = 8,
423 	/* BPF program support non-linear XDP buffer */
424 	SEC_XDP_FRAGS = 16,
425 	/* Setup proper attach type for usdt probes. */
426 	SEC_USDT = 32,
427 };
428 
429 struct bpf_sec_def {
430 	char *sec;
431 	enum bpf_prog_type prog_type;
432 	enum bpf_attach_type expected_attach_type;
433 	long cookie;
434 	int handler_id;
435 
436 	libbpf_prog_setup_fn_t prog_setup_fn;
437 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
438 	libbpf_prog_attach_fn_t prog_attach_fn;
439 };
440 
441 struct bpf_light_subprog {
442 	__u32 sec_insn_off;
443 	__u32 sub_insn_off;
444 };
445 
446 /*
447  * bpf_prog should be a better name but it has been used in
448  * linux/filter.h.
449  */
450 struct bpf_program {
451 	char *name;
452 	char *sec_name;
453 	size_t sec_idx;
454 	const struct bpf_sec_def *sec_def;
455 	/* this program's instruction offset (in number of instructions)
456 	 * within its containing ELF section
457 	 */
458 	size_t sec_insn_off;
459 	/* number of original instructions in ELF section belonging to this
460 	 * program, not taking into account subprogram instructions possible
461 	 * appended later during relocation
462 	 */
463 	size_t sec_insn_cnt;
464 	/* Offset (in number of instructions) of the start of instruction
465 	 * belonging to this BPF program  within its containing main BPF
466 	 * program. For the entry-point (main) BPF program, this is always
467 	 * zero. For a sub-program, this gets reset before each of main BPF
468 	 * programs are processed and relocated and is used to determined
469 	 * whether sub-program was already appended to the main program, and
470 	 * if yes, at which instruction offset.
471 	 */
472 	size_t sub_insn_off;
473 
474 	/* instructions that belong to BPF program; insns[0] is located at
475 	 * sec_insn_off instruction within its ELF section in ELF file, so
476 	 * when mapping ELF file instruction index to the local instruction,
477 	 * one needs to subtract sec_insn_off; and vice versa.
478 	 */
479 	struct bpf_insn *insns;
480 	/* actual number of instruction in this BPF program's image; for
481 	 * entry-point BPF programs this includes the size of main program
482 	 * itself plus all the used sub-programs, appended at the end
483 	 */
484 	size_t insns_cnt;
485 
486 	struct reloc_desc *reloc_desc;
487 	int nr_reloc;
488 
489 	/* BPF verifier log settings */
490 	char *log_buf;
491 	size_t log_size;
492 	__u32 log_level;
493 
494 	struct bpf_object *obj;
495 
496 	int fd;
497 	bool autoload;
498 	bool autoattach;
499 	bool sym_global;
500 	bool mark_btf_static;
501 	enum bpf_prog_type type;
502 	enum bpf_attach_type expected_attach_type;
503 	int exception_cb_idx;
504 
505 	int prog_ifindex;
506 	__u32 attach_btf_obj_fd;
507 	__u32 attach_btf_id;
508 	__u32 attach_prog_fd;
509 
510 	void *func_info;
511 	__u32 func_info_rec_size;
512 	__u32 func_info_cnt;
513 
514 	void *line_info;
515 	__u32 line_info_rec_size;
516 	__u32 line_info_cnt;
517 	__u32 prog_flags;
518 	__u8  hash[SHA256_DIGEST_LENGTH];
519 
520 	struct bpf_light_subprog *subprogs;
521 	__u32 subprog_cnt;
522 };
523 
524 struct bpf_struct_ops {
525 	struct bpf_program **progs;
526 	__u32 *kern_func_off;
527 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
528 	void *data;
529 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
530 	 *      btf_vmlinux's format.
531 	 * struct bpf_struct_ops_tcp_congestion_ops {
532 	 *	[... some other kernel fields ...]
533 	 *	struct tcp_congestion_ops data;
534 	 * }
535 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
536 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
537 	 * from "data".
538 	 */
539 	void *kern_vdata;
540 	__u32 type_id;
541 };
542 
543 #define DATA_SEC ".data"
544 #define PERCPU_SEC ".percpu"
545 #define BSS_SEC ".bss"
546 #define RODATA_SEC ".rodata"
547 #define KCONFIG_SEC ".kconfig"
548 #define KSYMS_SEC ".ksyms"
549 #define STRUCT_OPS_SEC ".struct_ops"
550 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
551 #define ARENA_SEC ".addr_space.1"
552 
553 enum libbpf_map_type {
554 	LIBBPF_MAP_UNSPEC,
555 	LIBBPF_MAP_DATA,
556 	LIBBPF_MAP_BSS,
557 	LIBBPF_MAP_RODATA,
558 	LIBBPF_MAP_KCONFIG,
559 	LIBBPF_MAP_PERCPU,
560 };
561 
562 struct bpf_map_def {
563 	unsigned int type;
564 	unsigned int key_size;
565 	unsigned int value_size;
566 	unsigned int max_entries;
567 	unsigned int map_flags;
568 };
569 
570 struct bpf_map {
571 	struct bpf_object *obj;
572 	char *name;
573 	/* real_name is defined for special internal maps (.rodata*,
574 	 * .data*, .bss, .kconfig) and preserves their original ELF section
575 	 * name. This is important to be able to find corresponding BTF
576 	 * DATASEC information.
577 	 */
578 	char *real_name;
579 	int fd;
580 	int sec_idx;
581 	size_t sec_offset;
582 	int map_ifindex;
583 	int inner_map_fd;
584 	struct bpf_map_def def;
585 	__u32 numa_node;
586 	__u32 btf_var_idx;
587 	int mod_btf_fd;
588 	__u32 btf_key_type_id;
589 	__u32 btf_value_type_id;
590 	__u32 btf_vmlinux_value_type_id;
591 	enum libbpf_map_type libbpf_type;
592 	void *mmaped;
593 	struct bpf_struct_ops *st_ops;
594 	struct bpf_map *inner_map;
595 	void **init_slots;
596 	int init_slots_sz;
597 	char *pin_path;
598 	bool pinned;
599 	bool reused;
600 	bool autocreate;
601 	bool autoattach;
602 	__u64 map_extra;
603 	struct bpf_program *excl_prog;
604 };
605 
606 enum extern_type {
607 	EXT_UNKNOWN,
608 	EXT_KCFG,
609 	EXT_KSYM,
610 };
611 
612 enum kcfg_type {
613 	KCFG_UNKNOWN,
614 	KCFG_CHAR,
615 	KCFG_BOOL,
616 	KCFG_INT,
617 	KCFG_TRISTATE,
618 	KCFG_CHAR_ARR,
619 };
620 
621 struct extern_desc {
622 	enum extern_type type;
623 	int sym_idx;
624 	int btf_id;
625 	int sec_btf_id;
626 	char *name;
627 	char *essent_name;
628 	bool is_set;
629 	bool is_weak;
630 	union {
631 		struct {
632 			enum kcfg_type type;
633 			int sz;
634 			int align;
635 			int data_off;
636 			bool is_signed;
637 		} kcfg;
638 		struct {
639 			unsigned long long addr;
640 
641 			/* target btf_id of the corresponding kernel var. */
642 			int kernel_btf_obj_fd;
643 			int kernel_btf_id;
644 
645 			/* local btf_id of the ksym extern's type. */
646 			__u32 type_id;
647 			/* BTF fd index to be patched in for insn->off, this is
648 			 * 0 for vmlinux BTF, index in obj->fd_array for module
649 			 * BTF
650 			 */
651 			__s16 btf_fd_idx;
652 		} ksym;
653 	};
654 };
655 
656 struct module_btf {
657 	struct btf *btf;
658 	char *name;
659 	__u32 id;
660 	int fd;
661 	int fd_array_idx;
662 };
663 
664 enum sec_type {
665 	SEC_UNUSED = 0,
666 	SEC_RELO,
667 	SEC_BSS,
668 	SEC_DATA,
669 	SEC_RODATA,
670 	SEC_ST_OPS,
671 	SEC_PERCPU,
672 };
673 
674 struct elf_sec_desc {
675 	enum sec_type sec_type;
676 	Elf64_Shdr *shdr;
677 	Elf_Data *data;
678 };
679 
680 struct elf_state {
681 	int fd;
682 	const void *obj_buf;
683 	size_t obj_buf_sz;
684 	Elf *elf;
685 	Elf64_Ehdr *ehdr;
686 	Elf_Data *symbols;
687 	Elf_Data *arena_data;
688 	size_t shstrndx; /* section index for section name strings */
689 	size_t strtabidx;
690 	struct elf_sec_desc *secs;
691 	size_t sec_cnt;
692 	int btf_maps_shndx;
693 	__u32 btf_maps_sec_btf_id;
694 	int text_shndx;
695 	int symbols_shndx;
696 	bool has_st_ops;
697 	int arena_data_shndx;
698 	int jumptables_data_shndx;
699 };
700 
701 struct usdt_manager;
702 
703 enum bpf_object_state {
704 	OBJ_OPEN,
705 	OBJ_PREPARED,
706 	OBJ_LOADED,
707 };
708 
709 struct bpf_object {
710 	char name[BPF_OBJ_NAME_LEN];
711 	char license[64];
712 	__u32 kern_version;
713 
714 	enum bpf_object_state state;
715 	struct bpf_program *programs;
716 	size_t nr_programs;
717 	struct bpf_map *maps;
718 	size_t nr_maps;
719 	size_t maps_cap;
720 
721 	char *kconfig;
722 	struct extern_desc *externs;
723 	int nr_extern;
724 	int kconfig_map_idx;
725 
726 	bool has_subcalls;
727 	bool has_rodata;
728 
729 	struct bpf_gen *gen_loader;
730 
731 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
732 	struct elf_state efile;
733 
734 	unsigned char byteorder;
735 
736 	struct btf *btf;
737 	struct btf_ext *btf_ext;
738 
739 	/* Parse and load BTF vmlinux if any of the programs in the object need
740 	 * it at load time.
741 	 */
742 	struct btf *btf_vmlinux;
743 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
744 	 * override for vmlinux BTF.
745 	 */
746 	char *btf_custom_path;
747 	/* vmlinux BTF override for CO-RE relocations */
748 	struct btf *btf_vmlinux_override;
749 	/* Lazily initialized kernel module BTFs */
750 	struct module_btf *btf_modules;
751 	bool btf_modules_loaded;
752 	size_t btf_module_cnt;
753 	size_t btf_module_cap;
754 
755 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
756 	char *log_buf;
757 	size_t log_size;
758 	__u32 log_level;
759 
760 	int *fd_array;
761 	size_t fd_array_cap;
762 	size_t fd_array_cnt;
763 
764 	struct usdt_manager *usdt_man;
765 
766 	int arena_map_idx;
767 	void *arena_data;
768 	size_t arena_data_sz;
769 	size_t arena_data_off;
770 
771 	void *jumptables_data;
772 	size_t jumptables_data_sz;
773 
774 	struct {
775 		struct bpf_program *prog;
776 		unsigned int sym_off;
777 		int fd;
778 	} *jumptable_maps;
779 	size_t jumptable_map_cnt;
780 
781 	struct kern_feature_cache *feat_cache;
782 	char *token_path;
783 	int token_fd;
784 
785 	char path[];
786 };
787 
788 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
789 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
790 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
791 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
792 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
793 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
794 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
795 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
796 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
797 
bpf_program__unload(struct bpf_program * prog)798 void bpf_program__unload(struct bpf_program *prog)
799 {
800 	if (!prog)
801 		return;
802 
803 	zclose(prog->fd);
804 
805 	zfree(&prog->func_info);
806 	zfree(&prog->line_info);
807 	zfree(&prog->subprogs);
808 }
809 
bpf_program__exit(struct bpf_program * prog)810 static void bpf_program__exit(struct bpf_program *prog)
811 {
812 	if (!prog)
813 		return;
814 
815 	bpf_program__unload(prog);
816 	zfree(&prog->name);
817 	zfree(&prog->sec_name);
818 	zfree(&prog->insns);
819 	zfree(&prog->reloc_desc);
820 
821 	prog->nr_reloc = 0;
822 	prog->insns_cnt = 0;
823 	prog->sec_idx = -1;
824 }
825 
insn_is_subprog_call(const struct bpf_insn * insn)826 static bool insn_is_subprog_call(const struct bpf_insn *insn)
827 {
828 	return BPF_CLASS(insn->code) == BPF_JMP &&
829 	       BPF_OP(insn->code) == BPF_CALL &&
830 	       BPF_SRC(insn->code) == BPF_K &&
831 	       insn->src_reg == BPF_PSEUDO_CALL &&
832 	       insn->dst_reg == 0 &&
833 	       insn->off == 0;
834 }
835 
is_call_insn(const struct bpf_insn * insn)836 static bool is_call_insn(const struct bpf_insn *insn)
837 {
838 	return insn->code == (BPF_JMP | BPF_CALL);
839 }
840 
insn_is_pseudo_func(struct bpf_insn * insn)841 static bool insn_is_pseudo_func(struct bpf_insn *insn)
842 {
843 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
844 }
845 
846 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)847 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
848 		      const char *name, size_t sec_idx, const char *sec_name,
849 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
850 {
851 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
852 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
853 			sec_name, name, sec_off, insn_data_sz);
854 		return -EINVAL;
855 	}
856 
857 	memset(prog, 0, sizeof(*prog));
858 	prog->obj = obj;
859 
860 	prog->sec_idx = sec_idx;
861 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
862 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
863 	/* insns_cnt can later be increased by appending used subprograms */
864 	prog->insns_cnt = prog->sec_insn_cnt;
865 
866 	prog->type = BPF_PROG_TYPE_UNSPEC;
867 	prog->fd = -1;
868 	prog->exception_cb_idx = -1;
869 
870 	/* libbpf's convention for SEC("?abc...") is that it's just like
871 	 * SEC("abc...") but the corresponding bpf_program starts out with
872 	 * autoload set to false.
873 	 */
874 	if (sec_name[0] == '?') {
875 		prog->autoload = false;
876 		/* from now on forget there was ? in section name */
877 		sec_name++;
878 	} else {
879 		prog->autoload = true;
880 	}
881 
882 	prog->autoattach = true;
883 
884 	/* inherit object's log_level */
885 	prog->log_level = obj->log_level;
886 
887 	prog->sec_name = strdup(sec_name);
888 	if (!prog->sec_name)
889 		goto errout;
890 
891 	prog->name = strdup(name);
892 	if (!prog->name)
893 		goto errout;
894 
895 	prog->insns = malloc(insn_data_sz);
896 	if (!prog->insns)
897 		goto errout;
898 	memcpy(prog->insns, insn_data, insn_data_sz);
899 
900 	return 0;
901 errout:
902 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
903 	bpf_program__exit(prog);
904 	return -ENOMEM;
905 }
906 
907 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)908 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
909 			 const char *sec_name, int sec_idx)
910 {
911 	Elf_Data *symbols = obj->efile.symbols;
912 	struct bpf_program *prog, *progs;
913 	void *data = sec_data->d_buf;
914 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
915 	int nr_progs, err, i;
916 	const char *name;
917 	Elf64_Sym *sym;
918 
919 	progs = obj->programs;
920 	nr_progs = obj->nr_programs;
921 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
922 
923 	for (i = 0; i < nr_syms; i++) {
924 		sym = elf_sym_by_idx(obj, i);
925 
926 		if (sym->st_shndx != sec_idx)
927 			continue;
928 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
929 			continue;
930 
931 		prog_sz = sym->st_size;
932 		sec_off = sym->st_value;
933 
934 		name = elf_sym_str(obj, sym->st_name);
935 		if (!name) {
936 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
937 				sec_name, sec_off);
938 			return -LIBBPF_ERRNO__FORMAT;
939 		}
940 
941 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
942 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
943 				sec_name, sec_off);
944 			return -LIBBPF_ERRNO__FORMAT;
945 		}
946 
947 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
948 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
949 			return -ENOTSUP;
950 		}
951 
952 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
953 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
954 
955 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
956 		if (!progs) {
957 			/*
958 			 * In this case the original obj->programs
959 			 * is still valid, so don't need special treat for
960 			 * bpf_close_object().
961 			 */
962 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
963 				sec_name, name);
964 			return -ENOMEM;
965 		}
966 		obj->programs = progs;
967 
968 		prog = &progs[nr_progs];
969 
970 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
971 					    sec_off, data + sec_off, prog_sz);
972 		if (err)
973 			return err;
974 
975 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
976 			prog->sym_global = true;
977 
978 		/* if function is a global/weak symbol, but has restricted
979 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
980 		 * as static to enable more permissive BPF verification mode
981 		 * with more outside context available to BPF verifier
982 		 */
983 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
984 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
985 			prog->mark_btf_static = true;
986 
987 		nr_progs++;
988 		obj->nr_programs = nr_progs;
989 	}
990 
991 	return 0;
992 }
993 
bpf_object_bswap_progs(struct bpf_object * obj)994 static void bpf_object_bswap_progs(struct bpf_object *obj)
995 {
996 	struct bpf_program *prog = obj->programs;
997 	struct bpf_insn *insn;
998 	int p, i;
999 
1000 	for (p = 0; p < obj->nr_programs; p++, prog++) {
1001 		insn = prog->insns;
1002 		for (i = 0; i < prog->insns_cnt; i++, insn++)
1003 			bpf_insn_bswap(insn);
1004 	}
1005 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
1006 }
1007 
1008 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)1009 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1010 {
1011 	struct btf_member *m;
1012 	int i;
1013 
1014 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1015 		if (btf_member_bit_offset(t, i) == bit_offset)
1016 			return m;
1017 	}
1018 
1019 	return NULL;
1020 }
1021 
1022 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)1023 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1024 		    const char *name)
1025 {
1026 	struct btf_member *m;
1027 	int i;
1028 
1029 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1030 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1031 			return m;
1032 	}
1033 
1034 	return NULL;
1035 }
1036 
1037 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1038 			    __u16 kind, struct btf **res_btf,
1039 			    struct module_btf **res_mod_btf);
1040 
1041 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1042 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1043 				   const char *name, __u32 kind);
1044 
1045 static int
find_struct_ops_kern_types(struct bpf_object * obj,const char * tname_raw,struct module_btf ** mod_btf,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)1046 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1047 			   struct module_btf **mod_btf,
1048 			   const struct btf_type **type, __u32 *type_id,
1049 			   const struct btf_type **vtype, __u32 *vtype_id,
1050 			   const struct btf_member **data_member)
1051 {
1052 	const struct btf_type *kern_type, *kern_vtype;
1053 	const struct btf_member *kern_data_member;
1054 	struct btf *btf = NULL;
1055 	__s32 kern_vtype_id, kern_type_id;
1056 	char tname[192], stname[256];
1057 	__u32 i;
1058 
1059 	snprintf(tname, sizeof(tname), "%.*s",
1060 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1061 
1062 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1063 
1064 	/* Look for the corresponding "map_value" type that will be used
1065 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1066 	 * and the mod_btf.
1067 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1068 	 */
1069 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1070 	if (kern_vtype_id < 0) {
1071 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1072 		return kern_vtype_id;
1073 	}
1074 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1075 
1076 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1077 	if (kern_type_id < 0) {
1078 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1079 		return kern_type_id;
1080 	}
1081 	kern_type = btf__type_by_id(btf, kern_type_id);
1082 
1083 	/* Find "struct tcp_congestion_ops" from
1084 	 * struct bpf_struct_ops_tcp_congestion_ops {
1085 	 *	[ ... ]
1086 	 *	struct tcp_congestion_ops data;
1087 	 * }
1088 	 */
1089 	kern_data_member = btf_members(kern_vtype);
1090 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1091 		if (kern_data_member->type == kern_type_id)
1092 			break;
1093 	}
1094 	if (i == btf_vlen(kern_vtype)) {
1095 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1096 			tname, stname);
1097 		return -EINVAL;
1098 	}
1099 
1100 	*type = kern_type;
1101 	*type_id = kern_type_id;
1102 	*vtype = kern_vtype;
1103 	*vtype_id = kern_vtype_id;
1104 	*data_member = kern_data_member;
1105 
1106 	return 0;
1107 }
1108 
bpf_map__is_struct_ops(const struct bpf_map * map)1109 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1110 {
1111 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1112 }
1113 
is_valid_st_ops_program(struct bpf_object * obj,const struct bpf_program * prog)1114 static bool is_valid_st_ops_program(struct bpf_object *obj,
1115 				    const struct bpf_program *prog)
1116 {
1117 	int i;
1118 
1119 	for (i = 0; i < obj->nr_programs; i++) {
1120 		if (&obj->programs[i] == prog)
1121 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1122 	}
1123 
1124 	return false;
1125 }
1126 
1127 /* For each struct_ops program P, referenced from some struct_ops map M,
1128  * enable P.autoload if there are Ms for which M.autocreate is true,
1129  * disable P.autoload if for all Ms M.autocreate is false.
1130  * Don't change P.autoload for programs that are not referenced from any maps.
1131  */
bpf_object_adjust_struct_ops_autoload(struct bpf_object * obj)1132 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1133 {
1134 	struct bpf_program *prog, *slot_prog;
1135 	struct bpf_map *map;
1136 	int i, j, k, vlen;
1137 
1138 	for (i = 0; i < obj->nr_programs; ++i) {
1139 		int should_load = false;
1140 		int use_cnt = 0;
1141 
1142 		prog = &obj->programs[i];
1143 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1144 			continue;
1145 
1146 		for (j = 0; j < obj->nr_maps; ++j) {
1147 			const struct btf_type *type;
1148 
1149 			map = &obj->maps[j];
1150 			if (!bpf_map__is_struct_ops(map))
1151 				continue;
1152 
1153 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1154 			vlen = btf_vlen(type);
1155 			for (k = 0; k < vlen; ++k) {
1156 				slot_prog = map->st_ops->progs[k];
1157 				if (prog != slot_prog)
1158 					continue;
1159 
1160 				use_cnt++;
1161 				if (map->autocreate)
1162 					should_load = true;
1163 			}
1164 		}
1165 		if (use_cnt)
1166 			prog->autoload = should_load;
1167 	}
1168 
1169 	return 0;
1170 }
1171 
1172 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map)1173 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1174 {
1175 	const struct btf_member *member, *kern_member, *kern_data_member;
1176 	const struct btf_type *type, *kern_type, *kern_vtype;
1177 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1178 	struct bpf_object *obj = map->obj;
1179 	const struct btf *btf = obj->btf;
1180 	struct bpf_struct_ops *st_ops;
1181 	const struct btf *kern_btf;
1182 	struct module_btf *mod_btf = NULL;
1183 	void *data, *kern_data;
1184 	const char *tname;
1185 	int err;
1186 
1187 	st_ops = map->st_ops;
1188 	type = btf__type_by_id(btf, st_ops->type_id);
1189 	tname = btf__name_by_offset(btf, type->name_off);
1190 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1191 					 &kern_type, &kern_type_id,
1192 					 &kern_vtype, &kern_vtype_id,
1193 					 &kern_data_member);
1194 	if (err)
1195 		return err;
1196 
1197 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1198 
1199 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1200 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1201 
1202 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1203 	map->def.value_size = kern_vtype->size;
1204 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1205 
1206 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1207 	if (!st_ops->kern_vdata)
1208 		return -ENOMEM;
1209 
1210 	data = st_ops->data;
1211 	kern_data_off = kern_data_member->offset / 8;
1212 	kern_data = st_ops->kern_vdata + kern_data_off;
1213 
1214 	member = btf_members(type);
1215 	for (i = 0; i < btf_vlen(type); i++, member++) {
1216 		const struct btf_type *mtype, *kern_mtype;
1217 		__u32 mtype_id, kern_mtype_id;
1218 		void *mdata, *kern_mdata;
1219 		struct bpf_program *prog;
1220 		__s64 msize, kern_msize;
1221 		__u32 moff, kern_moff;
1222 		__u32 kern_member_idx;
1223 		const char *mname;
1224 
1225 		mname = btf__name_by_offset(btf, member->name_off);
1226 		moff = member->offset / 8;
1227 		mdata = data + moff;
1228 		msize = btf__resolve_size(btf, member->type);
1229 		if (msize < 0) {
1230 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1231 				map->name, mname);
1232 			return msize;
1233 		}
1234 
1235 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1236 		if (!kern_member) {
1237 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1238 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1239 					map->name, mname);
1240 				return -ENOTSUP;
1241 			}
1242 
1243 			if (st_ops->progs[i]) {
1244 				/* If we had declaratively set struct_ops callback, we need to
1245 				 * force its autoload to false, because it doesn't have
1246 				 * a chance of succeeding from POV of the current struct_ops map.
1247 				 * If this program is still referenced somewhere else, though,
1248 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1249 				 * autoload accordingly.
1250 				 */
1251 				st_ops->progs[i]->autoload = false;
1252 				st_ops->progs[i] = NULL;
1253 			}
1254 
1255 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1256 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1257 				map->name, mname);
1258 			continue;
1259 		}
1260 
1261 		kern_member_idx = kern_member - btf_members(kern_type);
1262 		if (btf_member_bitfield_size(type, i) ||
1263 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1264 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1265 				map->name, mname);
1266 			return -ENOTSUP;
1267 		}
1268 
1269 		kern_moff = kern_member->offset / 8;
1270 		kern_mdata = kern_data + kern_moff;
1271 
1272 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1273 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1274 						    &kern_mtype_id);
1275 		if (BTF_INFO_KIND(mtype->info) !=
1276 		    BTF_INFO_KIND(kern_mtype->info)) {
1277 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1278 				map->name, mname, BTF_INFO_KIND(mtype->info),
1279 				BTF_INFO_KIND(kern_mtype->info));
1280 			return -ENOTSUP;
1281 		}
1282 
1283 		if (btf_is_ptr(mtype)) {
1284 			prog = *(void **)mdata;
1285 			/* just like for !kern_member case above, reset declaratively
1286 			 * set (at compile time) program's autload to false,
1287 			 * if user replaced it with another program or NULL
1288 			 */
1289 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1290 				st_ops->progs[i]->autoload = false;
1291 
1292 			/* Update the value from the shadow type */
1293 			st_ops->progs[i] = prog;
1294 			if (!prog)
1295 				continue;
1296 
1297 			if (!is_valid_st_ops_program(obj, prog)) {
1298 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1299 					map->name, mname);
1300 				return -ENOTSUP;
1301 			}
1302 
1303 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1304 							    kern_mtype->type,
1305 							    &kern_mtype_id);
1306 
1307 			/* mtype->type must be a func_proto which was
1308 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1309 			 * so only check kern_mtype for func_proto here.
1310 			 */
1311 			if (!btf_is_func_proto(kern_mtype)) {
1312 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1313 					map->name, mname);
1314 				return -ENOTSUP;
1315 			}
1316 
1317 			if (mod_btf)
1318 				prog->attach_btf_obj_fd = mod_btf->fd;
1319 
1320 			/* if we haven't yet processed this BPF program, record proper
1321 			 * attach_btf_id and member_idx
1322 			 */
1323 			if (!prog->attach_btf_id) {
1324 				prog->attach_btf_id = kern_type_id;
1325 				prog->expected_attach_type = kern_member_idx;
1326 			}
1327 
1328 			/* struct_ops BPF prog can be re-used between multiple
1329 			 * .struct_ops & .struct_ops.link as long as it's the
1330 			 * same struct_ops struct definition and the same
1331 			 * function pointer field
1332 			 */
1333 			if (prog->attach_btf_id != kern_type_id) {
1334 				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: attach_btf_id %u != kern_type_id %u\n",
1335 					map->name, mname, prog->name, prog->sec_name, prog->type,
1336 					prog->attach_btf_id, kern_type_id);
1337 				return -EINVAL;
1338 			}
1339 			if (prog->expected_attach_type != kern_member_idx) {
1340 				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: expected_attach_type %u != kern_member_idx %u\n",
1341 					map->name, mname, prog->name, prog->sec_name, prog->type,
1342 					prog->expected_attach_type, kern_member_idx);
1343 				return -EINVAL;
1344 			}
1345 
1346 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1347 
1348 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1349 				 map->name, mname, prog->name, moff,
1350 				 kern_moff);
1351 
1352 			continue;
1353 		}
1354 
1355 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1356 		if (kern_msize < 0 || msize != kern_msize) {
1357 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1358 				map->name, mname, (ssize_t)msize,
1359 				(ssize_t)kern_msize);
1360 			return -ENOTSUP;
1361 		}
1362 
1363 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1364 			 map->name, mname, (unsigned int)msize,
1365 			 moff, kern_moff);
1366 		memcpy(kern_mdata, mdata, msize);
1367 	}
1368 
1369 	return 0;
1370 }
1371 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1372 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1373 {
1374 	struct bpf_map *map;
1375 	size_t i;
1376 	int err;
1377 
1378 	for (i = 0; i < obj->nr_maps; i++) {
1379 		map = &obj->maps[i];
1380 
1381 		if (!bpf_map__is_struct_ops(map))
1382 			continue;
1383 
1384 		if (!map->autocreate)
1385 			continue;
1386 
1387 		err = bpf_map__init_kern_struct_ops(map);
1388 		if (err)
1389 			return err;
1390 	}
1391 
1392 	return 0;
1393 }
1394 
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data)1395 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1396 				int shndx, Elf_Data *data)
1397 {
1398 	const struct btf_type *type, *datasec;
1399 	const struct btf_var_secinfo *vsi;
1400 	struct bpf_struct_ops *st_ops;
1401 	const char *tname, *var_name;
1402 	__s32 type_id, datasec_id;
1403 	const struct btf *btf;
1404 	struct bpf_map *map;
1405 	__u32 i;
1406 
1407 	if (shndx == -1)
1408 		return 0;
1409 
1410 	btf = obj->btf;
1411 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1412 					    BTF_KIND_DATASEC);
1413 	if (datasec_id < 0) {
1414 		pr_warn("struct_ops init: DATASEC %s not found\n",
1415 			sec_name);
1416 		return -EINVAL;
1417 	}
1418 
1419 	datasec = btf__type_by_id(btf, datasec_id);
1420 	vsi = btf_var_secinfos(datasec);
1421 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1422 		type = btf__type_by_id(obj->btf, vsi->type);
1423 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1424 
1425 		type_id = btf__resolve_type(obj->btf, vsi->type);
1426 		if (type_id < 0) {
1427 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1428 				vsi->type, sec_name);
1429 			return -EINVAL;
1430 		}
1431 
1432 		type = btf__type_by_id(obj->btf, type_id);
1433 		tname = btf__name_by_offset(obj->btf, type->name_off);
1434 		if (!tname[0]) {
1435 			pr_warn("struct_ops init: anonymous type is not supported\n");
1436 			return -ENOTSUP;
1437 		}
1438 		if (!btf_is_struct(type)) {
1439 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1440 			return -EINVAL;
1441 		}
1442 
1443 		map = bpf_object__add_map(obj);
1444 		if (IS_ERR(map))
1445 			return PTR_ERR(map);
1446 
1447 		map->sec_idx = shndx;
1448 		map->sec_offset = vsi->offset;
1449 		map->name = strdup(var_name);
1450 		if (!map->name)
1451 			return -ENOMEM;
1452 		map->btf_value_type_id = type_id;
1453 
1454 		/* Follow same convention as for programs autoload:
1455 		 * SEC("?.struct_ops") means map is not created by default.
1456 		 */
1457 		if (sec_name[0] == '?') {
1458 			map->autocreate = false;
1459 			/* from now on forget there was ? in section name */
1460 			sec_name++;
1461 		}
1462 
1463 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1464 		map->def.key_size = sizeof(int);
1465 		map->def.value_size = type->size;
1466 		map->def.max_entries = 1;
1467 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1468 		map->autoattach = true;
1469 
1470 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1471 		if (!map->st_ops)
1472 			return -ENOMEM;
1473 		st_ops = map->st_ops;
1474 		st_ops->data = malloc(type->size);
1475 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1476 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1477 					       sizeof(*st_ops->kern_func_off));
1478 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1479 			return -ENOMEM;
1480 
1481 		if (vsi->offset + type->size > data->d_size) {
1482 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1483 				var_name, sec_name);
1484 			return -EINVAL;
1485 		}
1486 
1487 		memcpy(st_ops->data,
1488 		       data->d_buf + vsi->offset,
1489 		       type->size);
1490 		st_ops->type_id = type_id;
1491 
1492 		pr_debug("struct_ops init: struct %s(type_id=%d) %s found at offset %u\n",
1493 			 tname, type_id, var_name, vsi->offset);
1494 	}
1495 
1496 	return 0;
1497 }
1498 
bpf_object_init_struct_ops(struct bpf_object * obj)1499 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1500 {
1501 	const char *sec_name;
1502 	int sec_idx, err;
1503 
1504 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1505 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1506 
1507 		if (desc->sec_type != SEC_ST_OPS)
1508 			continue;
1509 
1510 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1511 		if (!sec_name)
1512 			return -LIBBPF_ERRNO__FORMAT;
1513 
1514 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1515 		if (err)
1516 			return err;
1517 	}
1518 
1519 	return 0;
1520 }
1521 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1522 static struct bpf_object *bpf_object__new(const char *path,
1523 					  const void *obj_buf,
1524 					  size_t obj_buf_sz,
1525 					  const char *obj_name)
1526 {
1527 	struct bpf_object *obj;
1528 	char *end;
1529 
1530 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1531 	if (!obj) {
1532 		pr_warn("alloc memory failed for %s\n", path);
1533 		return ERR_PTR(-ENOMEM);
1534 	}
1535 
1536 	strcpy(obj->path, path);
1537 	if (obj_name) {
1538 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1539 	} else {
1540 		/* Using basename() GNU version which doesn't modify arg. */
1541 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1542 		end = strchr(obj->name, '.');
1543 		if (end)
1544 			*end = 0;
1545 	}
1546 
1547 	obj->efile.fd = -1;
1548 	/*
1549 	 * Caller of this function should also call
1550 	 * bpf_object__elf_finish() after data collection to return
1551 	 * obj_buf to user. If not, we should duplicate the buffer to
1552 	 * avoid user freeing them before elf finish.
1553 	 */
1554 	obj->efile.obj_buf = obj_buf;
1555 	obj->efile.obj_buf_sz = obj_buf_sz;
1556 	obj->efile.btf_maps_shndx = -1;
1557 	obj->kconfig_map_idx = -1;
1558 	obj->arena_map_idx = -1;
1559 
1560 	obj->kern_version = get_kernel_version();
1561 	obj->state  = OBJ_OPEN;
1562 
1563 	return obj;
1564 }
1565 
bpf_object__elf_finish(struct bpf_object * obj)1566 static void bpf_object__elf_finish(struct bpf_object *obj)
1567 {
1568 	if (!obj->efile.elf)
1569 		return;
1570 
1571 	elf_end(obj->efile.elf);
1572 	obj->efile.elf = NULL;
1573 	obj->efile.ehdr = NULL;
1574 	obj->efile.symbols = NULL;
1575 	obj->efile.arena_data = NULL;
1576 
1577 	zfree(&obj->efile.secs);
1578 	obj->efile.sec_cnt = 0;
1579 	zclose(obj->efile.fd);
1580 	obj->efile.obj_buf = NULL;
1581 	obj->efile.obj_buf_sz = 0;
1582 }
1583 
bpf_object__elf_init(struct bpf_object * obj)1584 static int bpf_object__elf_init(struct bpf_object *obj)
1585 {
1586 	Elf64_Ehdr *ehdr;
1587 	int err = 0;
1588 	Elf *elf;
1589 
1590 	if (obj->efile.elf) {
1591 		pr_warn("elf: init internal error\n");
1592 		return -LIBBPF_ERRNO__LIBELF;
1593 	}
1594 
1595 	if (obj->efile.obj_buf_sz > 0) {
1596 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1597 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1598 	} else {
1599 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1600 		if (obj->efile.fd < 0) {
1601 			err = -errno;
1602 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1603 			return err;
1604 		}
1605 
1606 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1607 	}
1608 
1609 	if (!elf) {
1610 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1611 		err = -LIBBPF_ERRNO__LIBELF;
1612 		goto errout;
1613 	}
1614 
1615 	obj->efile.elf = elf;
1616 
1617 	if (elf_kind(elf) != ELF_K_ELF) {
1618 		err = -LIBBPF_ERRNO__FORMAT;
1619 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1620 		goto errout;
1621 	}
1622 
1623 	if (gelf_getclass(elf) != ELFCLASS64) {
1624 		err = -LIBBPF_ERRNO__FORMAT;
1625 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1626 		goto errout;
1627 	}
1628 
1629 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1630 	if (!obj->efile.ehdr) {
1631 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1632 		err = -LIBBPF_ERRNO__FORMAT;
1633 		goto errout;
1634 	}
1635 
1636 	/* Validate ELF object endianness... */
1637 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1638 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1639 		err = -LIBBPF_ERRNO__ENDIAN;
1640 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1641 		goto errout;
1642 	}
1643 	/* and save after bpf_object_open() frees ELF data */
1644 	obj->byteorder = ehdr->e_ident[EI_DATA];
1645 
1646 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1647 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1648 			obj->path, elf_errmsg(-1));
1649 		err = -LIBBPF_ERRNO__FORMAT;
1650 		goto errout;
1651 	}
1652 
1653 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1654 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1655 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1656 			obj->path, elf_errmsg(-1));
1657 		err = -LIBBPF_ERRNO__FORMAT;
1658 		goto errout;
1659 	}
1660 
1661 	/* Old LLVM set e_machine to EM_NONE */
1662 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1663 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1664 		err = -LIBBPF_ERRNO__FORMAT;
1665 		goto errout;
1666 	}
1667 
1668 	return 0;
1669 errout:
1670 	bpf_object__elf_finish(obj);
1671 	return err;
1672 }
1673 
is_native_endianness(struct bpf_object * obj)1674 static bool is_native_endianness(struct bpf_object *obj)
1675 {
1676 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1677 	return obj->byteorder == ELFDATA2LSB;
1678 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1679 	return obj->byteorder == ELFDATA2MSB;
1680 #else
1681 # error "Unrecognized __BYTE_ORDER__"
1682 #endif
1683 }
1684 
1685 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1686 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1687 {
1688 	if (!data) {
1689 		pr_warn("invalid license section in %s\n", obj->path);
1690 		return -LIBBPF_ERRNO__FORMAT;
1691 	}
1692 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1693 	 * go over allowed ELF data section buffer
1694 	 */
1695 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1696 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1697 	return 0;
1698 }
1699 
1700 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1701 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1702 {
1703 	__u32 kver;
1704 
1705 	if (!data || size != sizeof(kver)) {
1706 		pr_warn("invalid kver section in %s\n", obj->path);
1707 		return -LIBBPF_ERRNO__FORMAT;
1708 	}
1709 	memcpy(&kver, data, sizeof(kver));
1710 	obj->kern_version = kver;
1711 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1712 	return 0;
1713 }
1714 
bpf_map_type__is_map_in_map(enum bpf_map_type type)1715 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1716 {
1717 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1718 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1719 		return true;
1720 	return false;
1721 }
1722 
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1723 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1724 {
1725 	Elf_Data *data;
1726 	Elf_Scn *scn;
1727 
1728 	if (!name)
1729 		return -EINVAL;
1730 
1731 	scn = elf_sec_by_name(obj, name);
1732 	data = elf_sec_data(obj, scn);
1733 	if (data) {
1734 		*size = data->d_size;
1735 		return 0; /* found it */
1736 	}
1737 
1738 	return -ENOENT;
1739 }
1740 
find_elf_var_sym(const struct bpf_object * obj,const char * name)1741 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1742 {
1743 	Elf_Data *symbols = obj->efile.symbols;
1744 	const char *sname;
1745 	size_t si;
1746 
1747 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1748 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1749 
1750 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1751 			continue;
1752 
1753 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1754 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1755 			continue;
1756 
1757 		sname = elf_sym_str(obj, sym->st_name);
1758 		if (!sname) {
1759 			pr_warn("failed to get sym name string for var %s\n", name);
1760 			return ERR_PTR(-EIO);
1761 		}
1762 		if (strcmp(name, sname) == 0)
1763 			return sym;
1764 	}
1765 
1766 	return ERR_PTR(-ENOENT);
1767 }
1768 
1769 #ifndef MFD_CLOEXEC
1770 #define MFD_CLOEXEC 0x0001U
1771 #endif
1772 #ifndef MFD_NOEXEC_SEAL
1773 #define MFD_NOEXEC_SEAL 0x0008U
1774 #endif
1775 
create_placeholder_fd(void)1776 static int create_placeholder_fd(void)
1777 {
1778 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1779 	const char *name = "libbpf-placeholder-fd";
1780 	int fd;
1781 
1782 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1783 	if (fd >= 0)
1784 		return fd;
1785 	else if (errno != EINVAL)
1786 		return -errno;
1787 
1788 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1789 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1790 	if (fd < 0)
1791 		return -errno;
1792 	return fd;
1793 }
1794 
bpf_object__add_map(struct bpf_object * obj)1795 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1796 {
1797 	struct bpf_map *map;
1798 	int err;
1799 
1800 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1801 				sizeof(*obj->maps), obj->nr_maps + 1);
1802 	if (err)
1803 		return ERR_PTR(err);
1804 
1805 	map = &obj->maps[obj->nr_maps++];
1806 	map->obj = obj;
1807 	/* Preallocate map FD without actually creating BPF map just yet.
1808 	 * These map FD "placeholders" will be reused later without changing
1809 	 * FD value when map is actually created in the kernel.
1810 	 *
1811 	 * This is useful to be able to perform BPF program relocations
1812 	 * without having to create BPF maps before that step. This allows us
1813 	 * to finalize and load BTF very late in BPF object's loading phase,
1814 	 * right before BPF maps have to be created and BPF programs have to
1815 	 * be loaded. By having these map FD placeholders we can perform all
1816 	 * the sanitizations, relocations, and any other adjustments before we
1817 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1818 	 */
1819 	map->fd = create_placeholder_fd();
1820 	if (map->fd < 0)
1821 		return ERR_PTR(map->fd);
1822 	map->inner_map_fd = -1;
1823 	map->autocreate = true;
1824 
1825 	return map;
1826 }
1827 
array_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1828 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1829 {
1830 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1831 	size_t map_sz;
1832 
1833 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1834 	map_sz = roundup(map_sz, page_sz);
1835 	return map_sz;
1836 }
1837 
bpf_map_mmap_sz(const struct bpf_map * map)1838 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1839 {
1840 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1841 
1842 	switch (map->def.type) {
1843 	case BPF_MAP_TYPE_ARRAY:
1844 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1845 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1846 	case BPF_MAP_TYPE_ARENA:
1847 		return page_sz * map->def.max_entries;
1848 	default:
1849 		return 0; /* not supported */
1850 	}
1851 }
1852 
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1853 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1854 {
1855 	void *mmaped;
1856 
1857 	if (!map->mmaped)
1858 		return -EINVAL;
1859 
1860 	if (old_sz == new_sz)
1861 		return 0;
1862 
1863 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1864 	if (mmaped == MAP_FAILED)
1865 		return -errno;
1866 
1867 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1868 	munmap(map->mmaped, old_sz);
1869 	map->mmaped = mmaped;
1870 	return 0;
1871 }
1872 
internal_map_name(struct bpf_object * obj,const char * real_name,enum libbpf_map_type type)1873 static char *internal_map_name(struct bpf_object *obj, const char *real_name,
1874 			       enum libbpf_map_type type)
1875 {
1876 	char map_name[BPF_OBJ_NAME_LEN], *p;
1877 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1878 
1879 	/* This is one of the more confusing parts of libbpf for various
1880 	 * reasons, some of which are historical. The original idea for naming
1881 	 * internal names was to include as much of BPF object name prefix as
1882 	 * possible, so that it can be distinguished from similar internal
1883 	 * maps of a different BPF object.
1884 	 * As an example, let's say we have bpf_object named 'my_object_name'
1885 	 * and internal map corresponding to '.rodata' ELF section. The final
1886 	 * map name advertised to user and to the kernel will be
1887 	 * 'my_objec.rodata', taking first 8 characters of object name and
1888 	 * entire 7 characters of '.rodata'.
1889 	 * Somewhat confusingly, if internal map ELF section name is shorter
1890 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1891 	 * for the suffix, even though we only have 4 actual characters, and
1892 	 * resulting map will be called 'my_objec.bss', not even using all 15
1893 	 * characters allowed by the kernel. Oh well, at least the truncated
1894 	 * object name is somewhat consistent in this case. But if the map
1895 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1896 	 * (8 chars) and thus will be left with only first 7 characters of the
1897 	 * object name ('my_obje'). Happy guessing, user, that the final map
1898 	 * name will be "my_obje.kconfig".
1899 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1900 	 * and .data.* data sections, it's possible that ELF section name is
1901 	 * longer than allowed 15 chars, so we now need to be careful to take
1902 	 * only up to 15 first characters of ELF name, taking no BPF object
1903 	 * name characters at all. So '.rodata.abracadabra' will result in
1904 	 * '.rodata.abracad' kernel and user-visible name.
1905 	 * We need to keep this convoluted logic intact for .data, .bss and
1906 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1907 	 * maps we use their ELF names as is, not prepending bpf_object name
1908 	 * in front. We still need to truncate them to 15 characters for the
1909 	 * kernel. Full name can be recovered for such maps by using DATASEC
1910 	 * BTF type associated with such map's value type, though.
1911 	 */
1912 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1913 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1914 
1915 	/*
1916 	 * Don't prefix the bpf_object name if this is a custom dot map
1917 	 * (containing two or more dots) or a percpu data map.
1918 	 */
1919 	if (strchr(real_name + 1, '.') != NULL || type == LIBBPF_MAP_PERCPU)
1920 		pfx_len = 0;
1921 	else
1922 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1923 
1924 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1925 		 sfx_len, real_name);
1926 
1927 	/* sanities map name to characters allowed by kernel */
1928 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1929 		if (!isalnum(*p) && *p != '_' && *p != '.')
1930 			*p = '_';
1931 
1932 	return strdup(map_name);
1933 }
1934 
1935 static int
1936 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1937 
1938 /* Internal BPF map is mmap()'able only if at least one of corresponding
1939  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1940  * variable and it's not marked as __hidden (which turns it into, effectively,
1941  * a STATIC variable).
1942  */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1943 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1944 {
1945 	const struct btf_type *t, *vt;
1946 	struct btf_var_secinfo *vsi;
1947 	int i, n;
1948 
1949 	if (!map->btf_value_type_id)
1950 		return false;
1951 
1952 	/*
1953 	 * The internal PERCPU maps are not mmapable because the underlying
1954 	 * percpu_array maps do not have mmap support.
1955 	 */
1956 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
1957 		return false;
1958 
1959 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1960 	if (!btf_is_datasec(t))
1961 		return false;
1962 
1963 	vsi = btf_var_secinfos(t);
1964 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1965 		vt = btf__type_by_id(obj->btf, vsi->type);
1966 		if (!btf_is_var(vt))
1967 			continue;
1968 
1969 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1970 			return true;
1971 	}
1972 
1973 	return false;
1974 }
1975 
1976 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)1977 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1978 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1979 {
1980 	bool is_percpu = type == LIBBPF_MAP_PERCPU;
1981 	struct bpf_map_def *def;
1982 	struct bpf_map *map;
1983 	size_t mmap_sz;
1984 	int err;
1985 
1986 	map = bpf_object__add_map(obj);
1987 	if (IS_ERR(map))
1988 		return PTR_ERR(map);
1989 
1990 	map->libbpf_type = type;
1991 	map->sec_idx = sec_idx;
1992 	map->sec_offset = 0;
1993 	map->real_name = strdup(real_name);
1994 	map->name = internal_map_name(obj, real_name, type);
1995 	if (!map->real_name || !map->name) {
1996 		zfree(&map->real_name);
1997 		zfree(&map->name);
1998 		return -ENOMEM;
1999 	}
2000 
2001 	def = &map->def;
2002 	def->type = is_percpu ? BPF_MAP_TYPE_PERCPU_ARRAY : BPF_MAP_TYPE_ARRAY;
2003 	def->key_size = sizeof(int);
2004 	def->value_size = data_sz;
2005 	def->max_entries = 1;
2006 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
2007 		? BPF_F_RDONLY_PROG : 0;
2008 
2009 	/* failures are fine because of maps like .rodata.str1.1 */
2010 	(void) map_fill_btf_type_info(obj, map);
2011 
2012 	if (map_is_mmapable(obj, map))
2013 		def->map_flags |= BPF_F_MMAPABLE;
2014 
2015 	pr_debug("map '%s' (global %sdata): at sec_idx %d, offset %zu, flags %x.\n",
2016 		 map->name, is_percpu ? "percpu " : "", map->sec_idx,
2017 		 map->sec_offset, def->map_flags);
2018 
2019 	mmap_sz = bpf_map_mmap_sz(map);
2020 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2021 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2022 	if (map->mmaped == MAP_FAILED) {
2023 		err = -errno;
2024 		map->mmaped = NULL;
2025 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2026 		zfree(&map->real_name);
2027 		zfree(&map->name);
2028 		return err;
2029 	}
2030 
2031 	if (data)
2032 		memcpy(map->mmaped, data, data_sz);
2033 
2034 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2035 	return 0;
2036 }
2037 
bpf_object__init_global_data_maps(struct bpf_object * obj)2038 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2039 {
2040 	struct elf_sec_desc *sec_desc;
2041 	const char *sec_name;
2042 	int err = 0, sec_idx;
2043 
2044 	/*
2045 	 * Populate obj->maps with libbpf internal maps.
2046 	 */
2047 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2048 		sec_desc = &obj->efile.secs[sec_idx];
2049 
2050 		/* Skip recognized sections with size 0. */
2051 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2052 			continue;
2053 
2054 		switch (sec_desc->sec_type) {
2055 		case SEC_DATA:
2056 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2057 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2058 							    sec_name, sec_idx,
2059 							    sec_desc->data->d_buf,
2060 							    sec_desc->data->d_size);
2061 			break;
2062 		case SEC_RODATA:
2063 			obj->has_rodata = true;
2064 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2065 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2066 							    sec_name, sec_idx,
2067 							    sec_desc->data->d_buf,
2068 							    sec_desc->data->d_size);
2069 			break;
2070 		case SEC_BSS:
2071 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2072 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2073 							    sec_name, sec_idx,
2074 							    NULL,
2075 							    sec_desc->data->d_size);
2076 			break;
2077 		case SEC_PERCPU:
2078 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2079 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_PERCPU,
2080 							    sec_name, sec_idx,
2081 							    sec_desc->data->d_buf,
2082 							    sec_desc->data->d_size);
2083 			break;
2084 		default:
2085 			/* skip */
2086 			break;
2087 		}
2088 		if (err)
2089 			return err;
2090 	}
2091 	return 0;
2092 }
2093 
2094 
find_extern_by_name(const struct bpf_object * obj,const void * name)2095 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2096 					       const void *name)
2097 {
2098 	int i;
2099 
2100 	for (i = 0; i < obj->nr_extern; i++) {
2101 		if (strcmp(obj->externs[i].name, name) == 0)
2102 			return &obj->externs[i];
2103 	}
2104 	return NULL;
2105 }
2106 
find_extern_by_name_with_len(const struct bpf_object * obj,const void * name,int len)2107 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2108 							const void *name, int len)
2109 {
2110 	const char *ext_name;
2111 	int i;
2112 
2113 	for (i = 0; i < obj->nr_extern; i++) {
2114 		ext_name = obj->externs[i].name;
2115 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2116 			return &obj->externs[i];
2117 	}
2118 	return NULL;
2119 }
2120 
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)2121 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2122 			      char value)
2123 {
2124 	switch (ext->kcfg.type) {
2125 	case KCFG_BOOL:
2126 		if (value == 'm') {
2127 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2128 				ext->name, value);
2129 			return -EINVAL;
2130 		}
2131 		*(bool *)ext_val = value == 'y' ? true : false;
2132 		break;
2133 	case KCFG_TRISTATE:
2134 		if (value == 'y')
2135 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2136 		else if (value == 'm')
2137 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2138 		else /* value == 'n' */
2139 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2140 		break;
2141 	case KCFG_CHAR:
2142 		*(char *)ext_val = value;
2143 		break;
2144 	case KCFG_UNKNOWN:
2145 	case KCFG_INT:
2146 	case KCFG_CHAR_ARR:
2147 	default:
2148 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2149 			ext->name, value);
2150 		return -EINVAL;
2151 	}
2152 	ext->is_set = true;
2153 	return 0;
2154 }
2155 
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)2156 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2157 			      const char *value)
2158 {
2159 	size_t len;
2160 
2161 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2162 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2163 			ext->name, value);
2164 		return -EINVAL;
2165 	}
2166 
2167 	len = strlen(value);
2168 	if (len < 2 || value[len - 1] != '"') {
2169 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2170 			ext->name, value);
2171 		return -EINVAL;
2172 	}
2173 
2174 	/* strip quotes */
2175 	len -= 2;
2176 	if (len >= ext->kcfg.sz) {
2177 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2178 			ext->name, value, len, ext->kcfg.sz - 1);
2179 		len = ext->kcfg.sz - 1;
2180 	}
2181 	memcpy(ext_val, value + 1, len);
2182 	ext_val[len] = '\0';
2183 	ext->is_set = true;
2184 	return 0;
2185 }
2186 
parse_u64(const char * value,__u64 * res)2187 static int parse_u64(const char *value, __u64 *res)
2188 {
2189 	char *value_end;
2190 	int err;
2191 
2192 	errno = 0;
2193 	*res = strtoull(value, &value_end, 0);
2194 	if (errno) {
2195 		err = -errno;
2196 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2197 		return err;
2198 	}
2199 	if (*value_end) {
2200 		pr_warn("failed to parse '%s' as integer completely\n", value);
2201 		return -EINVAL;
2202 	}
2203 	return 0;
2204 }
2205 
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)2206 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2207 {
2208 	int bit_sz = ext->kcfg.sz * 8;
2209 
2210 	if (ext->kcfg.sz == 8)
2211 		return true;
2212 
2213 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2214 	 * bytes size without any loss of information. If the target integer
2215 	 * is signed, we rely on the following limits of integer type of
2216 	 * Y bits and subsequent transformation:
2217 	 *
2218 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2219 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2220 	 *            0 <= X + 2^(Y-1) <  2^Y
2221 	 *
2222 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2223 	 *  zero.
2224 	 */
2225 	if (ext->kcfg.is_signed)
2226 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2227 	else
2228 		return (v >> bit_sz) == 0;
2229 }
2230 
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)2231 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2232 			      __u64 value)
2233 {
2234 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2235 	    ext->kcfg.type != KCFG_BOOL) {
2236 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2237 			ext->name, (unsigned long long)value);
2238 		return -EINVAL;
2239 	}
2240 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2241 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2242 			ext->name, (unsigned long long)value);
2243 		return -EINVAL;
2244 
2245 	}
2246 	if (!is_kcfg_value_in_range(ext, value)) {
2247 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2248 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2249 		return -ERANGE;
2250 	}
2251 	switch (ext->kcfg.sz) {
2252 	case 1:
2253 		*(__u8 *)ext_val = value;
2254 		break;
2255 	case 2:
2256 		*(__u16 *)ext_val = value;
2257 		break;
2258 	case 4:
2259 		*(__u32 *)ext_val = value;
2260 		break;
2261 	case 8:
2262 		*(__u64 *)ext_val = value;
2263 		break;
2264 	default:
2265 		return -EINVAL;
2266 	}
2267 	ext->is_set = true;
2268 	return 0;
2269 }
2270 
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)2271 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2272 					    char *buf, void *data)
2273 {
2274 	struct extern_desc *ext;
2275 	char *sep, *value;
2276 	int len, err = 0;
2277 	void *ext_val;
2278 	__u64 num;
2279 
2280 	if (!str_has_pfx(buf, "CONFIG_"))
2281 		return 0;
2282 
2283 	sep = strchr(buf, '=');
2284 	if (!sep) {
2285 		pr_warn("failed to parse '%s': no separator\n", buf);
2286 		return -EINVAL;
2287 	}
2288 
2289 	/* Trim ending '\n' */
2290 	len = strlen(buf);
2291 	if (buf[len - 1] == '\n')
2292 		buf[len - 1] = '\0';
2293 	/* Split on '=' and ensure that a value is present. */
2294 	*sep = '\0';
2295 	if (!sep[1]) {
2296 		*sep = '=';
2297 		pr_warn("failed to parse '%s': no value\n", buf);
2298 		return -EINVAL;
2299 	}
2300 
2301 	ext = find_extern_by_name(obj, buf);
2302 	if (!ext || ext->is_set)
2303 		return 0;
2304 
2305 	ext_val = data + ext->kcfg.data_off;
2306 	value = sep + 1;
2307 
2308 	switch (*value) {
2309 	case 'y': case 'n': case 'm':
2310 		err = set_kcfg_value_tri(ext, ext_val, *value);
2311 		break;
2312 	case '"':
2313 		err = set_kcfg_value_str(ext, ext_val, value);
2314 		break;
2315 	default:
2316 		/* assume integer */
2317 		err = parse_u64(value, &num);
2318 		if (err) {
2319 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2320 			return err;
2321 		}
2322 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2323 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2324 			return -EINVAL;
2325 		}
2326 		err = set_kcfg_value_num(ext, ext_val, num);
2327 		break;
2328 	}
2329 	if (err)
2330 		return err;
2331 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2332 	return 0;
2333 }
2334 
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)2335 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2336 {
2337 	char buf[PATH_MAX];
2338 	struct utsname uts;
2339 	int len, err = 0;
2340 	gzFile file;
2341 
2342 	uname(&uts);
2343 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2344 	if (len < 0)
2345 		return -EINVAL;
2346 	else if (len >= PATH_MAX)
2347 		return -ENAMETOOLONG;
2348 
2349 	/* gzopen also accepts uncompressed files. */
2350 	file = gzopen(buf, "re");
2351 	if (!file)
2352 		file = gzopen("/proc/config.gz", "re");
2353 
2354 	if (!file) {
2355 		pr_warn("failed to open system Kconfig\n");
2356 		return -ENOENT;
2357 	}
2358 
2359 	while (gzgets(file, buf, sizeof(buf))) {
2360 		err = bpf_object__process_kconfig_line(obj, buf, data);
2361 		if (err) {
2362 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2363 				buf, errstr(err));
2364 			goto out;
2365 		}
2366 	}
2367 
2368 out:
2369 	gzclose(file);
2370 	return err;
2371 }
2372 
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2373 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2374 					const char *config, void *data)
2375 {
2376 	char buf[PATH_MAX];
2377 	int err = 0;
2378 	FILE *file;
2379 
2380 	file = fmemopen((void *)config, strlen(config), "r");
2381 	if (!file) {
2382 		err = -errno;
2383 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2384 		return err;
2385 	}
2386 
2387 	while (fgets(buf, sizeof(buf), file)) {
2388 		err = bpf_object__process_kconfig_line(obj, buf, data);
2389 		if (err) {
2390 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2391 				buf, errstr(err));
2392 			break;
2393 		}
2394 	}
2395 
2396 	fclose(file);
2397 	return err;
2398 }
2399 
bpf_object__init_kconfig_map(struct bpf_object * obj)2400 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2401 {
2402 	struct extern_desc *last_ext = NULL, *ext;
2403 	size_t map_sz;
2404 	int i, err;
2405 
2406 	for (i = 0; i < obj->nr_extern; i++) {
2407 		ext = &obj->externs[i];
2408 		if (ext->type == EXT_KCFG)
2409 			last_ext = ext;
2410 	}
2411 
2412 	if (!last_ext)
2413 		return 0;
2414 
2415 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2416 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2417 					    ".kconfig", obj->efile.symbols_shndx,
2418 					    NULL, map_sz);
2419 	if (err)
2420 		return err;
2421 
2422 	obj->kconfig_map_idx = obj->nr_maps - 1;
2423 
2424 	return 0;
2425 }
2426 
2427 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2428 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2429 {
2430 	const struct btf_type *t = btf__type_by_id(btf, id);
2431 
2432 	if (res_id)
2433 		*res_id = id;
2434 
2435 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2436 		if (res_id)
2437 			*res_id = t->type;
2438 		t = btf__type_by_id(btf, t->type);
2439 	}
2440 
2441 	return t;
2442 }
2443 
2444 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2445 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2446 {
2447 	const struct btf_type *t;
2448 
2449 	t = skip_mods_and_typedefs(btf, id, NULL);
2450 	if (!btf_is_ptr(t))
2451 		return NULL;
2452 
2453 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2454 
2455 	return btf_is_func_proto(t) ? t : NULL;
2456 }
2457 
__btf_kind_str(__u16 kind)2458 static const char *__btf_kind_str(__u16 kind)
2459 {
2460 	switch (kind) {
2461 	case BTF_KIND_UNKN: return "void";
2462 	case BTF_KIND_INT: return "int";
2463 	case BTF_KIND_PTR: return "ptr";
2464 	case BTF_KIND_ARRAY: return "array";
2465 	case BTF_KIND_STRUCT: return "struct";
2466 	case BTF_KIND_UNION: return "union";
2467 	case BTF_KIND_ENUM: return "enum";
2468 	case BTF_KIND_FWD: return "fwd";
2469 	case BTF_KIND_TYPEDEF: return "typedef";
2470 	case BTF_KIND_VOLATILE: return "volatile";
2471 	case BTF_KIND_CONST: return "const";
2472 	case BTF_KIND_RESTRICT: return "restrict";
2473 	case BTF_KIND_FUNC: return "func";
2474 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2475 	case BTF_KIND_VAR: return "var";
2476 	case BTF_KIND_DATASEC: return "datasec";
2477 	case BTF_KIND_FLOAT: return "float";
2478 	case BTF_KIND_DECL_TAG: return "decl_tag";
2479 	case BTF_KIND_TYPE_TAG: return "type_tag";
2480 	case BTF_KIND_ENUM64: return "enum64";
2481 	default: return "unknown";
2482 	}
2483 }
2484 
btf_kind_str(const struct btf_type * t)2485 const char *btf_kind_str(const struct btf_type *t)
2486 {
2487 	return __btf_kind_str(btf_kind(t));
2488 }
2489 
2490 /*
2491  * Fetch integer attribute of BTF map definition. Such attributes are
2492  * represented using a pointer to an array, in which dimensionality of array
2493  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2494  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2495  * type definition, while using only sizeof(void *) space in ELF data section.
2496  */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2497 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2498 			      const struct btf_member *m, __u32 *res)
2499 {
2500 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2501 	const char *name = btf__name_by_offset(btf, m->name_off);
2502 	const struct btf_array *arr_info;
2503 	const struct btf_type *arr_t;
2504 
2505 	if (!btf_is_ptr(t)) {
2506 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2507 			map_name, name, btf_kind_str(t));
2508 		return false;
2509 	}
2510 
2511 	arr_t = btf__type_by_id(btf, t->type);
2512 	if (!arr_t) {
2513 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2514 			map_name, name, t->type);
2515 		return false;
2516 	}
2517 	if (!btf_is_array(arr_t)) {
2518 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2519 			map_name, name, btf_kind_str(arr_t));
2520 		return false;
2521 	}
2522 	arr_info = btf_array(arr_t);
2523 	*res = arr_info->nelems;
2524 	return true;
2525 }
2526 
get_map_field_long(const char * map_name,const struct btf * btf,const struct btf_member * m,__u64 * res)2527 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2528 			       const struct btf_member *m, __u64 *res)
2529 {
2530 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2531 	const char *name = btf__name_by_offset(btf, m->name_off);
2532 
2533 	if (btf_is_ptr(t)) {
2534 		__u32 res32;
2535 		bool ret;
2536 
2537 		ret = get_map_field_int(map_name, btf, m, &res32);
2538 		if (ret)
2539 			*res = (__u64)res32;
2540 		return ret;
2541 	}
2542 
2543 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2544 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2545 			map_name, name, btf_kind_str(t));
2546 		return false;
2547 	}
2548 
2549 	if (btf_vlen(t) != 1) {
2550 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2551 			map_name, name);
2552 		return false;
2553 	}
2554 
2555 	if (btf_is_enum(t)) {
2556 		const struct btf_enum *e = btf_enum(t);
2557 
2558 		*res = e->val;
2559 	} else {
2560 		const struct btf_enum64 *e = btf_enum64(t);
2561 
2562 		*res = btf_enum64_value(e);
2563 	}
2564 	return true;
2565 }
2566 
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2567 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2568 {
2569 	int len;
2570 
2571 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2572 	if (len < 0)
2573 		return -EINVAL;
2574 	if (len >= buf_sz)
2575 		return -ENAMETOOLONG;
2576 
2577 	return 0;
2578 }
2579 
build_map_pin_path(struct bpf_map * map,const char * path)2580 static int build_map_pin_path(struct bpf_map *map, const char *path)
2581 {
2582 	char buf[PATH_MAX];
2583 	int err;
2584 
2585 	if (!path)
2586 		path = BPF_FS_DEFAULT_PATH;
2587 
2588 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2589 	if (err)
2590 		return err;
2591 
2592 	return bpf_map__set_pin_path(map, buf);
2593 }
2594 
2595 /* should match definition in bpf_helpers.h */
2596 enum libbpf_pin_type {
2597 	LIBBPF_PIN_NONE,
2598 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2599 	LIBBPF_PIN_BY_NAME,
2600 };
2601 
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)2602 int parse_btf_map_def(const char *map_name, struct btf *btf,
2603 		      const struct btf_type *def_t, bool strict,
2604 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2605 {
2606 	const struct btf_type *t;
2607 	const struct btf_member *m;
2608 	bool is_inner = inner_def == NULL;
2609 	int vlen, i;
2610 
2611 	vlen = btf_vlen(def_t);
2612 	m = btf_members(def_t);
2613 	for (i = 0; i < vlen; i++, m++) {
2614 		const char *name = btf__name_by_offset(btf, m->name_off);
2615 
2616 		if (!name) {
2617 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2618 			return -EINVAL;
2619 		}
2620 		if (strcmp(name, "type") == 0) {
2621 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2622 				return -EINVAL;
2623 			map_def->parts |= MAP_DEF_MAP_TYPE;
2624 		} else if (strcmp(name, "max_entries") == 0) {
2625 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2626 				return -EINVAL;
2627 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2628 		} else if (strcmp(name, "map_flags") == 0) {
2629 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2630 				return -EINVAL;
2631 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2632 		} else if (strcmp(name, "numa_node") == 0) {
2633 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2634 				return -EINVAL;
2635 			map_def->parts |= MAP_DEF_NUMA_NODE;
2636 		} else if (strcmp(name, "key_size") == 0) {
2637 			__u32 sz;
2638 
2639 			if (!get_map_field_int(map_name, btf, m, &sz))
2640 				return -EINVAL;
2641 			if (map_def->key_size && map_def->key_size != sz) {
2642 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2643 					map_name, map_def->key_size, sz);
2644 				return -EINVAL;
2645 			}
2646 			map_def->key_size = sz;
2647 			map_def->parts |= MAP_DEF_KEY_SIZE;
2648 		} else if (strcmp(name, "key") == 0) {
2649 			__s64 sz;
2650 
2651 			t = btf__type_by_id(btf, m->type);
2652 			if (!t) {
2653 				pr_warn("map '%s': key type [%u] not found.\n",
2654 					map_name, m->type);
2655 				return -EINVAL;
2656 			}
2657 			if (!btf_is_ptr(t)) {
2658 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2659 					map_name, btf_kind_str(t));
2660 				return -EINVAL;
2661 			}
2662 			sz = btf__resolve_size(btf, t->type);
2663 			if (sz < 0) {
2664 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2665 					map_name, t->type, (ssize_t)sz);
2666 				return sz;
2667 			}
2668 			if (map_def->key_size && map_def->key_size != sz) {
2669 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2670 					map_name, map_def->key_size, (ssize_t)sz);
2671 				return -EINVAL;
2672 			}
2673 			map_def->key_size = sz;
2674 			map_def->key_type_id = t->type;
2675 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2676 		} else if (strcmp(name, "value_size") == 0) {
2677 			__u32 sz;
2678 
2679 			if (!get_map_field_int(map_name, btf, m, &sz))
2680 				return -EINVAL;
2681 			if (map_def->value_size && map_def->value_size != sz) {
2682 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2683 					map_name, map_def->value_size, sz);
2684 				return -EINVAL;
2685 			}
2686 			map_def->value_size = sz;
2687 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2688 		} else if (strcmp(name, "value") == 0) {
2689 			__s64 sz;
2690 
2691 			t = btf__type_by_id(btf, m->type);
2692 			if (!t) {
2693 				pr_warn("map '%s': value type [%u] not found.\n",
2694 					map_name, m->type);
2695 				return -EINVAL;
2696 			}
2697 			if (!btf_is_ptr(t)) {
2698 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2699 					map_name, btf_kind_str(t));
2700 				return -EINVAL;
2701 			}
2702 			sz = btf__resolve_size(btf, t->type);
2703 			if (sz < 0) {
2704 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2705 					map_name, t->type, (ssize_t)sz);
2706 				return sz;
2707 			}
2708 			if (map_def->value_size && map_def->value_size != sz) {
2709 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2710 					map_name, map_def->value_size, (ssize_t)sz);
2711 				return -EINVAL;
2712 			}
2713 			map_def->value_size = sz;
2714 			map_def->value_type_id = t->type;
2715 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2716 		}
2717 		else if (strcmp(name, "values") == 0) {
2718 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2719 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2720 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2721 			char inner_map_name[128];
2722 			int err;
2723 
2724 			if (is_inner) {
2725 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2726 					map_name);
2727 				return -ENOTSUP;
2728 			}
2729 			if (i != vlen - 1) {
2730 				pr_warn("map '%s': '%s' member should be last.\n",
2731 					map_name, name);
2732 				return -EINVAL;
2733 			}
2734 			if (!is_map_in_map && !is_prog_array) {
2735 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2736 					map_name);
2737 				return -ENOTSUP;
2738 			}
2739 			if (map_def->value_size && map_def->value_size != 4) {
2740 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2741 					map_name, map_def->value_size);
2742 				return -EINVAL;
2743 			}
2744 			map_def->value_size = 4;
2745 			t = btf__type_by_id(btf, m->type);
2746 			if (!t) {
2747 				pr_warn("map '%s': %s type [%u] not found.\n",
2748 					map_name, desc, m->type);
2749 				return -EINVAL;
2750 			}
2751 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2752 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2753 					map_name, desc);
2754 				return -EINVAL;
2755 			}
2756 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2757 			if (!btf_is_ptr(t)) {
2758 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2759 					map_name, desc, btf_kind_str(t));
2760 				return -EINVAL;
2761 			}
2762 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2763 			if (is_prog_array) {
2764 				if (!btf_is_func_proto(t)) {
2765 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2766 						map_name, btf_kind_str(t));
2767 					return -EINVAL;
2768 				}
2769 				continue;
2770 			}
2771 			if (!btf_is_struct(t)) {
2772 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2773 					map_name, btf_kind_str(t));
2774 				return -EINVAL;
2775 			}
2776 
2777 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2778 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2779 			if (err)
2780 				return err;
2781 
2782 			map_def->parts |= MAP_DEF_INNER_MAP;
2783 		} else if (strcmp(name, "pinning") == 0) {
2784 			__u32 val;
2785 
2786 			if (is_inner) {
2787 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2788 				return -EINVAL;
2789 			}
2790 			if (!get_map_field_int(map_name, btf, m, &val))
2791 				return -EINVAL;
2792 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2793 				pr_warn("map '%s': invalid pinning value %u.\n",
2794 					map_name, val);
2795 				return -EINVAL;
2796 			}
2797 			map_def->pinning = val;
2798 			map_def->parts |= MAP_DEF_PINNING;
2799 		} else if (strcmp(name, "map_extra") == 0) {
2800 			__u64 map_extra;
2801 
2802 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2803 				return -EINVAL;
2804 			map_def->map_extra = map_extra;
2805 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2806 		} else {
2807 			if (strict) {
2808 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2809 				return -ENOTSUP;
2810 			}
2811 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2812 		}
2813 	}
2814 
2815 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2816 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2817 		return -EINVAL;
2818 	}
2819 
2820 	return 0;
2821 }
2822 
adjust_ringbuf_sz(size_t sz)2823 static size_t adjust_ringbuf_sz(size_t sz)
2824 {
2825 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2826 	__u32 mul;
2827 
2828 	/* if user forgot to set any size, make sure they see error */
2829 	if (sz == 0)
2830 		return 0;
2831 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2832 	 * a power-of-2 multiple of kernel's page size. If user diligently
2833 	 * satisfied these conditions, pass the size through.
2834 	 */
2835 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2836 		return sz;
2837 
2838 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2839 	 * user-set size to satisfy both user size request and kernel
2840 	 * requirements and substitute correct max_entries for map creation.
2841 	 */
2842 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2843 		if (mul * page_sz > sz)
2844 			return mul * page_sz;
2845 	}
2846 
2847 	/* if it's impossible to satisfy the conditions (i.e., user size is
2848 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2849 	 * page_size) then just return original size and let kernel reject it
2850 	 */
2851 	return sz;
2852 }
2853 
map_is_ringbuf(const struct bpf_map * map)2854 static bool map_is_ringbuf(const struct bpf_map *map)
2855 {
2856 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2857 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2858 }
2859 
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2860 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2861 {
2862 	map->def.type = def->map_type;
2863 	map->def.key_size = def->key_size;
2864 	map->def.value_size = def->value_size;
2865 	map->def.max_entries = def->max_entries;
2866 	map->def.map_flags = def->map_flags;
2867 	map->map_extra = def->map_extra;
2868 
2869 	map->numa_node = def->numa_node;
2870 	map->btf_key_type_id = def->key_type_id;
2871 	map->btf_value_type_id = def->value_type_id;
2872 
2873 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2874 	if (map_is_ringbuf(map))
2875 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2876 
2877 	if (def->parts & MAP_DEF_MAP_TYPE)
2878 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2879 
2880 	if (def->parts & MAP_DEF_KEY_TYPE)
2881 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2882 			 map->name, def->key_type_id, def->key_size);
2883 	else if (def->parts & MAP_DEF_KEY_SIZE)
2884 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2885 
2886 	if (def->parts & MAP_DEF_VALUE_TYPE)
2887 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2888 			 map->name, def->value_type_id, def->value_size);
2889 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2890 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2891 
2892 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2893 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2894 	if (def->parts & MAP_DEF_MAP_FLAGS)
2895 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2896 	if (def->parts & MAP_DEF_MAP_EXTRA)
2897 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2898 			 (unsigned long long)def->map_extra);
2899 	if (def->parts & MAP_DEF_PINNING)
2900 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2901 	if (def->parts & MAP_DEF_NUMA_NODE)
2902 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2903 
2904 	if (def->parts & MAP_DEF_INNER_MAP)
2905 		pr_debug("map '%s': found inner map definition.\n", map->name);
2906 }
2907 
btf_var_linkage_str(__u32 linkage)2908 static const char *btf_var_linkage_str(__u32 linkage)
2909 {
2910 	switch (linkage) {
2911 	case BTF_VAR_STATIC: return "static";
2912 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2913 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2914 	default: return "unknown";
2915 	}
2916 }
2917 
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)2918 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2919 					 const struct btf_type *sec,
2920 					 int var_idx, int sec_idx,
2921 					 const Elf_Data *data, bool strict,
2922 					 const char *pin_root_path)
2923 {
2924 	struct btf_map_def map_def = {}, inner_def = {};
2925 	const struct btf_type *var, *def;
2926 	const struct btf_var_secinfo *vi;
2927 	const struct btf_var *var_extra;
2928 	const char *map_name;
2929 	struct bpf_map *map;
2930 	int err;
2931 
2932 	vi = btf_var_secinfos(sec) + var_idx;
2933 	var = btf__type_by_id(obj->btf, vi->type);
2934 	var_extra = btf_var(var);
2935 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2936 
2937 	if (str_is_empty(map_name)) {
2938 		pr_warn("map #%d: empty name.\n", var_idx);
2939 		return -EINVAL;
2940 	}
2941 	if ((__u64)vi->offset + vi->size > data->d_size) {
2942 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2943 		return -EINVAL;
2944 	}
2945 	if (!btf_is_var(var)) {
2946 		pr_warn("map '%s': unexpected var kind %s.\n",
2947 			map_name, btf_kind_str(var));
2948 		return -EINVAL;
2949 	}
2950 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2951 		pr_warn("map '%s': unsupported map linkage %s.\n",
2952 			map_name, btf_var_linkage_str(var_extra->linkage));
2953 		return -EOPNOTSUPP;
2954 	}
2955 
2956 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2957 	if (!btf_is_struct(def)) {
2958 		pr_warn("map '%s': unexpected def kind %s.\n",
2959 			map_name, btf_kind_str(var));
2960 		return -EINVAL;
2961 	}
2962 	if (def->size > vi->size) {
2963 		pr_warn("map '%s': invalid def size.\n", map_name);
2964 		return -EINVAL;
2965 	}
2966 
2967 	map = bpf_object__add_map(obj);
2968 	if (IS_ERR(map))
2969 		return PTR_ERR(map);
2970 	map->name = strdup(map_name);
2971 	if (!map->name) {
2972 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2973 		return -ENOMEM;
2974 	}
2975 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2976 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2977 	map->sec_idx = sec_idx;
2978 	map->sec_offset = vi->offset;
2979 	map->btf_var_idx = var_idx;
2980 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2981 		 map_name, map->sec_idx, map->sec_offset);
2982 
2983 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2984 	if (err)
2985 		return err;
2986 
2987 	fill_map_from_def(map, &map_def);
2988 
2989 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2990 		err = build_map_pin_path(map, pin_root_path);
2991 		if (err) {
2992 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2993 			return err;
2994 		}
2995 	}
2996 
2997 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2998 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2999 		if (!map->inner_map)
3000 			return -ENOMEM;
3001 		map->inner_map->fd = create_placeholder_fd();
3002 		if (map->inner_map->fd < 0)
3003 			return map->inner_map->fd;
3004 		map->inner_map->sec_idx = sec_idx;
3005 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
3006 		if (!map->inner_map->name)
3007 			return -ENOMEM;
3008 		sprintf(map->inner_map->name, "%s.inner", map_name);
3009 
3010 		fill_map_from_def(map->inner_map, &inner_def);
3011 	}
3012 
3013 	err = map_fill_btf_type_info(obj, map);
3014 	if (err)
3015 		return err;
3016 
3017 	return 0;
3018 }
3019 
init_arena_map_data(struct bpf_object * obj,struct bpf_map * map,const char * sec_name,int sec_idx,void * data,size_t data_sz)3020 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
3021 			       const char *sec_name, int sec_idx,
3022 			       void *data, size_t data_sz)
3023 {
3024 	const long page_sz = sysconf(_SC_PAGE_SIZE);
3025 	const size_t data_alloc_sz = roundup(data_sz, page_sz);
3026 	size_t mmap_sz;
3027 
3028 	mmap_sz = bpf_map_mmap_sz(map);
3029 	if (data_alloc_sz > mmap_sz) {
3030 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
3031 			sec_name, mmap_sz, data_sz);
3032 		return -E2BIG;
3033 	}
3034 
3035 	obj->arena_data = malloc(data_sz);
3036 	if (!obj->arena_data)
3037 		return -ENOMEM;
3038 	memcpy(obj->arena_data, data, data_sz);
3039 	obj->arena_data_sz = data_sz;
3040 
3041 	/* make bpf_map__init_value() work for ARENA maps */
3042 	map->mmaped = obj->arena_data;
3043 
3044 	return 0;
3045 }
3046 
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)3047 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3048 					  const char *pin_root_path)
3049 {
3050 	const struct btf_type *sec = NULL;
3051 	int nr_types, i, vlen, err;
3052 	const struct btf_type *t;
3053 	const char *name;
3054 	Elf_Data *data;
3055 	Elf_Scn *scn;
3056 
3057 	if (obj->efile.btf_maps_shndx < 0)
3058 		return 0;
3059 
3060 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3061 	data = elf_sec_data(obj, scn);
3062 	if (!data) {
3063 		pr_warn("elf: failed to get %s map definitions for %s\n",
3064 			MAPS_ELF_SEC, obj->path);
3065 		return -EINVAL;
3066 	}
3067 
3068 	nr_types = btf__type_cnt(obj->btf);
3069 	for (i = 1; i < nr_types; i++) {
3070 		t = btf__type_by_id(obj->btf, i);
3071 		if (!btf_is_datasec(t))
3072 			continue;
3073 		name = btf__name_by_offset(obj->btf, t->name_off);
3074 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3075 			sec = t;
3076 			obj->efile.btf_maps_sec_btf_id = i;
3077 			break;
3078 		}
3079 	}
3080 
3081 	if (!sec) {
3082 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3083 		return -ENOENT;
3084 	}
3085 
3086 	vlen = btf_vlen(sec);
3087 	for (i = 0; i < vlen; i++) {
3088 		err = bpf_object__init_user_btf_map(obj, sec, i,
3089 						    obj->efile.btf_maps_shndx,
3090 						    data, strict,
3091 						    pin_root_path);
3092 		if (err)
3093 			return err;
3094 	}
3095 
3096 	for (i = 0; i < obj->nr_maps; i++) {
3097 		struct bpf_map *map = &obj->maps[i];
3098 
3099 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3100 			continue;
3101 
3102 		if (obj->arena_map_idx >= 0) {
3103 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3104 				map->name, obj->maps[obj->arena_map_idx].name);
3105 			return -EINVAL;
3106 		}
3107 		obj->arena_map_idx = i;
3108 
3109 		if (obj->efile.arena_data) {
3110 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3111 						  obj->efile.arena_data->d_buf,
3112 						  obj->efile.arena_data->d_size);
3113 			if (err)
3114 				return err;
3115 		}
3116 	}
3117 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3118 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3119 			ARENA_SEC);
3120 		return -ENOENT;
3121 	}
3122 
3123 	return 0;
3124 }
3125 
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)3126 static int bpf_object__init_maps(struct bpf_object *obj,
3127 				 const struct bpf_object_open_opts *opts)
3128 {
3129 	const char *pin_root_path;
3130 	bool strict;
3131 	int err = 0;
3132 
3133 	strict = !OPTS_GET(opts, relaxed_maps, false);
3134 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3135 
3136 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3137 	err = err ?: bpf_object__init_global_data_maps(obj);
3138 	err = err ?: bpf_object__init_kconfig_map(obj);
3139 	err = err ?: bpf_object_init_struct_ops(obj);
3140 
3141 	return err;
3142 }
3143 
section_have_execinstr(struct bpf_object * obj,int idx)3144 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3145 {
3146 	Elf64_Shdr *sh;
3147 
3148 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3149 	if (!sh)
3150 		return false;
3151 
3152 	return sh->sh_flags & SHF_EXECINSTR;
3153 }
3154 
starts_with_qmark(const char * s)3155 static bool starts_with_qmark(const char *s)
3156 {
3157 	return s && s[0] == '?';
3158 }
3159 
btf_needs_sanitization(struct bpf_object * obj)3160 static bool btf_needs_sanitization(struct bpf_object *obj)
3161 {
3162 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3163 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3164 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3165 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3166 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3167 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3168 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3169 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3170 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3171 
3172 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3173 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3174 	       !has_layout;
3175 }
3176 
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * orig_btf)3177 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3178 {
3179 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3180 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3181 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3182 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3183 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3184 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3185 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3186 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3187 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3188 	int enum64_placeholder_id = 0;
3189 	const struct btf_header *hdr;
3190 	struct btf *btf = NULL;
3191 	const void *raw_data;
3192 	struct btf_type *t;
3193 	int i, j, vlen;
3194 	__u32 sz;
3195 	int err;
3196 
3197 	/* clone BTF to sanitize a copy and leave the original intact */
3198 	raw_data = btf__raw_data(orig_btf, &sz);
3199 	if (!raw_data)
3200 		return ERR_PTR(-ENOMEM);
3201 	/* btf_header() gives us endian-safe header info */
3202 	hdr = btf_header(orig_btf);
3203 
3204 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3205 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3206 		const struct btf_header *old_hdr = raw_data;
3207 		struct btf_header *new_hdr;
3208 		void *new_raw_data;
3209 		__u32 new_str_off;
3210 
3211 		/*
3212 		 * Need to rewrite BTF to exclude layout information and
3213 		 * move string section to immediately after types.
3214 		 */
3215 		new_raw_data = malloc(sz);
3216 		if (!new_raw_data)
3217 			return ERR_PTR(-ENOMEM);
3218 
3219 		memcpy(new_raw_data, raw_data, sz);
3220 		new_hdr = new_raw_data;
3221 		new_hdr->layout_off = 0;
3222 		new_hdr->layout_len = 0;
3223 		new_str_off = hdr->type_off + hdr->type_len;
3224 		/* Handle swapped endian case */
3225 		if (old_hdr->magic != hdr->magic)
3226 			new_hdr->str_off = bswap_32(new_str_off);
3227 		else
3228 			new_hdr->str_off = new_str_off;
3229 
3230 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3231 			new_raw_data + hdr->hdr_len + hdr->str_off,
3232 			hdr->str_len);
3233 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3234 		btf = btf__new(new_raw_data, sz);
3235 		free(new_raw_data);
3236 	} else {
3237 		btf = btf__new(raw_data, sz);
3238 	}
3239 	err = libbpf_get_error(btf);
3240 	if (err)
3241 		return ERR_PTR(err);
3242 
3243 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3244 	btf__set_pointer_size(btf, 8);
3245 
3246 	for (i = 1; i < btf__type_cnt(btf); i++) {
3247 		t = (struct btf_type *)btf__type_by_id(btf, i);
3248 
3249 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3250 			/* replace VAR/DECL_TAG with INT */
3251 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3252 			/*
3253 			 * using size = 1 is the safest choice, 4 will be too
3254 			 * big and cause kernel BTF validation failure if
3255 			 * original variable took less than 4 bytes
3256 			 */
3257 			t->size = 1;
3258 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3259 		} else if (!has_datasec && btf_is_datasec(t)) {
3260 			/* replace DATASEC with STRUCT */
3261 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3262 			struct btf_member *m = btf_members(t);
3263 			struct btf_type *vt;
3264 			char *name;
3265 
3266 			name = (char *)btf__name_by_offset(btf, t->name_off);
3267 			while (*name) {
3268 				if (*name == '.' || *name == '?')
3269 					*name = '_';
3270 				name++;
3271 			}
3272 
3273 			vlen = btf_vlen(t);
3274 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3275 			for (j = 0; j < vlen; j++, v++, m++) {
3276 				/* order of field assignments is important */
3277 				m->offset = v->offset * 8;
3278 				m->type = v->type;
3279 				/* preserve variable name as member name */
3280 				vt = (void *)btf__type_by_id(btf, v->type);
3281 				m->name_off = vt->name_off;
3282 			}
3283 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3284 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3285 			/* replace '?' prefix with '_' for DATASEC names */
3286 			char *name;
3287 
3288 			name = (char *)btf__name_by_offset(btf, t->name_off);
3289 			if (name[0] == '?')
3290 				name[0] = '_';
3291 		} else if (!has_func && btf_is_func_proto(t)) {
3292 			/* replace FUNC_PROTO with ENUM */
3293 			vlen = btf_vlen(t);
3294 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3295 			t->size = sizeof(__u32); /* kernel enforced */
3296 		} else if (!has_func && btf_is_func(t)) {
3297 			/* replace FUNC with TYPEDEF */
3298 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3299 		} else if (!has_func_global && btf_is_func(t)) {
3300 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3301 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3302 		} else if (!has_float && btf_is_float(t)) {
3303 			/* replace FLOAT with an equally-sized empty STRUCT;
3304 			 * since C compilers do not accept e.g. "float" as a
3305 			 * valid struct name, make it anonymous
3306 			 */
3307 			t->name_off = 0;
3308 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3309 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3310 			/* replace TYPE_TAG with a CONST */
3311 			t->name_off = 0;
3312 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3313 		} else if (!has_enum64 && btf_is_enum(t)) {
3314 			/* clear the kflag */
3315 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3316 		} else if (!has_enum64 && btf_is_enum64(t)) {
3317 			/* replace ENUM64 with a union */
3318 			struct btf_member *m;
3319 
3320 			if (enum64_placeholder_id == 0) {
3321 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3322 				if (enum64_placeholder_id < 0) {
3323 					btf__free(btf);
3324 					return ERR_PTR(enum64_placeholder_id);
3325 				}
3326 				t = (struct btf_type *)btf__type_by_id(btf, i);
3327 			}
3328 
3329 			m = btf_members(t);
3330 			vlen = btf_vlen(t);
3331 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3332 			for (j = 0; j < vlen; j++, m++) {
3333 				m->type = enum64_placeholder_id;
3334 				m->offset = 0;
3335 			}
3336 		}
3337 	}
3338 
3339 	return btf;
3340 }
3341 
libbpf_needs_btf(const struct bpf_object * obj)3342 static bool libbpf_needs_btf(const struct bpf_object *obj)
3343 {
3344 	return obj->efile.btf_maps_shndx >= 0 ||
3345 	       obj->efile.has_st_ops ||
3346 	       obj->nr_extern > 0;
3347 }
3348 
kernel_needs_btf(const struct bpf_object * obj)3349 static bool kernel_needs_btf(const struct bpf_object *obj)
3350 {
3351 	return obj->efile.has_st_ops;
3352 }
3353 
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)3354 static int bpf_object__init_btf(struct bpf_object *obj,
3355 				Elf_Data *btf_data,
3356 				Elf_Data *btf_ext_data)
3357 {
3358 	int err = -ENOENT;
3359 
3360 	if (btf_data) {
3361 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3362 		err = libbpf_get_error(obj->btf);
3363 		if (err) {
3364 			obj->btf = NULL;
3365 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3366 			goto out;
3367 		}
3368 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3369 		btf__set_pointer_size(obj->btf, 8);
3370 	}
3371 	if (btf_ext_data) {
3372 		struct btf_ext_info *ext_segs[3];
3373 		int seg_num, sec_num;
3374 
3375 		if (!obj->btf) {
3376 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3377 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3378 			goto out;
3379 		}
3380 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3381 		err = libbpf_get_error(obj->btf_ext);
3382 		if (err) {
3383 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3384 				BTF_EXT_ELF_SEC, errstr(err));
3385 			obj->btf_ext = NULL;
3386 			goto out;
3387 		}
3388 
3389 		/* setup .BTF.ext to ELF section mapping */
3390 		ext_segs[0] = &obj->btf_ext->func_info;
3391 		ext_segs[1] = &obj->btf_ext->line_info;
3392 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3393 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3394 			struct btf_ext_info *seg = ext_segs[seg_num];
3395 			const struct btf_ext_info_sec *sec;
3396 			const char *sec_name;
3397 			Elf_Scn *scn;
3398 
3399 			if (seg->sec_cnt == 0)
3400 				continue;
3401 
3402 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3403 			if (!seg->sec_idxs) {
3404 				err = -ENOMEM;
3405 				goto out;
3406 			}
3407 
3408 			sec_num = 0;
3409 			for_each_btf_ext_sec(seg, sec) {
3410 				/* preventively increment index to avoid doing
3411 				 * this before every continue below
3412 				 */
3413 				sec_num++;
3414 
3415 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3416 				if (str_is_empty(sec_name))
3417 					continue;
3418 				scn = elf_sec_by_name(obj, sec_name);
3419 				if (!scn)
3420 					continue;
3421 
3422 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3423 			}
3424 		}
3425 	}
3426 out:
3427 	if (err && libbpf_needs_btf(obj)) {
3428 		pr_warn("BTF is required, but is missing or corrupted.\n");
3429 		return err;
3430 	}
3431 	return 0;
3432 }
3433 
compare_vsi_off(const void * _a,const void * _b)3434 static int compare_vsi_off(const void *_a, const void *_b)
3435 {
3436 	const struct btf_var_secinfo *a = _a;
3437 	const struct btf_var_secinfo *b = _b;
3438 
3439 	return a->offset - b->offset;
3440 }
3441 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)3442 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3443 			     struct btf_type *t)
3444 {
3445 	__u32 size = 0, i, vars = btf_vlen(t);
3446 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3447 	struct btf_var_secinfo *vsi;
3448 	bool fixup_offsets = false;
3449 	int err;
3450 
3451 	if (!sec_name) {
3452 		pr_debug("No name found in string section for DATASEC kind.\n");
3453 		return -ENOENT;
3454 	}
3455 
3456 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3457 	 * variable offsets set at the previous step. Further, not every
3458 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3459 	 * all fixups altogether for such sections and go straight to sorting
3460 	 * VARs within their DATASEC.
3461 	 */
3462 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3463 		goto sort_vars;
3464 
3465 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3466 	 * fix this up. But BPF static linker already fixes this up and fills
3467 	 * all the sizes and offsets during static linking. So this step has
3468 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3469 	 * non-extern DATASEC, so the variable fixup loop below handles both
3470 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3471 	 * symbol matching just once.
3472 	 */
3473 	if (t->size == 0) {
3474 		err = find_elf_sec_sz(obj, sec_name, &size);
3475 		if (err || !size) {
3476 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3477 				 sec_name, size, errstr(err));
3478 			return -ENOENT;
3479 		}
3480 
3481 		t->size = size;
3482 		fixup_offsets = true;
3483 	}
3484 
3485 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3486 		const struct btf_type *t_var;
3487 		struct btf_var *var;
3488 		const char *var_name;
3489 		Elf64_Sym *sym;
3490 
3491 		t_var = btf__type_by_id(btf, vsi->type);
3492 		if (!t_var || !btf_is_var(t_var)) {
3493 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3494 			return -EINVAL;
3495 		}
3496 
3497 		var = btf_var(t_var);
3498 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3499 			continue;
3500 
3501 		var_name = btf__name_by_offset(btf, t_var->name_off);
3502 		if (!var_name) {
3503 			pr_debug("sec '%s': failed to find name of DATASEC's member #%u\n",
3504 				 sec_name, i);
3505 			return -ENOENT;
3506 		}
3507 
3508 		sym = find_elf_var_sym(obj, var_name);
3509 		if (IS_ERR(sym)) {
3510 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3511 				 sec_name, var_name);
3512 			return -ENOENT;
3513 		}
3514 
3515 		if (fixup_offsets)
3516 			vsi->offset = sym->st_value;
3517 
3518 		/* if variable is a global/weak symbol, but has restricted
3519 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3520 		 * as static. This follows similar logic for functions (BPF
3521 		 * subprogs) and influences libbpf's further decisions about
3522 		 * whether to make global data BPF array maps as
3523 		 * BPF_F_MMAPABLE.
3524 		 */
3525 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3526 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3527 			var->linkage = BTF_VAR_STATIC;
3528 	}
3529 
3530 sort_vars:
3531 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3532 	return 0;
3533 }
3534 
bpf_object_fixup_btf(struct bpf_object * obj)3535 static int bpf_object_fixup_btf(struct bpf_object *obj)
3536 {
3537 	int i, n, err = 0;
3538 
3539 	if (!obj->btf)
3540 		return 0;
3541 
3542 	n = btf__type_cnt(obj->btf);
3543 	for (i = 1; i < n; i++) {
3544 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3545 
3546 		/* Loader needs to fix up some of the things compiler
3547 		 * couldn't get its hands on while emitting BTF. This
3548 		 * is section size and global variable offset. We use
3549 		 * the info from the ELF itself for this purpose.
3550 		 */
3551 		if (btf_is_datasec(t)) {
3552 			err = btf_fixup_datasec(obj, obj->btf, t);
3553 			if (err)
3554 				return err;
3555 		}
3556 	}
3557 
3558 	return 0;
3559 }
3560 
prog_needs_vmlinux_btf(struct bpf_program * prog)3561 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3562 {
3563 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3564 	    prog->type == BPF_PROG_TYPE_LSM)
3565 		return true;
3566 
3567 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3568 	 * also need vmlinux BTF
3569 	 */
3570 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3571 		return true;
3572 
3573 	return false;
3574 }
3575 
map_needs_vmlinux_btf(struct bpf_map * map)3576 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3577 {
3578 	return bpf_map__is_struct_ops(map);
3579 }
3580 
obj_needs_vmlinux_btf(const struct bpf_object * obj)3581 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3582 {
3583 	struct bpf_program *prog;
3584 	struct bpf_map *map;
3585 	int i;
3586 
3587 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3588 	 * is not specified
3589 	 */
3590 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3591 		return true;
3592 
3593 	/* Support for typed ksyms needs kernel BTF */
3594 	for (i = 0; i < obj->nr_extern; i++) {
3595 		const struct extern_desc *ext;
3596 
3597 		ext = &obj->externs[i];
3598 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3599 			return true;
3600 	}
3601 
3602 	bpf_object__for_each_program(prog, obj) {
3603 		if (!prog->autoload)
3604 			continue;
3605 		if (prog_needs_vmlinux_btf(prog))
3606 			return true;
3607 	}
3608 
3609 	bpf_object__for_each_map(map, obj) {
3610 		if (map_needs_vmlinux_btf(map))
3611 			return true;
3612 	}
3613 
3614 	return false;
3615 }
3616 
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3617 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3618 {
3619 	int err;
3620 
3621 	/* btf_vmlinux could be loaded earlier */
3622 	if (obj->btf_vmlinux || obj->gen_loader)
3623 		return 0;
3624 
3625 	if (!force && !obj_needs_vmlinux_btf(obj))
3626 		return 0;
3627 
3628 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3629 	err = libbpf_get_error(obj->btf_vmlinux);
3630 	if (err) {
3631 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3632 		obj->btf_vmlinux = NULL;
3633 		return err;
3634 	}
3635 	return 0;
3636 }
3637 
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3638 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3639 {
3640 	struct btf *kern_btf = obj->btf;
3641 	bool btf_mandatory, sanitize;
3642 	int i, err = 0;
3643 
3644 	if (!obj->btf)
3645 		return 0;
3646 
3647 	if (!kernel_supports(obj, FEAT_BTF)) {
3648 		if (kernel_needs_btf(obj)) {
3649 			err = -EOPNOTSUPP;
3650 			goto report;
3651 		}
3652 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3653 		return 0;
3654 	}
3655 
3656 	/* Even though some subprogs are global/weak, user might prefer more
3657 	 * permissive BPF verification process that BPF verifier performs for
3658 	 * static functions, taking into account more context from the caller
3659 	 * functions. In such case, they need to mark such subprogs with
3660 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3661 	 * corresponding FUNC BTF type to be marked as static and trigger more
3662 	 * involved BPF verification process.
3663 	 */
3664 	for (i = 0; i < obj->nr_programs; i++) {
3665 		struct bpf_program *prog = &obj->programs[i];
3666 		struct btf_type *t;
3667 		const char *name;
3668 		int j, n;
3669 
3670 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3671 			continue;
3672 
3673 		n = btf__type_cnt(obj->btf);
3674 		for (j = 1; j < n; j++) {
3675 			t = btf_type_by_id(obj->btf, j);
3676 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3677 				continue;
3678 
3679 			name = btf__str_by_offset(obj->btf, t->name_off);
3680 			if (strcmp(name, prog->name) != 0)
3681 				continue;
3682 
3683 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3684 			break;
3685 		}
3686 	}
3687 
3688 	sanitize = btf_needs_sanitization(obj);
3689 	if (sanitize) {
3690 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3691 		if (IS_ERR(kern_btf))
3692 			return PTR_ERR(kern_btf);
3693 	}
3694 
3695 	if (obj->gen_loader) {
3696 		__u32 raw_size = 0;
3697 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3698 
3699 		if (!raw_data)
3700 			return -ENOMEM;
3701 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3702 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3703 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3704 		 */
3705 		btf__set_fd(kern_btf, 0);
3706 	} else {
3707 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3708 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3709 					   obj->log_level ? 1 : 0, obj->token_fd);
3710 	}
3711 	if (sanitize) {
3712 		if (!err) {
3713 			/* move fd to libbpf's BTF */
3714 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3715 			btf__set_fd(kern_btf, -1);
3716 		}
3717 		btf__free(kern_btf);
3718 	}
3719 report:
3720 	if (err) {
3721 		btf_mandatory = kernel_needs_btf(obj);
3722 		if (btf_mandatory) {
3723 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3724 				errstr(err));
3725 		} else {
3726 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3727 				errstr(err));
3728 			err = 0;
3729 		}
3730 	}
3731 	return err;
3732 }
3733 
elf_sym_str(const struct bpf_object * obj,size_t off)3734 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3735 {
3736 	const char *name;
3737 
3738 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3739 	if (!name) {
3740 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3741 			off, obj->path, elf_errmsg(-1));
3742 		return NULL;
3743 	}
3744 
3745 	return name;
3746 }
3747 
elf_sec_str(const struct bpf_object * obj,size_t off)3748 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3749 {
3750 	const char *name;
3751 
3752 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3753 	if (!name) {
3754 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3755 			off, obj->path, elf_errmsg(-1));
3756 		return NULL;
3757 	}
3758 
3759 	return name;
3760 }
3761 
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3762 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3763 {
3764 	Elf_Scn *scn;
3765 
3766 	scn = elf_getscn(obj->efile.elf, idx);
3767 	if (!scn) {
3768 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3769 			idx, obj->path, elf_errmsg(-1));
3770 		return NULL;
3771 	}
3772 	return scn;
3773 }
3774 
elf_sec_by_name(const struct bpf_object * obj,const char * name)3775 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3776 {
3777 	Elf_Scn *scn = NULL;
3778 	Elf *elf = obj->efile.elf;
3779 	const char *sec_name;
3780 
3781 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3782 		sec_name = elf_sec_name(obj, scn);
3783 		if (!sec_name)
3784 			return NULL;
3785 
3786 		if (strcmp(sec_name, name) != 0)
3787 			continue;
3788 
3789 		return scn;
3790 	}
3791 	return NULL;
3792 }
3793 
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3794 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3795 {
3796 	Elf64_Shdr *shdr;
3797 
3798 	if (!scn)
3799 		return NULL;
3800 
3801 	shdr = elf64_getshdr(scn);
3802 	if (!shdr) {
3803 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3804 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3805 		return NULL;
3806 	}
3807 
3808 	return shdr;
3809 }
3810 
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3811 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3812 {
3813 	const char *name;
3814 	Elf64_Shdr *sh;
3815 
3816 	if (!scn)
3817 		return NULL;
3818 
3819 	sh = elf_sec_hdr(obj, scn);
3820 	if (!sh)
3821 		return NULL;
3822 
3823 	name = elf_sec_str(obj, sh->sh_name);
3824 	if (!name) {
3825 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3826 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3827 		return NULL;
3828 	}
3829 
3830 	return name;
3831 }
3832 
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3833 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3834 {
3835 	Elf_Data *data;
3836 
3837 	if (!scn)
3838 		return NULL;
3839 
3840 	data = elf_getdata(scn, 0);
3841 	if (!data) {
3842 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3843 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3844 			obj->path, elf_errmsg(-1));
3845 		return NULL;
3846 	}
3847 
3848 	return data;
3849 }
3850 
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3851 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3852 {
3853 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3854 		return NULL;
3855 
3856 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3857 }
3858 
elf_rel_by_idx(Elf_Data * data,size_t idx)3859 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3860 {
3861 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3862 		return NULL;
3863 
3864 	return (Elf64_Rel *)data->d_buf + idx;
3865 }
3866 
is_sec_name_dwarf(const char * name)3867 static bool is_sec_name_dwarf(const char *name)
3868 {
3869 	/* approximation, but the actual list is too long */
3870 	return str_has_pfx(name, ".debug_");
3871 }
3872 
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3873 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3874 {
3875 	/* no special handling of .strtab */
3876 	if (hdr->sh_type == SHT_STRTAB)
3877 		return true;
3878 
3879 	/* ignore .llvm_addrsig section as well */
3880 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3881 		return true;
3882 
3883 	/* no subprograms will lead to an empty .text section, ignore it */
3884 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3885 	    strcmp(name, ".text") == 0)
3886 		return true;
3887 
3888 	/* DWARF sections */
3889 	if (is_sec_name_dwarf(name))
3890 		return true;
3891 
3892 	if (str_has_pfx(name, ".rel")) {
3893 		name += sizeof(".rel") - 1;
3894 		/* DWARF section relocations */
3895 		if (is_sec_name_dwarf(name))
3896 			return true;
3897 
3898 		/* .BTF and .BTF.ext don't need relocations */
3899 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3900 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3901 			return true;
3902 	}
3903 
3904 	return false;
3905 }
3906 
cmp_progs(const void * _a,const void * _b)3907 static int cmp_progs(const void *_a, const void *_b)
3908 {
3909 	const struct bpf_program *a = _a;
3910 	const struct bpf_program *b = _b;
3911 
3912 	if (a->sec_idx != b->sec_idx)
3913 		return a->sec_idx < b->sec_idx ? -1 : 1;
3914 
3915 	/* sec_insn_off can't be the same within the section */
3916 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3917 }
3918 
bpf_object__elf_collect(struct bpf_object * obj)3919 static int bpf_object__elf_collect(struct bpf_object *obj)
3920 {
3921 	struct elf_sec_desc *sec_desc;
3922 	Elf *elf = obj->efile.elf;
3923 	Elf_Data *btf_ext_data = NULL;
3924 	Elf_Data *btf_data = NULL;
3925 	int idx = 0, err = 0;
3926 	const char *name;
3927 	Elf_Data *data;
3928 	Elf_Scn *scn;
3929 	Elf64_Shdr *sh;
3930 
3931 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3932 	 * section. Since section count retrieved by elf_getshdrnum() does
3933 	 * include sec #0, it is already the necessary size of an array to keep
3934 	 * all the sections.
3935 	 */
3936 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3937 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3938 			obj->path, elf_errmsg(-1));
3939 		return -LIBBPF_ERRNO__FORMAT;
3940 	}
3941 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3942 	if (!obj->efile.secs)
3943 		return -ENOMEM;
3944 
3945 	/* a bunch of ELF parsing functionality depends on processing symbols,
3946 	 * so do the first pass and find the symbol table
3947 	 */
3948 	scn = NULL;
3949 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3950 		sh = elf_sec_hdr(obj, scn);
3951 		if (!sh)
3952 			return -LIBBPF_ERRNO__FORMAT;
3953 
3954 		if (sh->sh_type == SHT_SYMTAB) {
3955 			if (obj->efile.symbols) {
3956 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3957 				return -LIBBPF_ERRNO__FORMAT;
3958 			}
3959 
3960 			data = elf_sec_data(obj, scn);
3961 			if (!data)
3962 				return -LIBBPF_ERRNO__FORMAT;
3963 
3964 			idx = elf_ndxscn(scn);
3965 
3966 			obj->efile.symbols = data;
3967 			obj->efile.symbols_shndx = idx;
3968 			obj->efile.strtabidx = sh->sh_link;
3969 		}
3970 	}
3971 
3972 	if (!obj->efile.symbols) {
3973 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3974 			obj->path);
3975 		return -ENOENT;
3976 	}
3977 
3978 	scn = NULL;
3979 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3980 		idx = elf_ndxscn(scn);
3981 		sec_desc = &obj->efile.secs[idx];
3982 
3983 		sh = elf_sec_hdr(obj, scn);
3984 		if (!sh)
3985 			return -LIBBPF_ERRNO__FORMAT;
3986 
3987 		name = elf_sec_str(obj, sh->sh_name);
3988 		if (!name)
3989 			return -LIBBPF_ERRNO__FORMAT;
3990 
3991 		if (ignore_elf_section(sh, name))
3992 			continue;
3993 
3994 		data = elf_sec_data(obj, scn);
3995 		if (!data)
3996 			return -LIBBPF_ERRNO__FORMAT;
3997 
3998 		pr_debug("elf: section(%d) %s, size %lu, link %d, flags %lx, type=%d\n",
3999 			 idx, name, (unsigned long)data->d_size,
4000 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
4001 			 (int)sh->sh_type);
4002 
4003 		if (strcmp(name, "license") == 0) {
4004 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
4005 			if (err)
4006 				return err;
4007 		} else if (strcmp(name, "version") == 0) {
4008 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
4009 			if (err)
4010 				return err;
4011 		} else if (strcmp(name, "maps") == 0) {
4012 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
4013 			return -ENOTSUP;
4014 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
4015 			obj->efile.btf_maps_shndx = idx;
4016 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
4017 			if (sh->sh_type != SHT_PROGBITS)
4018 				return -LIBBPF_ERRNO__FORMAT;
4019 			btf_data = data;
4020 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
4021 			if (sh->sh_type != SHT_PROGBITS)
4022 				return -LIBBPF_ERRNO__FORMAT;
4023 			btf_ext_data = data;
4024 		} else if (sh->sh_type == SHT_SYMTAB) {
4025 			/* already processed during the first pass above */
4026 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4027 			if (sh->sh_flags & SHF_EXECINSTR) {
4028 				if (strcmp(name, ".text") == 0)
4029 					obj->efile.text_shndx = idx;
4030 				err = bpf_object__add_programs(obj, data, name, idx);
4031 				if (err)
4032 					return err;
4033 			} else if (strcmp(name, DATA_SEC) == 0 ||
4034 				   str_has_pfx(name, DATA_SEC ".")) {
4035 				sec_desc->sec_type = SEC_DATA;
4036 				sec_desc->shdr = sh;
4037 				sec_desc->data = data;
4038 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4039 				   str_has_pfx(name, RODATA_SEC ".")) {
4040 				sec_desc->sec_type = SEC_RODATA;
4041 				sec_desc->shdr = sh;
4042 				sec_desc->data = data;
4043 			} else if (strcmp(name, PERCPU_SEC) == 0 ||
4044 				   str_has_pfx(name, PERCPU_SEC ".")) {
4045 				sec_desc->sec_type = SEC_PERCPU;
4046 				sec_desc->shdr = sh;
4047 				sec_desc->data = data;
4048 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4049 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4050 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4051 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4052 				sec_desc->sec_type = SEC_ST_OPS;
4053 				sec_desc->shdr = sh;
4054 				sec_desc->data = data;
4055 				obj->efile.has_st_ops = true;
4056 			} else if (strcmp(name, ARENA_SEC) == 0) {
4057 				obj->efile.arena_data = data;
4058 				obj->efile.arena_data_shndx = idx;
4059 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4060 				obj->jumptables_data = malloc(data->d_size);
4061 				if (!obj->jumptables_data)
4062 					return -ENOMEM;
4063 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4064 				obj->jumptables_data_sz = data->d_size;
4065 				obj->efile.jumptables_data_shndx = idx;
4066 			} else {
4067 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4068 					idx, name);
4069 			}
4070 		} else if (sh->sh_type == SHT_REL) {
4071 			int targ_sec_idx = sh->sh_info; /* points to other section */
4072 
4073 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4074 			    targ_sec_idx >= obj->efile.sec_cnt)
4075 				return -LIBBPF_ERRNO__FORMAT;
4076 
4077 			/* Only do relo for section with exec instructions */
4078 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4079 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4080 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4081 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4082 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4083 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4084 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4085 					idx, name, targ_sec_idx,
4086 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4087 				continue;
4088 			}
4089 
4090 			sec_desc->sec_type = SEC_RELO;
4091 			sec_desc->shdr = sh;
4092 			sec_desc->data = data;
4093 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4094 							 str_has_pfx(name, BSS_SEC "."))) {
4095 			sec_desc->sec_type = SEC_BSS;
4096 			sec_desc->shdr = sh;
4097 			sec_desc->data = data;
4098 		} else {
4099 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4100 				(size_t)sh->sh_size);
4101 		}
4102 	}
4103 
4104 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4105 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4106 		return -LIBBPF_ERRNO__FORMAT;
4107 	}
4108 
4109 	/* change BPF program insns to native endianness for introspection */
4110 	if (!is_native_endianness(obj))
4111 		bpf_object_bswap_progs(obj);
4112 
4113 	/* sort BPF programs by section name and in-section instruction offset
4114 	 * for faster search
4115 	 */
4116 	if (obj->nr_programs)
4117 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4118 
4119 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4120 }
4121 
sym_is_extern(const Elf64_Sym * sym)4122 static bool sym_is_extern(const Elf64_Sym *sym)
4123 {
4124 	int bind = ELF64_ST_BIND(sym->st_info);
4125 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4126 	return sym->st_shndx == SHN_UNDEF &&
4127 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4128 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4129 }
4130 
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)4131 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4132 {
4133 	int bind = ELF64_ST_BIND(sym->st_info);
4134 	int type = ELF64_ST_TYPE(sym->st_info);
4135 
4136 	/* in .text section */
4137 	if (sym->st_shndx != text_shndx)
4138 		return false;
4139 
4140 	/* local function */
4141 	if (bind == STB_LOCAL && type == STT_SECTION)
4142 		return true;
4143 
4144 	/* global function */
4145 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4146 }
4147 
find_extern_btf_id(const struct btf * btf,const char * ext_name)4148 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4149 {
4150 	const struct btf_type *t;
4151 	const char *tname;
4152 	int i, n;
4153 
4154 	if (!btf)
4155 		return -ESRCH;
4156 
4157 	n = btf__type_cnt(btf);
4158 	for (i = 1; i < n; i++) {
4159 		t = btf__type_by_id(btf, i);
4160 
4161 		if (!btf_is_var(t) && !btf_is_func(t))
4162 			continue;
4163 
4164 		tname = btf__name_by_offset(btf, t->name_off);
4165 		if (strcmp(tname, ext_name))
4166 			continue;
4167 
4168 		if (btf_is_var(t) &&
4169 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4170 			return -EINVAL;
4171 
4172 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4173 			return -EINVAL;
4174 
4175 		return i;
4176 	}
4177 
4178 	return -ENOENT;
4179 }
4180 
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)4181 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4182 	const struct btf_var_secinfo *vs;
4183 	const struct btf_type *t;
4184 	int i, j, n;
4185 
4186 	if (!btf)
4187 		return -ESRCH;
4188 
4189 	n = btf__type_cnt(btf);
4190 	for (i = 1; i < n; i++) {
4191 		t = btf__type_by_id(btf, i);
4192 
4193 		if (!btf_is_datasec(t))
4194 			continue;
4195 
4196 		vs = btf_var_secinfos(t);
4197 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4198 			if (vs->type == ext_btf_id)
4199 				return i;
4200 		}
4201 	}
4202 
4203 	return -ENOENT;
4204 }
4205 
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)4206 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4207 				     bool *is_signed)
4208 {
4209 	const struct btf_type *t;
4210 	const char *name;
4211 
4212 	t = skip_mods_and_typedefs(btf, id, NULL);
4213 	name = btf__name_by_offset(btf, t->name_off);
4214 
4215 	if (is_signed)
4216 		*is_signed = false;
4217 	switch (btf_kind(t)) {
4218 	case BTF_KIND_INT: {
4219 		int enc = btf_int_encoding(t);
4220 
4221 		if (enc & BTF_INT_BOOL)
4222 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4223 		if (is_signed)
4224 			*is_signed = enc & BTF_INT_SIGNED;
4225 		if (t->size == 1)
4226 			return KCFG_CHAR;
4227 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4228 			return KCFG_UNKNOWN;
4229 		return KCFG_INT;
4230 	}
4231 	case BTF_KIND_ENUM:
4232 		if (t->size != 4)
4233 			return KCFG_UNKNOWN;
4234 		if (strcmp(name, "libbpf_tristate"))
4235 			return KCFG_UNKNOWN;
4236 		return KCFG_TRISTATE;
4237 	case BTF_KIND_ENUM64:
4238 		if (strcmp(name, "libbpf_tristate"))
4239 			return KCFG_UNKNOWN;
4240 		return KCFG_TRISTATE;
4241 	case BTF_KIND_ARRAY:
4242 		if (btf_array(t)->nelems == 0)
4243 			return KCFG_UNKNOWN;
4244 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4245 			return KCFG_UNKNOWN;
4246 		return KCFG_CHAR_ARR;
4247 	default:
4248 		return KCFG_UNKNOWN;
4249 	}
4250 }
4251 
cmp_externs(const void * _a,const void * _b)4252 static int cmp_externs(const void *_a, const void *_b)
4253 {
4254 	const struct extern_desc *a = _a;
4255 	const struct extern_desc *b = _b;
4256 
4257 	if (a->type != b->type)
4258 		return a->type < b->type ? -1 : 1;
4259 
4260 	if (a->type == EXT_KCFG) {
4261 		/* descending order by alignment requirements */
4262 		if (a->kcfg.align != b->kcfg.align)
4263 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4264 		/* ascending order by size, within same alignment class */
4265 		if (a->kcfg.sz != b->kcfg.sz)
4266 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4267 	}
4268 
4269 	/* resolve ties by name */
4270 	return strcmp(a->name, b->name);
4271 }
4272 
find_int_btf_id(const struct btf * btf)4273 static int find_int_btf_id(const struct btf *btf)
4274 {
4275 	const struct btf_type *t;
4276 	int i, n;
4277 
4278 	n = btf__type_cnt(btf);
4279 	for (i = 1; i < n; i++) {
4280 		t = btf__type_by_id(btf, i);
4281 
4282 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4283 			return i;
4284 	}
4285 
4286 	return 0;
4287 }
4288 
add_dummy_ksym_var(struct btf * btf)4289 static int add_dummy_ksym_var(struct btf *btf)
4290 {
4291 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4292 	const struct btf_var_secinfo *vs;
4293 	const struct btf_type *sec;
4294 
4295 	if (!btf)
4296 		return 0;
4297 
4298 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4299 					    BTF_KIND_DATASEC);
4300 	if (sec_btf_id < 0)
4301 		return 0;
4302 
4303 	sec = btf__type_by_id(btf, sec_btf_id);
4304 	vs = btf_var_secinfos(sec);
4305 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4306 		const struct btf_type *vt;
4307 
4308 		vt = btf__type_by_id(btf, vs->type);
4309 		if (btf_is_func(vt))
4310 			break;
4311 	}
4312 
4313 	/* No func in ksyms sec.  No need to add dummy var. */
4314 	if (i == btf_vlen(sec))
4315 		return 0;
4316 
4317 	int_btf_id = find_int_btf_id(btf);
4318 	dummy_var_btf_id = btf__add_var(btf,
4319 					"dummy_ksym",
4320 					BTF_VAR_GLOBAL_ALLOCATED,
4321 					int_btf_id);
4322 	if (dummy_var_btf_id < 0)
4323 		pr_warn("cannot create a dummy_ksym var\n");
4324 
4325 	return dummy_var_btf_id;
4326 }
4327 
bpf_object__collect_externs(struct bpf_object * obj)4328 static int bpf_object__collect_externs(struct bpf_object *obj)
4329 {
4330 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4331 	const struct btf_type *t;
4332 	struct extern_desc *ext;
4333 	int i, n, off, dummy_var_btf_id;
4334 	const char *ext_name, *sec_name;
4335 	size_t ext_essent_len;
4336 	Elf_Scn *scn;
4337 	Elf64_Shdr *sh;
4338 
4339 	if (!obj->efile.symbols)
4340 		return 0;
4341 
4342 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4343 	sh = elf_sec_hdr(obj, scn);
4344 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4345 		return -LIBBPF_ERRNO__FORMAT;
4346 
4347 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4348 	if (dummy_var_btf_id < 0)
4349 		return dummy_var_btf_id;
4350 
4351 	n = sh->sh_size / sh->sh_entsize;
4352 	pr_debug("looking for externs among %d symbols...\n", n);
4353 
4354 	for (i = 0; i < n; i++) {
4355 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4356 
4357 		if (!sym)
4358 			return -LIBBPF_ERRNO__FORMAT;
4359 		if (!sym_is_extern(sym))
4360 			continue;
4361 		ext_name = elf_sym_str(obj, sym->st_name);
4362 		if (str_is_empty(ext_name))
4363 			continue;
4364 
4365 		ext = obj->externs;
4366 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4367 		if (!ext)
4368 			return -ENOMEM;
4369 		obj->externs = ext;
4370 		ext = &ext[obj->nr_extern];
4371 		memset(ext, 0, sizeof(*ext));
4372 		obj->nr_extern++;
4373 
4374 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4375 		if (ext->btf_id <= 0) {
4376 			pr_warn("failed to find BTF for extern '%s': %d\n",
4377 				ext_name, ext->btf_id);
4378 			return ext->btf_id;
4379 		}
4380 		t = btf__type_by_id(obj->btf, ext->btf_id);
4381 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4382 		if (!ext->name)
4383 			return -ENOMEM;
4384 		ext->sym_idx = i;
4385 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4386 
4387 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4388 		ext->essent_name = NULL;
4389 		if (ext_essent_len != strlen(ext->name)) {
4390 			ext->essent_name = strndup(ext->name, ext_essent_len);
4391 			if (!ext->essent_name)
4392 				return -ENOMEM;
4393 		}
4394 
4395 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4396 		if (ext->sec_btf_id <= 0) {
4397 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4398 				ext_name, ext->btf_id, ext->sec_btf_id);
4399 			return ext->sec_btf_id;
4400 		}
4401 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4402 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4403 
4404 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4405 			if (btf_is_func(t)) {
4406 				pr_warn("extern function %s is unsupported under %s section\n",
4407 					ext->name, KCONFIG_SEC);
4408 				return -ENOTSUP;
4409 			}
4410 			kcfg_sec = sec;
4411 			ext->type = EXT_KCFG;
4412 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4413 			if (ext->kcfg.sz <= 0) {
4414 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4415 					ext_name, ext->kcfg.sz);
4416 				return ext->kcfg.sz;
4417 			}
4418 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4419 			if (ext->kcfg.align <= 0) {
4420 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4421 					ext_name, ext->kcfg.align);
4422 				return -EINVAL;
4423 			}
4424 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4425 							&ext->kcfg.is_signed);
4426 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4427 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4428 				return -ENOTSUP;
4429 			}
4430 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4431 			ksym_sec = sec;
4432 			ext->type = EXT_KSYM;
4433 			skip_mods_and_typedefs(obj->btf, t->type,
4434 					       &ext->ksym.type_id);
4435 		} else {
4436 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4437 			return -ENOTSUP;
4438 		}
4439 	}
4440 	pr_debug("collected %d externs total\n", obj->nr_extern);
4441 
4442 	if (!obj->nr_extern)
4443 		return 0;
4444 
4445 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4446 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4447 
4448 	/* for .ksyms section, we need to turn all externs into allocated
4449 	 * variables in BTF to pass kernel verification; we do this by
4450 	 * pretending that each extern is a 8-byte variable
4451 	 */
4452 	if (ksym_sec) {
4453 		/* find existing 4-byte integer type in BTF to use for fake
4454 		 * extern variables in DATASEC
4455 		 */
4456 		int int_btf_id = find_int_btf_id(obj->btf);
4457 		/* For extern function, a dummy_var added earlier
4458 		 * will be used to replace the vs->type and
4459 		 * its name string will be used to refill
4460 		 * the missing param's name.
4461 		 */
4462 		const struct btf_type *dummy_var;
4463 
4464 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4465 		for (i = 0; i < obj->nr_extern; i++) {
4466 			ext = &obj->externs[i];
4467 			if (ext->type != EXT_KSYM)
4468 				continue;
4469 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4470 				 i, ext->sym_idx, ext->name);
4471 		}
4472 
4473 		sec = ksym_sec;
4474 		n = btf_vlen(sec);
4475 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4476 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4477 			struct btf_type *vt;
4478 
4479 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4480 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4481 			ext = find_extern_by_name(obj, ext_name);
4482 			if (!ext) {
4483 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4484 					btf_kind_str(vt), ext_name);
4485 				return -ESRCH;
4486 			}
4487 			if (btf_is_func(vt)) {
4488 				const struct btf_type *func_proto;
4489 				struct btf_param *param;
4490 				int j;
4491 
4492 				func_proto = btf__type_by_id(obj->btf,
4493 							     vt->type);
4494 				param = btf_params(func_proto);
4495 				/* Reuse the dummy_var string if the
4496 				 * func proto does not have param name.
4497 				 */
4498 				for (j = 0; j < btf_vlen(func_proto); j++)
4499 					if (param[j].type && !param[j].name_off)
4500 						param[j].name_off =
4501 							dummy_var->name_off;
4502 				vs->type = dummy_var_btf_id;
4503 				vt->info &= ~0xffff;
4504 				vt->info |= BTF_FUNC_GLOBAL;
4505 			} else {
4506 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4507 				vt->type = int_btf_id;
4508 			}
4509 			vs->offset = off;
4510 			vs->size = sizeof(int);
4511 		}
4512 		sec->size = off;
4513 	}
4514 
4515 	if (kcfg_sec) {
4516 		sec = kcfg_sec;
4517 		/* for kcfg externs calculate their offsets within a .kconfig map */
4518 		off = 0;
4519 		for (i = 0; i < obj->nr_extern; i++) {
4520 			ext = &obj->externs[i];
4521 			if (ext->type != EXT_KCFG)
4522 				continue;
4523 
4524 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4525 			off = ext->kcfg.data_off + ext->kcfg.sz;
4526 			pr_debug("extern (kcfg) #%d: symbol %d, off %d, name %s\n",
4527 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4528 		}
4529 		sec->size = off;
4530 		n = btf_vlen(sec);
4531 		for (i = 0; i < n; i++) {
4532 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4533 
4534 			t = btf__type_by_id(obj->btf, vs->type);
4535 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4536 			ext = find_extern_by_name(obj, ext_name);
4537 			if (!ext) {
4538 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4539 					ext_name);
4540 				return -ESRCH;
4541 			}
4542 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4543 			vs->offset = ext->kcfg.data_off;
4544 		}
4545 	}
4546 	return 0;
4547 }
4548 
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)4549 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4550 {
4551 	return prog->sec_idx == obj->efile.text_shndx;
4552 }
4553 
4554 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)4555 bpf_object__find_program_by_name(const struct bpf_object *obj,
4556 				 const char *name)
4557 {
4558 	struct bpf_program *prog;
4559 
4560 	bpf_object__for_each_program(prog, obj) {
4561 		if (prog_is_subprog(obj, prog))
4562 			continue;
4563 		if (!strcmp(prog->name, name))
4564 			return prog;
4565 	}
4566 	return errno = ENOENT, NULL;
4567 }
4568 
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4569 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4570 				      int shndx)
4571 {
4572 	switch (obj->efile.secs[shndx].sec_type) {
4573 	case SEC_BSS:
4574 	case SEC_DATA:
4575 	case SEC_RODATA:
4576 	case SEC_PERCPU:
4577 		return true;
4578 	default:
4579 		return false;
4580 	}
4581 }
4582 
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4583 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4584 				      int shndx)
4585 {
4586 	return shndx == obj->efile.btf_maps_shndx;
4587 }
4588 
4589 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4590 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4591 {
4592 	if (shndx == obj->efile.symbols_shndx)
4593 		return LIBBPF_MAP_KCONFIG;
4594 
4595 	switch (obj->efile.secs[shndx].sec_type) {
4596 	case SEC_BSS:
4597 		return LIBBPF_MAP_BSS;
4598 	case SEC_DATA:
4599 		return LIBBPF_MAP_DATA;
4600 	case SEC_RODATA:
4601 		return LIBBPF_MAP_RODATA;
4602 	case SEC_PERCPU:
4603 		return LIBBPF_MAP_PERCPU;
4604 	default:
4605 		return LIBBPF_MAP_UNSPEC;
4606 	}
4607 }
4608 
bpf_prog_compute_hash(struct bpf_program * prog)4609 static int bpf_prog_compute_hash(struct bpf_program *prog)
4610 {
4611 	struct bpf_insn *purged;
4612 	int i, err = 0;
4613 
4614 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4615 	if (!purged)
4616 		return -ENOMEM;
4617 
4618 	/* If relocations have been done, the map_fd needs to be
4619 	 * discarded for the digest calculation.
4620 	 */
4621 	for (i = 0; i < prog->insns_cnt; i++) {
4622 		purged[i] = prog->insns[i];
4623 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4624 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4625 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4626 			purged[i].imm = 0;
4627 			i++;
4628 			if (i >= prog->insns_cnt ||
4629 			    prog->insns[i].code != 0 ||
4630 			    prog->insns[i].dst_reg != 0 ||
4631 			    prog->insns[i].src_reg != 0 ||
4632 			    prog->insns[i].off != 0) {
4633 				err = -EINVAL;
4634 				goto out;
4635 			}
4636 			purged[i] = prog->insns[i];
4637 			purged[i].imm = 0;
4638 		}
4639 	}
4640 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4641 		      prog->hash);
4642 out:
4643 	free(purged);
4644 	return err;
4645 }
4646 
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)4647 static int bpf_program__record_reloc(struct bpf_program *prog,
4648 				     struct reloc_desc *reloc_desc,
4649 				     __u32 insn_idx, const char *sym_name,
4650 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4651 {
4652 	struct bpf_insn *insn = &prog->insns[insn_idx];
4653 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4654 	struct bpf_object *obj = prog->obj;
4655 	__u32 shdr_idx = sym->st_shndx;
4656 	enum libbpf_map_type type;
4657 	const char *sym_sec_name;
4658 	struct bpf_map *map;
4659 
4660 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4661 		pr_warn("prog '%s': invalid relo against '%s' for insns[%u].code 0x%x\n",
4662 			prog->name, sym_name, insn_idx, insn->code);
4663 		return -LIBBPF_ERRNO__RELOC;
4664 	}
4665 
4666 	if (sym_is_extern(sym)) {
4667 		int sym_idx = ELF64_R_SYM(rel->r_info);
4668 		int i, n = obj->nr_extern;
4669 		struct extern_desc *ext;
4670 
4671 		for (i = 0; i < n; i++) {
4672 			ext = &obj->externs[i];
4673 			if (ext->sym_idx == sym_idx)
4674 				break;
4675 		}
4676 		if (i >= n) {
4677 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4678 				prog->name, sym_name, sym_idx);
4679 			return -LIBBPF_ERRNO__RELOC;
4680 		}
4681 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4682 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4683 		if (insn->code == (BPF_JMP | BPF_CALL))
4684 			reloc_desc->type = RELO_EXTERN_CALL;
4685 		else
4686 			reloc_desc->type = RELO_EXTERN_LD64;
4687 		reloc_desc->insn_idx = insn_idx;
4688 		reloc_desc->ext_idx = i;
4689 		return 0;
4690 	}
4691 
4692 	/* sub-program call relocation */
4693 	if (is_call_insn(insn)) {
4694 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4695 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4696 			return -LIBBPF_ERRNO__RELOC;
4697 		}
4698 		/* text_shndx can be 0, if no default "main" program exists */
4699 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4700 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4701 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4702 				prog->name, sym_name, sym_sec_name);
4703 			return -LIBBPF_ERRNO__RELOC;
4704 		}
4705 		if (sym->st_value % BPF_INSN_SZ) {
4706 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4707 				prog->name, sym_name, (size_t)sym->st_value);
4708 			return -LIBBPF_ERRNO__RELOC;
4709 		}
4710 		reloc_desc->type = RELO_CALL;
4711 		reloc_desc->insn_idx = insn_idx;
4712 		reloc_desc->sym_off = sym->st_value;
4713 		return 0;
4714 	}
4715 
4716 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4717 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4718 			prog->name, sym_name, shdr_idx);
4719 		return -LIBBPF_ERRNO__RELOC;
4720 	}
4721 
4722 	/* loading subprog addresses */
4723 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4724 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4725 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4726 		 */
4727 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4728 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4729 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4730 			return -LIBBPF_ERRNO__RELOC;
4731 		}
4732 
4733 		reloc_desc->type = RELO_SUBPROG_ADDR;
4734 		reloc_desc->insn_idx = insn_idx;
4735 		reloc_desc->sym_off = sym->st_value;
4736 		return 0;
4737 	}
4738 
4739 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4740 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4741 
4742 	/* arena data relocation */
4743 	if (shdr_idx == obj->efile.arena_data_shndx) {
4744 		if (obj->arena_map_idx < 0) {
4745 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4746 				prog->name, insn_idx);
4747 			return -LIBBPF_ERRNO__RELOC;
4748 		}
4749 		reloc_desc->type = RELO_DATA;
4750 		reloc_desc->insn_idx = insn_idx;
4751 		reloc_desc->map_idx = obj->arena_map_idx;
4752 		reloc_desc->sym_off = sym->st_value;
4753 
4754 		map = &obj->maps[obj->arena_map_idx];
4755 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4756 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4757 			 map->sec_offset, insn_idx);
4758 		return 0;
4759 	}
4760 
4761 	/* jump table data relocation */
4762 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4763 		reloc_desc->type = RELO_INSN_ARRAY;
4764 		reloc_desc->insn_idx = insn_idx;
4765 		reloc_desc->map_idx = -1;
4766 		reloc_desc->sym_off = sym->st_value;
4767 		reloc_desc->sym_size = sym->st_size;
4768 		return 0;
4769 	}
4770 
4771 	/* generic map reference relocation */
4772 	if (type == LIBBPF_MAP_UNSPEC) {
4773 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4774 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4775 				prog->name, sym_name, sym_sec_name);
4776 			return -LIBBPF_ERRNO__RELOC;
4777 		}
4778 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4779 			map = &obj->maps[map_idx];
4780 			if (map->libbpf_type != type ||
4781 			    map->sec_idx != sym->st_shndx ||
4782 			    map->sec_offset != sym->st_value)
4783 				continue;
4784 			pr_debug("prog '%s': found map %zu (%s, sec %d, off %zu) for insn #%u\n",
4785 				 prog->name, map_idx, map->name, map->sec_idx,
4786 				 map->sec_offset, insn_idx);
4787 			break;
4788 		}
4789 		if (map_idx >= nr_maps) {
4790 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4791 				prog->name, sym_sec_name, (size_t)sym->st_value);
4792 			return -LIBBPF_ERRNO__RELOC;
4793 		}
4794 		reloc_desc->type = RELO_LD64;
4795 		reloc_desc->insn_idx = insn_idx;
4796 		reloc_desc->map_idx = map_idx;
4797 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4798 		return 0;
4799 	}
4800 
4801 	/* global data map relocation */
4802 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4803 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4804 			prog->name, sym_sec_name);
4805 		return -LIBBPF_ERRNO__RELOC;
4806 	}
4807 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4808 		map = &obj->maps[map_idx];
4809 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4810 			continue;
4811 		pr_debug("prog '%s': found data map %zu (%s, sec %d, off %zu) for insn %u\n",
4812 			 prog->name, map_idx, map->name, map->sec_idx,
4813 			 map->sec_offset, insn_idx);
4814 		break;
4815 	}
4816 	if (map_idx >= nr_maps) {
4817 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4818 			prog->name, sym_sec_name);
4819 		return -LIBBPF_ERRNO__RELOC;
4820 	}
4821 
4822 	reloc_desc->type = RELO_DATA;
4823 	reloc_desc->insn_idx = insn_idx;
4824 	reloc_desc->map_idx = map_idx;
4825 	reloc_desc->sym_off = sym->st_value;
4826 	return 0;
4827 }
4828 
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4829 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4830 {
4831 	return insn_idx >= prog->sec_insn_off &&
4832 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4833 }
4834 
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4835 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4836 						 size_t sec_idx, size_t insn_idx)
4837 {
4838 	int l = 0, r = obj->nr_programs - 1, m;
4839 	struct bpf_program *prog;
4840 
4841 	if (!obj->nr_programs)
4842 		return NULL;
4843 
4844 	while (l < r) {
4845 		m = l + (r - l + 1) / 2;
4846 		prog = &obj->programs[m];
4847 
4848 		if (prog->sec_idx < sec_idx ||
4849 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4850 			l = m;
4851 		else
4852 			r = m - 1;
4853 	}
4854 	/* matching program could be at index l, but it still might be the
4855 	 * wrong one, so we need to double check conditions for the last time
4856 	 */
4857 	prog = &obj->programs[l];
4858 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4859 		return prog;
4860 	return NULL;
4861 }
4862 
4863 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4864 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4865 {
4866 	const char *relo_sec_name, *sec_name;
4867 	size_t sec_idx = shdr->sh_info, sym_idx;
4868 	struct bpf_program *prog;
4869 	struct reloc_desc *relos;
4870 	int err, i, nrels;
4871 	const char *sym_name;
4872 	__u32 insn_idx;
4873 	Elf_Scn *scn;
4874 	Elf_Data *scn_data;
4875 	Elf64_Sym *sym;
4876 	Elf64_Rel *rel;
4877 
4878 	if (sec_idx >= obj->efile.sec_cnt)
4879 		return -EINVAL;
4880 
4881 	scn = elf_sec_by_idx(obj, sec_idx);
4882 	scn_data = elf_sec_data(obj, scn);
4883 	if (!scn_data)
4884 		return -LIBBPF_ERRNO__FORMAT;
4885 
4886 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4887 	sec_name = elf_sec_name(obj, scn);
4888 	if (!relo_sec_name || !sec_name)
4889 		return -EINVAL;
4890 
4891 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4892 		 relo_sec_name, sec_idx, sec_name);
4893 	nrels = shdr->sh_size / shdr->sh_entsize;
4894 
4895 	for (i = 0; i < nrels; i++) {
4896 		rel = elf_rel_by_idx(data, i);
4897 		if (!rel) {
4898 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4899 			return -LIBBPF_ERRNO__FORMAT;
4900 		}
4901 
4902 		sym_idx = ELF64_R_SYM(rel->r_info);
4903 		sym = elf_sym_by_idx(obj, sym_idx);
4904 		if (!sym) {
4905 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4906 				relo_sec_name, sym_idx, i);
4907 			return -LIBBPF_ERRNO__FORMAT;
4908 		}
4909 
4910 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4911 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4912 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4913 			return -LIBBPF_ERRNO__FORMAT;
4914 		}
4915 
4916 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4917 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4918 				relo_sec_name, (size_t)rel->r_offset, i);
4919 			return -LIBBPF_ERRNO__FORMAT;
4920 		}
4921 
4922 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4923 		/* relocations against static functions are recorded as
4924 		 * relocations against the section that contains a function;
4925 		 * in such case, symbol will be STT_SECTION and sym.st_name
4926 		 * will point to empty string (0), so fetch section name
4927 		 * instead
4928 		 */
4929 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4930 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4931 		else
4932 			sym_name = elf_sym_str(obj, sym->st_name);
4933 		sym_name = sym_name ?: "<?";
4934 
4935 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4936 			 relo_sec_name, i, insn_idx, sym_name);
4937 
4938 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4939 		if (!prog) {
4940 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4941 				relo_sec_name, i, sec_name, insn_idx);
4942 			continue;
4943 		}
4944 
4945 		relos = libbpf_reallocarray(prog->reloc_desc,
4946 					    prog->nr_reloc + 1, sizeof(*relos));
4947 		if (!relos)
4948 			return -ENOMEM;
4949 		prog->reloc_desc = relos;
4950 
4951 		/* adjust insn_idx to local BPF program frame of reference */
4952 		insn_idx -= prog->sec_insn_off;
4953 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4954 						insn_idx, sym_name, sym, rel);
4955 		if (err)
4956 			return err;
4957 
4958 		prog->nr_reloc++;
4959 	}
4960 	return 0;
4961 }
4962 
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4963 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4964 {
4965 	int id;
4966 
4967 	if (!obj->btf)
4968 		return -ENOENT;
4969 
4970 	/* if it's BTF-defined map, we don't need to search for type IDs.
4971 	 * For struct_ops map, it does not need btf_key_type_id and
4972 	 * btf_value_type_id.
4973 	 */
4974 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4975 		return 0;
4976 
4977 	/*
4978 	 * LLVM annotates global data differently in BTF, that is,
4979 	 * only as '.data', '.bss', '.percpu' or '.rodata'.
4980 	 */
4981 	if (!bpf_map__is_internal(map))
4982 		return -ENOENT;
4983 
4984 	id = btf__find_by_name(obj->btf, map->real_name);
4985 	if (id < 0)
4986 		return id;
4987 
4988 	map->btf_key_type_id = 0;
4989 	map->btf_value_type_id = id;
4990 	return 0;
4991 }
4992 
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4993 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4994 {
4995 	char file[PATH_MAX], buff[4096];
4996 	FILE *fp;
4997 	__u32 val;
4998 	int err;
4999 
5000 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
5001 	memset(info, 0, sizeof(*info));
5002 
5003 	fp = fopen(file, "re");
5004 	if (!fp) {
5005 		err = -errno;
5006 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
5007 			errstr(err));
5008 		return err;
5009 	}
5010 
5011 	while (fgets(buff, sizeof(buff), fp)) {
5012 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
5013 			info->type = val;
5014 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
5015 			info->key_size = val;
5016 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
5017 			info->value_size = val;
5018 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
5019 			info->max_entries = val;
5020 		else if (sscanf(buff, "map_flags:\t%x", &val) == 1)
5021 			info->map_flags = val;
5022 	}
5023 
5024 	fclose(fp);
5025 
5026 	return 0;
5027 }
5028 
map_is_created(const struct bpf_map * map)5029 static bool map_is_created(const struct bpf_map *map)
5030 {
5031 	return map->obj->state >= OBJ_PREPARED || map->reused;
5032 }
5033 
bpf_map__autocreate(const struct bpf_map * map)5034 bool bpf_map__autocreate(const struct bpf_map *map)
5035 {
5036 	return map->autocreate;
5037 }
5038 
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)5039 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5040 {
5041 	if (map_is_created(map))
5042 		return libbpf_err(-EBUSY);
5043 
5044 	map->autocreate = autocreate;
5045 	return 0;
5046 }
5047 
bpf_map__set_autoattach(struct bpf_map * map,bool autoattach)5048 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5049 {
5050 	if (!bpf_map__is_struct_ops(map))
5051 		return libbpf_err(-EINVAL);
5052 
5053 	map->autoattach = autoattach;
5054 	return 0;
5055 }
5056 
bpf_map__autoattach(const struct bpf_map * map)5057 bool bpf_map__autoattach(const struct bpf_map *map)
5058 {
5059 	return map->autoattach;
5060 }
5061 
bpf_map__reuse_fd(struct bpf_map * map,int fd)5062 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5063 {
5064 	struct bpf_map_info info;
5065 	__u32 len = sizeof(info), name_len;
5066 	int new_fd, err;
5067 	char *new_name;
5068 
5069 	memset(&info, 0, len);
5070 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5071 	if (err && errno == EINVAL)
5072 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5073 	if (err)
5074 		return libbpf_err(err);
5075 
5076 	name_len = strlen(info.name);
5077 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5078 		new_name = strdup(map->name);
5079 	else
5080 		new_name = strdup(info.name);
5081 
5082 	if (!new_name)
5083 		return libbpf_err(-errno);
5084 
5085 	/*
5086 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5087 	 * This is similar to what we do in ensure_good_fd(), but without
5088 	 * closing original FD.
5089 	 */
5090 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5091 	if (new_fd < 0) {
5092 		err = -errno;
5093 		goto err_free_new_name;
5094 	}
5095 
5096 	err = reuse_fd(map->fd, new_fd);
5097 	if (err)
5098 		goto err_free_new_name;
5099 
5100 	free(map->name);
5101 
5102 	map->name = new_name;
5103 	map->def.type = info.type;
5104 	map->def.key_size = info.key_size;
5105 	map->def.value_size = info.value_size;
5106 	map->def.max_entries = info.max_entries;
5107 	map->def.map_flags = info.map_flags;
5108 	map->btf_key_type_id = info.btf_key_type_id;
5109 	map->btf_value_type_id = info.btf_value_type_id;
5110 	map->reused = true;
5111 	map->map_extra = info.map_extra;
5112 
5113 	return 0;
5114 
5115 err_free_new_name:
5116 	free(new_name);
5117 	return libbpf_err(err);
5118 }
5119 
bpf_map__max_entries(const struct bpf_map * map)5120 __u32 bpf_map__max_entries(const struct bpf_map *map)
5121 {
5122 	return map->def.max_entries;
5123 }
5124 
bpf_map__inner_map(struct bpf_map * map)5125 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5126 {
5127 	if (!bpf_map_type__is_map_in_map(map->def.type))
5128 		return errno = EINVAL, NULL;
5129 
5130 	return map->inner_map;
5131 }
5132 
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)5133 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5134 {
5135 	if (map_is_created(map))
5136 		return libbpf_err(-EBUSY);
5137 
5138 	map->def.max_entries = max_entries;
5139 
5140 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5141 	if (map_is_ringbuf(map))
5142 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5143 
5144 	return 0;
5145 }
5146 
bpf_object_prepare_token(struct bpf_object * obj)5147 static int bpf_object_prepare_token(struct bpf_object *obj)
5148 {
5149 	const char *bpffs_path;
5150 	int bpffs_fd = -1, token_fd, err;
5151 	bool mandatory;
5152 	enum libbpf_print_level level;
5153 
5154 	/* token is explicitly prevented */
5155 	if (obj->token_path && obj->token_path[0] == '\0') {
5156 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5157 		return 0;
5158 	}
5159 
5160 	mandatory = obj->token_path != NULL;
5161 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5162 
5163 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5164 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5165 	if (bpffs_fd < 0) {
5166 		err = -errno;
5167 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5168 		     obj->name, errstr(err), bpffs_path,
5169 		     mandatory ? "" : ", skipping optional step...");
5170 		return mandatory ? err : 0;
5171 	}
5172 
5173 	token_fd = bpf_token_create(bpffs_fd, 0);
5174 	close(bpffs_fd);
5175 	if (token_fd < 0) {
5176 		if (!mandatory && token_fd == -ENOENT) {
5177 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5178 				 obj->name, bpffs_path);
5179 			return 0;
5180 		}
5181 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5182 		     obj->name, token_fd, bpffs_path,
5183 		     mandatory ? "" : ", skipping optional step...");
5184 		return mandatory ? token_fd : 0;
5185 	}
5186 
5187 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5188 	if (!obj->feat_cache) {
5189 		close(token_fd);
5190 		return -ENOMEM;
5191 	}
5192 
5193 	obj->token_fd = token_fd;
5194 	obj->feat_cache->token_fd = token_fd;
5195 
5196 	return 0;
5197 }
5198 
5199 static int
bpf_object__probe_loading(struct bpf_object * obj)5200 bpf_object__probe_loading(struct bpf_object *obj)
5201 {
5202 	struct bpf_insn insns[] = {
5203 		BPF_MOV64_IMM(BPF_REG_0, 0),
5204 		BPF_EXIT_INSN(),
5205 	};
5206 	int ret, insn_cnt = ARRAY_SIZE(insns);
5207 
5208 	if (obj->gen_loader || obj->token_fd)
5209 		return 0;
5210 
5211 	ret = bump_rlimit_memlock();
5212 	if (ret)
5213 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5214 			errstr(ret));
5215 
5216 	/* make sure basic loading works */
5217 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5218 	if (ret < 0)
5219 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5220 	if (ret < 0) {
5221 		ret = errno;
5222 		pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
5223 			__func__, errstr(ret));
5224 		return -ret;
5225 	}
5226 	close(ret);
5227 
5228 	return 0;
5229 }
5230 
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)5231 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5232 {
5233 	if (obj->gen_loader)
5234 		/* To generate loader program assume the latest kernel
5235 		 * to avoid doing extra prog_load, map_create syscalls.
5236 		 */
5237 		return true;
5238 
5239 	if (obj->feat_cache)
5240 		return feat_supported(obj->feat_cache, feat_id);
5241 
5242 	return feat_supported(NULL, feat_id);
5243 }
5244 
5245 /* Used in testing to simulate missing features. */
bpf_object_set_feat_cache(struct bpf_object * obj,struct kern_feature_cache * cache)5246 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5247 {
5248 	if (obj->feat_cache)
5249 		free(obj->feat_cache);
5250 	obj->feat_cache = cache;
5251 }
5252 
map_is_reuse_compat(const struct bpf_map * map,int map_fd)5253 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5254 {
5255 	struct bpf_map_info map_info;
5256 	__u32 map_info_len = sizeof(map_info);
5257 	int err;
5258 
5259 	memset(&map_info, 0, map_info_len);
5260 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5261 	if (err && errno == EINVAL)
5262 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5263 	if (err) {
5264 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5265 			errstr(err));
5266 		return false;
5267 	}
5268 
5269 	/*
5270 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5271 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5272 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5273 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5274 	 * existing DEVMAP.
5275 	 */
5276 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5277 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5278 
5279 	return (map_info.type == map->def.type &&
5280 		map_info.key_size == map->def.key_size &&
5281 		map_info.value_size == map->def.value_size &&
5282 		map_info.max_entries == map->def.max_entries &&
5283 		map_info.map_flags == map->def.map_flags &&
5284 		map_info.map_extra == map->map_extra);
5285 }
5286 
5287 static int
bpf_object__reuse_map(struct bpf_map * map)5288 bpf_object__reuse_map(struct bpf_map *map)
5289 {
5290 	int err, pin_fd;
5291 
5292 	pin_fd = bpf_obj_get(map->pin_path);
5293 	if (pin_fd < 0) {
5294 		err = -errno;
5295 		if (err == -ENOENT) {
5296 			pr_debug("found no pinned map to reuse at '%s'\n",
5297 				 map->pin_path);
5298 			return 0;
5299 		}
5300 
5301 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5302 			map->pin_path, errstr(err));
5303 		return err;
5304 	}
5305 
5306 	if (!map_is_reuse_compat(map, pin_fd)) {
5307 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5308 			map->pin_path);
5309 		close(pin_fd);
5310 		return -EINVAL;
5311 	}
5312 
5313 	err = bpf_map__reuse_fd(map, pin_fd);
5314 	close(pin_fd);
5315 	if (err)
5316 		return err;
5317 
5318 	map->pinned = true;
5319 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5320 
5321 	return 0;
5322 }
5323 
5324 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5325 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5326 {
5327 	enum libbpf_map_type map_type = map->libbpf_type;
5328 	bool is_percpu = map_type == LIBBPF_MAP_PERCPU;
5329 	const __u64 update_flags = is_percpu ? BPF_F_ALL_CPUS : 0;
5330 	int err, zero = 0;
5331 	size_t mmap_sz;
5332 
5333 	if (obj->gen_loader) {
5334 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5335 					 map->mmaped, map->def.value_size, update_flags);
5336 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5337 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5338 		return 0;
5339 	}
5340 
5341 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, update_flags);
5342 	if (err) {
5343 		err = -errno;
5344 		pr_warn("map '%s': failed to set initial contents: %s\n",
5345 			bpf_map__name(map), errstr(err));
5346 		return err;
5347 	}
5348 
5349 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5350 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5351 		err = bpf_map_freeze(map->fd);
5352 		if (err) {
5353 			err = -errno;
5354 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5355 				bpf_map__name(map), errstr(err));
5356 			return err;
5357 		}
5358 	}
5359 
5360 	/* Remap anonymous mmap()-ed "map initialization image" as
5361 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5362 	 * memory address. This will cause kernel to change process'
5363 	 * page table to point to a different piece of kernel memory,
5364 	 * but from userspace point of view memory address (and its
5365 	 * contents, being identical at this point) will stay the
5366 	 * same. This mapping will be released by bpf_object__close()
5367 	 * as per normal clean up procedure.
5368 	 */
5369 	mmap_sz = bpf_map_mmap_sz(map);
5370 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5371 		void *mmaped;
5372 		int prot;
5373 
5374 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5375 			prot = PROT_READ;
5376 		else
5377 			prot = PROT_READ | PROT_WRITE;
5378 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5379 		if (mmaped == MAP_FAILED) {
5380 			err = -errno;
5381 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5382 				bpf_map__name(map), errstr(err));
5383 			return err;
5384 		}
5385 		map->mmaped = mmaped;
5386 	} else if (is_percpu) {
5387 		if (mprotect(map->mmaped, mmap_sz, PROT_READ)) {
5388 			err = -errno;
5389 			pr_warn("map '%s': failed to mprotect() contents: %s\n",
5390 				bpf_map__name(map), errstr(err));
5391 			return err;
5392 		}
5393 	} else if (map->mmaped) {
5394 		munmap(map->mmaped, mmap_sz);
5395 		map->mmaped = NULL;
5396 	}
5397 
5398 	return 0;
5399 }
5400 
5401 static void bpf_map__destroy(struct bpf_map *map);
5402 
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5403 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5404 {
5405 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5406 	struct bpf_map_def *def = &map->def;
5407 	const char *map_name = NULL;
5408 	int err = 0, map_fd;
5409 
5410 	if (kernel_supports(obj, FEAT_PROG_NAME))
5411 		map_name = map->name;
5412 	create_attr.map_ifindex = map->map_ifindex;
5413 	create_attr.map_flags = def->map_flags;
5414 	create_attr.numa_node = map->numa_node;
5415 	create_attr.map_extra = map->map_extra;
5416 	create_attr.token_fd = obj->token_fd;
5417 	if (obj->token_fd)
5418 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5419 	if (map->excl_prog) {
5420 		err = bpf_prog_compute_hash(map->excl_prog);
5421 		if (err)
5422 			return err;
5423 
5424 		create_attr.excl_prog_hash = map->excl_prog->hash;
5425 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5426 	}
5427 
5428 	if (bpf_map__is_struct_ops(map)) {
5429 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5430 		if (map->mod_btf_fd >= 0) {
5431 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5432 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5433 		}
5434 	}
5435 
5436 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5437 		create_attr.btf_fd = btf__fd(obj->btf);
5438 		create_attr.btf_key_type_id = map->btf_key_type_id;
5439 		create_attr.btf_value_type_id = map->btf_value_type_id;
5440 	}
5441 
5442 	if (bpf_map_type__is_map_in_map(def->type)) {
5443 		if (map->inner_map) {
5444 			err = map_set_def_max_entries(map->inner_map);
5445 			if (err)
5446 				return err;
5447 			err = bpf_object__create_map(obj, map->inner_map, true);
5448 			if (err) {
5449 				pr_warn("map '%s': failed to create inner map: %s\n",
5450 					map->name, errstr(err));
5451 				return err;
5452 			}
5453 			map->inner_map_fd = map->inner_map->fd;
5454 		}
5455 		if (map->inner_map_fd >= 0)
5456 			create_attr.inner_map_fd = map->inner_map_fd;
5457 	}
5458 
5459 	switch (def->type) {
5460 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5461 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5462 	case BPF_MAP_TYPE_STACK_TRACE:
5463 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5464 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5465 	case BPF_MAP_TYPE_DEVMAP:
5466 	case BPF_MAP_TYPE_DEVMAP_HASH:
5467 	case BPF_MAP_TYPE_CPUMAP:
5468 	case BPF_MAP_TYPE_XSKMAP:
5469 	case BPF_MAP_TYPE_SOCKMAP:
5470 	case BPF_MAP_TYPE_SOCKHASH:
5471 	case BPF_MAP_TYPE_QUEUE:
5472 	case BPF_MAP_TYPE_STACK:
5473 	case BPF_MAP_TYPE_ARENA:
5474 		create_attr.btf_fd = 0;
5475 		create_attr.btf_key_type_id = 0;
5476 		create_attr.btf_value_type_id = 0;
5477 		map->btf_key_type_id = 0;
5478 		map->btf_value_type_id = 0;
5479 		break;
5480 	case BPF_MAP_TYPE_STRUCT_OPS:
5481 		create_attr.btf_value_type_id = 0;
5482 		break;
5483 	default:
5484 		break;
5485 	}
5486 
5487 	if (obj->gen_loader) {
5488 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5489 				    def->key_size, def->value_size, def->max_entries,
5490 				    &create_attr, is_inner ? -1 : map - obj->maps);
5491 		/* We keep pretenting we have valid FD to pass various fd >= 0
5492 		 * checks by just keeping original placeholder FDs in place.
5493 		 * See bpf_object__add_map() comment.
5494 		 * This placeholder fd will not be used with any syscall and
5495 		 * will be reset to -1 eventually.
5496 		 */
5497 		map_fd = map->fd;
5498 	} else {
5499 		map_fd = bpf_map_create(def->type, map_name,
5500 					def->key_size, def->value_size,
5501 					def->max_entries, &create_attr);
5502 	}
5503 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5504 		err = -errno;
5505 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5506 			map->name, errstr(err));
5507 		create_attr.btf_fd = 0;
5508 		create_attr.btf_key_type_id = 0;
5509 		create_attr.btf_value_type_id = 0;
5510 		map->btf_key_type_id = 0;
5511 		map->btf_value_type_id = 0;
5512 		map_fd = bpf_map_create(def->type, map_name,
5513 					def->key_size, def->value_size,
5514 					def->max_entries, &create_attr);
5515 	}
5516 
5517 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5518 		if (obj->gen_loader)
5519 			map->inner_map->fd = -1;
5520 		bpf_map__destroy(map->inner_map);
5521 		zfree(&map->inner_map);
5522 	}
5523 
5524 	if (map_fd < 0)
5525 		return map_fd;
5526 
5527 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5528 	if (map->fd == map_fd)
5529 		return 0;
5530 
5531 	/* Keep placeholder FD value but now point it to the BPF map object.
5532 	 * This way everything that relied on this map's FD (e.g., relocated
5533 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5534 	 * map->fd stays valid but now point to what map_fd points to.
5535 	 */
5536 	return reuse_fd(map->fd, map_fd);
5537 }
5538 
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5539 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5540 {
5541 	const struct bpf_map *targ_map;
5542 	unsigned int i;
5543 	int fd, err = 0;
5544 
5545 	for (i = 0; i < map->init_slots_sz; i++) {
5546 		if (!map->init_slots[i])
5547 			continue;
5548 
5549 		targ_map = map->init_slots[i];
5550 		fd = targ_map->fd;
5551 
5552 		if (obj->gen_loader) {
5553 			bpf_gen__populate_outer_map(obj->gen_loader,
5554 						    map - obj->maps, i,
5555 						    targ_map - obj->maps);
5556 		} else {
5557 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5558 		}
5559 		if (err) {
5560 			err = -errno;
5561 			pr_warn("map '%s': failed to initialize slot [%u] to map '%s' fd=%d: %s\n",
5562 				map->name, i, targ_map->name, fd, errstr(err));
5563 			return err;
5564 		}
5565 		pr_debug("map '%s': slot [%u] set to map '%s' fd=%d\n",
5566 			 map->name, i, targ_map->name, fd);
5567 	}
5568 
5569 	zfree(&map->init_slots);
5570 	map->init_slots_sz = 0;
5571 
5572 	return 0;
5573 }
5574 
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5575 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5576 {
5577 	const struct bpf_program *targ_prog;
5578 	unsigned int i;
5579 	int fd, err;
5580 
5581 	if (obj->gen_loader)
5582 		return -ENOTSUP;
5583 
5584 	for (i = 0; i < map->init_slots_sz; i++) {
5585 		if (!map->init_slots[i])
5586 			continue;
5587 
5588 		targ_prog = map->init_slots[i];
5589 		fd = bpf_program__fd(targ_prog);
5590 
5591 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5592 		if (err) {
5593 			err = -errno;
5594 			pr_warn("map '%s': failed to initialize slot [%u] to prog '%s' fd=%d: %s\n",
5595 				map->name, i, targ_prog->name, fd, errstr(err));
5596 			return err;
5597 		}
5598 		pr_debug("map '%s': slot [%u] set to prog '%s' fd=%d\n",
5599 			 map->name, i, targ_prog->name, fd);
5600 	}
5601 
5602 	zfree(&map->init_slots);
5603 	map->init_slots_sz = 0;
5604 
5605 	return 0;
5606 }
5607 
bpf_object_init_prog_arrays(struct bpf_object * obj)5608 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5609 {
5610 	struct bpf_map *map;
5611 	int i, err;
5612 
5613 	for (i = 0; i < obj->nr_maps; i++) {
5614 		map = &obj->maps[i];
5615 
5616 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5617 			continue;
5618 
5619 		err = init_prog_array_slots(obj, map);
5620 		if (err < 0)
5621 			return err;
5622 	}
5623 	return 0;
5624 }
5625 
map_set_def_max_entries(struct bpf_map * map)5626 static int map_set_def_max_entries(struct bpf_map *map)
5627 {
5628 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5629 		int nr_cpus;
5630 
5631 		nr_cpus = libbpf_num_possible_cpus();
5632 		if (nr_cpus < 0) {
5633 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5634 				map->name, nr_cpus);
5635 			return nr_cpus;
5636 		}
5637 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5638 		map->def.max_entries = nr_cpus;
5639 	}
5640 
5641 	return 0;
5642 }
5643 
5644 static int
bpf_object__create_maps(struct bpf_object * obj)5645 bpf_object__create_maps(struct bpf_object *obj)
5646 {
5647 	struct bpf_map *map;
5648 	unsigned int i, j;
5649 	int err;
5650 	bool retried;
5651 
5652 	for (i = 0; i < obj->nr_maps; i++) {
5653 		map = &obj->maps[i];
5654 
5655 		/* To support old kernels, we skip creating global data maps
5656 		 * (.rodata, .data, .kconfig, etc); later on, during program
5657 		 * loading, if we detect that at least one of the to-be-loaded
5658 		 * programs is referencing any global data map, we'll error
5659 		 * out with program name and relocation index logged.
5660 		 * This approach allows to accommodate Clang emitting
5661 		 * unnecessary .rodata.str1.1 sections for string literals,
5662 		 * but also it allows to have CO-RE applications that use
5663 		 * global variables in some of BPF programs, but not others.
5664 		 * If those global variable-using programs are not loaded at
5665 		 * runtime due to bpf_program__set_autoload(prog, false),
5666 		 * bpf_object loading will succeed just fine even on old
5667 		 * kernels.
5668 		 * Same skipping applies to percpu data.
5669 		 */
5670 		if (bpf_map__is_internal(map)) {
5671 			bool is_percpu = map->libbpf_type == LIBBPF_MAP_PERCPU;
5672 			enum kern_feature_id feat_id;
5673 
5674 			feat_id = is_percpu ? FEAT_PERCPU_DATA : FEAT_GLOBAL_DATA;
5675 			if (!kernel_supports(obj, feat_id))
5676 				map->autocreate = false;
5677 		}
5678 
5679 		if (!map->autocreate) {
5680 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5681 			continue;
5682 		}
5683 
5684 		err = map_set_def_max_entries(map);
5685 		if (err)
5686 			goto err_out;
5687 
5688 		retried = false;
5689 retry:
5690 		if (map->pin_path) {
5691 			err = bpf_object__reuse_map(map);
5692 			if (err) {
5693 				pr_warn("map '%s': error reusing pinned map\n",
5694 					map->name);
5695 				goto err_out;
5696 			}
5697 			if (retried && map->fd < 0) {
5698 				pr_warn("map '%s': cannot find pinned map\n",
5699 					map->name);
5700 				err = -ENOENT;
5701 				goto err_out;
5702 			}
5703 		}
5704 
5705 		if (map->reused) {
5706 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5707 				 map->name, map->fd);
5708 		} else {
5709 			err = bpf_object__create_map(obj, map, false);
5710 			if (err)
5711 				goto err_out;
5712 
5713 			pr_debug("map '%s': created successfully, fd=%d\n",
5714 				 map->name, map->fd);
5715 
5716 			if (bpf_map__is_internal(map)) {
5717 				err = bpf_object__populate_internal_map(obj, map);
5718 				if (err < 0)
5719 					goto err_out;
5720 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5721 				map->mmaped = mmap((void *)(long)map->map_extra,
5722 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5723 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5724 						   map->fd, 0);
5725 				if (map->mmaped == MAP_FAILED) {
5726 					err = -errno;
5727 					map->mmaped = NULL;
5728 					pr_warn("map '%s': failed to mmap arena: %s\n",
5729 						map->name, errstr(err));
5730 					return err;
5731 				}
5732 				if (obj->arena_data) {
5733 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5734 						obj->arena_data_sz);
5735 					zfree(&obj->arena_data);
5736 				}
5737 			}
5738 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5739 				err = init_map_in_map_slots(obj, map);
5740 				if (err < 0)
5741 					goto err_out;
5742 			}
5743 		}
5744 
5745 		if (map->pin_path && !map->pinned) {
5746 			err = bpf_map__pin(map, NULL);
5747 			if (err) {
5748 				if (!retried && err == -EEXIST) {
5749 					retried = true;
5750 					goto retry;
5751 				}
5752 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5753 					map->name, map->pin_path, errstr(err));
5754 				goto err_out;
5755 			}
5756 		}
5757 	}
5758 
5759 	return 0;
5760 
5761 err_out:
5762 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5763 	pr_perm_msg(err);
5764 	for (j = 0; j < i; j++)
5765 		zclose(obj->maps[j].fd);
5766 	return err;
5767 }
5768 
bpf_core_is_flavor_sep(const char * s)5769 static bool bpf_core_is_flavor_sep(const char *s)
5770 {
5771 	/* check X___Y name pattern, where X and Y are not underscores */
5772 	return s[0] != '_' &&				      /* X */
5773 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5774 	       s[4] != '_';				      /* Y */
5775 }
5776 
5777 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5778  * before last triple underscore. Struct name part after last triple
5779  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5780  */
bpf_core_essential_name_len(const char * name)5781 size_t bpf_core_essential_name_len(const char *name)
5782 {
5783 	size_t n = strlen(name);
5784 	int i;
5785 
5786 	for (i = n - 5; i >= 0; i--) {
5787 		if (bpf_core_is_flavor_sep(name + i))
5788 			return i + 1;
5789 	}
5790 	return n;
5791 }
5792 
bpf_core_free_cands(struct bpf_core_cand_list * cands)5793 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5794 {
5795 	if (!cands)
5796 		return;
5797 
5798 	free(cands->cands);
5799 	free(cands);
5800 }
5801 
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)5802 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5803 		       size_t local_essent_len,
5804 		       const struct btf *targ_btf,
5805 		       const char *targ_btf_name,
5806 		       int targ_start_id,
5807 		       struct bpf_core_cand_list *cands)
5808 {
5809 	struct bpf_core_cand *new_cands, *cand;
5810 	const struct btf_type *t, *local_t;
5811 	const char *targ_name, *local_name;
5812 	size_t targ_essent_len;
5813 	int n, i;
5814 
5815 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5816 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5817 
5818 	n = btf__type_cnt(targ_btf);
5819 	for (i = targ_start_id; i < n; i++) {
5820 		t = btf__type_by_id(targ_btf, i);
5821 		if (!btf_kind_core_compat(t, local_t))
5822 			continue;
5823 
5824 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5825 		if (str_is_empty(targ_name))
5826 			continue;
5827 
5828 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5829 		if (targ_essent_len != local_essent_len)
5830 			continue;
5831 
5832 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5833 			continue;
5834 
5835 		pr_debug("CO-RE relocating [%u] %s %s: found target candidate [%d] %s %s in [%s]\n",
5836 			 local_cand->id, btf_kind_str(local_t),
5837 			 local_name, i, btf_kind_str(t), targ_name,
5838 			 targ_btf_name);
5839 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5840 					      sizeof(*cands->cands));
5841 		if (!new_cands)
5842 			return -ENOMEM;
5843 
5844 		cand = &new_cands[cands->len];
5845 		cand->btf = targ_btf;
5846 		cand->id = i;
5847 
5848 		cands->cands = new_cands;
5849 		cands->len++;
5850 	}
5851 	return 0;
5852 }
5853 
load_module_btfs(struct bpf_object * obj)5854 static int load_module_btfs(struct bpf_object *obj)
5855 {
5856 	struct bpf_btf_info info;
5857 	struct module_btf *mod_btf;
5858 	struct btf *btf;
5859 	char name[64];
5860 	__u32 id = 0, len;
5861 	int err, fd;
5862 
5863 	if (obj->btf_modules_loaded)
5864 		return 0;
5865 
5866 	if (obj->gen_loader)
5867 		return 0;
5868 
5869 	/* don't do this again, even if we find no module BTFs */
5870 	obj->btf_modules_loaded = true;
5871 
5872 	/* kernel too old to support module BTFs */
5873 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5874 		return 0;
5875 
5876 	while (true) {
5877 		err = bpf_btf_get_next_id(id, &id);
5878 		if (err && errno == ENOENT)
5879 			return 0;
5880 		if (err && errno == EPERM) {
5881 			pr_debug("skipping module BTFs loading, missing privileges\n");
5882 			return 0;
5883 		}
5884 		if (err) {
5885 			err = -errno;
5886 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5887 			return err;
5888 		}
5889 
5890 		fd = bpf_btf_get_fd_by_id(id);
5891 		if (fd < 0) {
5892 			if (errno == ENOENT)
5893 				continue; /* expected race: BTF was unloaded */
5894 			err = -errno;
5895 			pr_warn("failed to get BTF object #%u FD: %s\n", id, errstr(err));
5896 			return err;
5897 		}
5898 
5899 		len = sizeof(info);
5900 		memset(&info, 0, sizeof(info));
5901 		info.name = ptr_to_u64(name);
5902 		info.name_len = sizeof(name);
5903 
5904 		btf = NULL;
5905 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5906 		if (err) {
5907 			err = -errno;
5908 			pr_warn("failed to get BTF object #%u info: %s\n", id, errstr(err));
5909 			break;
5910 		}
5911 
5912 		/* ignore non-module BTFs */
5913 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5914 			close(fd);
5915 			continue;
5916 		}
5917 
5918 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5919 		err = libbpf_get_error(btf);
5920 		if (err) {
5921 			pr_warn("failed to load module [%s]'s BTF object #%u: %s\n",
5922 				name, id, errstr(err));
5923 			break;
5924 		}
5925 
5926 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5927 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5928 		if (err)
5929 			break;
5930 
5931 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
5932 
5933 		mod_btf->btf = btf;
5934 		mod_btf->id = id;
5935 		mod_btf->fd = fd;
5936 		mod_btf->name = strdup(name);
5937 		if (!mod_btf->name) {
5938 			err = -ENOMEM;
5939 			break;
5940 		}
5941 		obj->btf_module_cnt++;
5942 	}
5943 
5944 	if (err) {
5945 		btf__free(btf);
5946 		close(fd);
5947 	}
5948 	return err;
5949 }
5950 
5951 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5952 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5953 {
5954 	struct bpf_core_cand local_cand = {};
5955 	struct bpf_core_cand_list *cands;
5956 	const struct btf *main_btf;
5957 	const struct btf_type *local_t;
5958 	const char *local_name;
5959 	size_t local_essent_len;
5960 	int err, i;
5961 
5962 	local_cand.btf = local_btf;
5963 	local_cand.id = local_type_id;
5964 	local_t = btf__type_by_id(local_btf, local_type_id);
5965 	if (!local_t)
5966 		return ERR_PTR(-EINVAL);
5967 
5968 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5969 	if (str_is_empty(local_name))
5970 		return ERR_PTR(-EINVAL);
5971 	local_essent_len = bpf_core_essential_name_len(local_name);
5972 
5973 	cands = calloc(1, sizeof(*cands));
5974 	if (!cands)
5975 		return ERR_PTR(-ENOMEM);
5976 
5977 	/* Attempt to find target candidates in vmlinux BTF first */
5978 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5979 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5980 	if (err)
5981 		goto err_out;
5982 
5983 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5984 	if (cands->len)
5985 		return cands;
5986 
5987 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5988 	if (obj->btf_vmlinux_override)
5989 		return cands;
5990 
5991 	/* now look through module BTFs, trying to still find candidates */
5992 	err = load_module_btfs(obj);
5993 	if (err)
5994 		goto err_out;
5995 
5996 	for (i = 0; i < obj->btf_module_cnt; i++) {
5997 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5998 					 obj->btf_modules[i].btf,
5999 					 obj->btf_modules[i].name,
6000 					 btf__type_cnt(obj->btf_vmlinux),
6001 					 cands);
6002 		if (err)
6003 			goto err_out;
6004 	}
6005 
6006 	return cands;
6007 err_out:
6008 	bpf_core_free_cands(cands);
6009 	return ERR_PTR(err);
6010 }
6011 
6012 /* Check local and target types for compatibility. This check is used for
6013  * type-based CO-RE relocations and follow slightly different rules than
6014  * field-based relocations. This function assumes that root types were already
6015  * checked for name match. Beyond that initial root-level name check, names
6016  * are completely ignored. Compatibility rules are as follows:
6017  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
6018  *     kind should match for local and target types (i.e., STRUCT is not
6019  *     compatible with UNION);
6020  *   - for ENUMs, the size is ignored;
6021  *   - for INT, size and signedness are ignored;
6022  *   - for ARRAY, dimensionality is ignored, element types are checked for
6023  *     compatibility recursively;
6024  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
6025  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
6026  *   - FUNC_PROTOs are compatible if they have compatible signature: same
6027  *     number of input args and compatible return and argument types.
6028  * These rules are not set in stone and probably will be adjusted as we get
6029  * more experience with using BPF CO-RE relocations.
6030  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)6031 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6032 			      const struct btf *targ_btf, __u32 targ_id)
6033 {
6034 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
6035 }
6036 
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)6037 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
6038 			 const struct btf *targ_btf, __u32 targ_id)
6039 {
6040 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
6041 }
6042 
bpf_core_hash_fn(const long key,void * ctx)6043 static size_t bpf_core_hash_fn(const long key, void *ctx)
6044 {
6045 	return key;
6046 }
6047 
bpf_core_equal_fn(const long k1,const long k2,void * ctx)6048 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6049 {
6050 	return k1 == k2;
6051 }
6052 
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)6053 static int record_relo_core(struct bpf_program *prog,
6054 			    const struct bpf_core_relo *core_relo, int insn_idx)
6055 {
6056 	struct reloc_desc *relos, *relo;
6057 
6058 	relos = libbpf_reallocarray(prog->reloc_desc,
6059 				    prog->nr_reloc + 1, sizeof(*relos));
6060 	if (!relos)
6061 		return -ENOMEM;
6062 	relo = &relos[prog->nr_reloc];
6063 	relo->type = RELO_CORE;
6064 	relo->insn_idx = insn_idx;
6065 	relo->core_relo = core_relo;
6066 	prog->reloc_desc = relos;
6067 	prog->nr_reloc++;
6068 	return 0;
6069 }
6070 
find_relo_core(struct bpf_program * prog,int insn_idx)6071 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6072 {
6073 	struct reloc_desc *relo;
6074 	int i;
6075 
6076 	for (i = 0; i < prog->nr_reloc; i++) {
6077 		relo = &prog->reloc_desc[i];
6078 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6079 			continue;
6080 
6081 		return relo->core_relo;
6082 	}
6083 
6084 	return NULL;
6085 }
6086 
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)6087 static int bpf_core_resolve_relo(struct bpf_program *prog,
6088 				 const struct bpf_core_relo *relo,
6089 				 int relo_idx,
6090 				 const struct btf *local_btf,
6091 				 struct hashmap *cand_cache,
6092 				 struct bpf_core_relo_res *targ_res)
6093 {
6094 	struct bpf_core_spec specs_scratch[3] = {};
6095 	struct bpf_core_cand_list *cands = NULL;
6096 	const char *prog_name = prog->name;
6097 	const struct btf_type *local_type;
6098 	const char *local_name;
6099 	__u32 local_id = relo->type_id;
6100 	int err;
6101 
6102 	local_type = btf__type_by_id(local_btf, local_id);
6103 	if (!local_type)
6104 		return -EINVAL;
6105 
6106 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6107 	if (!local_name)
6108 		return -EINVAL;
6109 
6110 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6111 	    !hashmap__find(cand_cache, local_id, &cands)) {
6112 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6113 		if (IS_ERR(cands)) {
6114 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%u] %s %s: %ld\n",
6115 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6116 				local_name, PTR_ERR(cands));
6117 			return PTR_ERR(cands);
6118 		}
6119 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6120 		if (err) {
6121 			bpf_core_free_cands(cands);
6122 			return err;
6123 		}
6124 	}
6125 
6126 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6127 				       targ_res);
6128 }
6129 
6130 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)6131 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6132 {
6133 	const struct btf_ext_info_sec *sec;
6134 	struct bpf_core_relo_res targ_res;
6135 	const struct bpf_core_relo *rec;
6136 	const struct btf_ext_info *seg;
6137 	struct hashmap_entry *entry;
6138 	struct hashmap *cand_cache = NULL;
6139 	struct bpf_program *prog;
6140 	struct bpf_insn *insn;
6141 	const char *sec_name;
6142 	int i, err = 0, insn_idx, sec_idx, sec_num;
6143 
6144 	if (obj->btf_ext->core_relo_info.len == 0)
6145 		return 0;
6146 
6147 	if (targ_btf_path) {
6148 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6149 		err = libbpf_get_error(obj->btf_vmlinux_override);
6150 		if (err) {
6151 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6152 			return err;
6153 		}
6154 	}
6155 
6156 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6157 	if (IS_ERR(cand_cache)) {
6158 		err = PTR_ERR(cand_cache);
6159 		goto out;
6160 	}
6161 
6162 	seg = &obj->btf_ext->core_relo_info;
6163 	sec_num = 0;
6164 	for_each_btf_ext_sec(seg, sec) {
6165 		sec_idx = seg->sec_idxs[sec_num];
6166 		sec_num++;
6167 
6168 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6169 		if (str_is_empty(sec_name)) {
6170 			err = -EINVAL;
6171 			goto out;
6172 		}
6173 
6174 		pr_debug("sec '%s': found %u CO-RE relocations\n", sec_name, sec->num_info);
6175 
6176 		for_each_btf_ext_rec(seg, sec, i, rec) {
6177 			if (rec->insn_off % BPF_INSN_SZ)
6178 				return -EINVAL;
6179 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6180 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6181 			if (!prog) {
6182 				/* When __weak subprog is "overridden" by another instance
6183 				 * of the subprog from a different object file, linker still
6184 				 * appends all the .BTF.ext info that used to belong to that
6185 				 * eliminated subprogram.
6186 				 * This is similar to what x86-64 linker does for relocations.
6187 				 * So just ignore such relocations just like we ignore
6188 				 * subprog instructions when discovering subprograms.
6189 				 */
6190 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6191 					 sec_name, i, insn_idx);
6192 				continue;
6193 			}
6194 			/* no need to apply CO-RE relocation if the program is
6195 			 * not going to be loaded
6196 			 */
6197 			if (!prog->autoload)
6198 				continue;
6199 
6200 			/* adjust insn_idx from section frame of reference to the local
6201 			 * program's frame of reference; (sub-)program code is not yet
6202 			 * relocated, so it's enough to just subtract in-section offset
6203 			 */
6204 			insn_idx = insn_idx - prog->sec_insn_off;
6205 			if (insn_idx >= prog->insns_cnt)
6206 				return -EINVAL;
6207 			insn = &prog->insns[insn_idx];
6208 
6209 			err = record_relo_core(prog, rec, insn_idx);
6210 			if (err) {
6211 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6212 					prog->name, i, errstr(err));
6213 				goto out;
6214 			}
6215 
6216 			if (prog->obj->gen_loader)
6217 				continue;
6218 
6219 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6220 			if (err) {
6221 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6222 					prog->name, i, errstr(err));
6223 				goto out;
6224 			}
6225 
6226 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6227 			if (err) {
6228 				pr_warn("prog '%s': relo #%d: failed to patch insn #%d: %s\n",
6229 					prog->name, i, insn_idx, errstr(err));
6230 				goto out;
6231 			}
6232 		}
6233 	}
6234 
6235 out:
6236 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6237 	btf__free(obj->btf_vmlinux_override);
6238 	obj->btf_vmlinux_override = NULL;
6239 
6240 	if (!IS_ERR_OR_NULL(cand_cache)) {
6241 		hashmap__for_each_entry(cand_cache, entry, i) {
6242 			bpf_core_free_cands(entry->pvalue);
6243 		}
6244 		hashmap__free(cand_cache);
6245 	}
6246 	return err;
6247 }
6248 
6249 /* base map load ldimm64 special constant, used also for log fixup logic */
6250 #define POISON_LDIMM64_MAP_BASE 2001000000
6251 #define POISON_LDIMM64_MAP_PFX "200100"
6252 
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)6253 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6254 			       int insn_idx, struct bpf_insn *insn,
6255 			       int map_idx, const struct bpf_map *map)
6256 {
6257 	int i;
6258 
6259 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6260 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6261 
6262 	/* we turn single ldimm64 into two identical invalid calls */
6263 	for (i = 0; i < 2; i++) {
6264 		insn->code = BPF_JMP | BPF_CALL;
6265 		insn->dst_reg = 0;
6266 		insn->src_reg = 0;
6267 		insn->off = 0;
6268 		/* if this instruction is reachable (not a dead code),
6269 		 * verifier will complain with something like:
6270 		 * invalid func unknown#2001000123
6271 		 * where lower 123 is map index into obj->maps[] array
6272 		 */
6273 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6274 
6275 		insn++;
6276 	}
6277 }
6278 
6279 /* unresolved kfunc call special constant, used also for log fixup logic */
6280 #define POISON_CALL_KFUNC_BASE 2002000000
6281 #define POISON_CALL_KFUNC_PFX "2002"
6282 
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)6283 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6284 			      int insn_idx, struct bpf_insn *insn,
6285 			      int ext_idx, const struct extern_desc *ext)
6286 {
6287 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6288 		 prog->name, relo_idx, insn_idx, ext->name);
6289 
6290 	/* we turn kfunc call into invalid helper call with identifiable constant */
6291 	insn->code = BPF_JMP | BPF_CALL;
6292 	insn->dst_reg = 0;
6293 	insn->src_reg = 0;
6294 	insn->off = 0;
6295 	/* if this instruction is reachable (not a dead code),
6296 	 * verifier will complain with something like:
6297 	 * invalid func unknown#2001000123
6298 	 * where lower 123 is extern index into obj->externs[] array
6299 	 */
6300 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6301 }
6302 
find_jt_map(struct bpf_object * obj,struct bpf_program * prog,unsigned int sym_off)6303 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6304 {
6305 	size_t i;
6306 
6307 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6308 		/*
6309 		 * This might happen that same offset is used for two different
6310 		 * programs (as jump tables can be the same). However, for
6311 		 * different programs different maps should be created.
6312 		 */
6313 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6314 		    obj->jumptable_maps[i].prog == prog)
6315 			return obj->jumptable_maps[i].fd;
6316 	}
6317 
6318 	return -ENOENT;
6319 }
6320 
add_jt_map(struct bpf_object * obj,struct bpf_program * prog,unsigned int sym_off,int map_fd)6321 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6322 {
6323 	size_t cnt = obj->jumptable_map_cnt;
6324 	size_t size = sizeof(obj->jumptable_maps[0]);
6325 	void *tmp;
6326 
6327 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6328 	if (!tmp)
6329 		return -ENOMEM;
6330 
6331 	obj->jumptable_maps = tmp;
6332 	obj->jumptable_maps[cnt].prog = prog;
6333 	obj->jumptable_maps[cnt].sym_off = sym_off;
6334 	obj->jumptable_maps[cnt].fd = map_fd;
6335 	obj->jumptable_map_cnt++;
6336 
6337 	return 0;
6338 }
6339 
find_subprog_idx(struct bpf_program * prog,int insn_idx)6340 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6341 {
6342 	int i;
6343 
6344 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6345 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6346 			return i;
6347 	}
6348 
6349 	return -1;
6350 }
6351 
create_jt_map(struct bpf_object * obj,struct bpf_program * prog,struct reloc_desc * relo)6352 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6353 {
6354 	const __u32 jt_entry_size = 8;
6355 	unsigned int sym_off = relo->sym_off;
6356 	int jt_size = relo->sym_size;
6357 	__u32 max_entries = jt_size / jt_entry_size;
6358 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6359 	struct bpf_insn_array_value val = {};
6360 	int subprog_idx;
6361 	int map_fd, err;
6362 	__u64 insn_off;
6363 	__u64 *jt;
6364 	__u32 i;
6365 
6366 	map_fd = find_jt_map(obj, prog, sym_off);
6367 	if (map_fd >= 0)
6368 		return map_fd;
6369 
6370 	if (sym_off % jt_entry_size) {
6371 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6372 			sym_off, jt_entry_size);
6373 		return -EINVAL;
6374 	}
6375 
6376 	if (jt_size % jt_entry_size) {
6377 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6378 			jt_size, jt_entry_size);
6379 		return -EINVAL;
6380 	}
6381 
6382 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6383 				4, value_size, max_entries, NULL);
6384 	if (map_fd < 0)
6385 		return map_fd;
6386 
6387 	if (!obj->jumptables_data) {
6388 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6389 		err = -EINVAL;
6390 		goto err_close;
6391 	}
6392 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6393 		pr_warn("map '.jumptables': jumptables_data size is %zu, trying to access %u\n",
6394 			obj->jumptables_data_sz, sym_off + jt_size);
6395 		err = -EINVAL;
6396 		goto err_close;
6397 	}
6398 
6399 	subprog_idx = -1; /* main program */
6400 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6401 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6402 		err = -EINVAL;
6403 		goto err_close;
6404 	}
6405 	if (prog->subprogs)
6406 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6407 
6408 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6409 	for (i = 0; i < max_entries; i++) {
6410 		/*
6411 		 * The offset should be made to be relative to the beginning of
6412 		 * the main function, not the subfunction.
6413 		 */
6414 		insn_off = jt[i]/sizeof(struct bpf_insn);
6415 		if (subprog_idx >= 0) {
6416 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6417 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6418 		} else {
6419 			insn_off -= prog->sec_insn_off;
6420 		}
6421 
6422 		/*
6423 		 * LLVM-generated jump tables contain u64 records, however
6424 		 * should contain values that fit in u32.
6425 		 */
6426 		if (insn_off > UINT32_MAX) {
6427 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6428 				(unsigned long long)jt[i], sym_off + i * jt_entry_size);
6429 			err = -EINVAL;
6430 			goto err_close;
6431 		}
6432 
6433 		val.orig_off = insn_off;
6434 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6435 		if (err)
6436 			goto err_close;
6437 	}
6438 
6439 	err = bpf_map_freeze(map_fd);
6440 	if (err)
6441 		goto err_close;
6442 
6443 	err = add_jt_map(obj, prog, sym_off, map_fd);
6444 	if (err)
6445 		goto err_close;
6446 
6447 	return map_fd;
6448 
6449 err_close:
6450 	close(map_fd);
6451 	return err;
6452 }
6453 
6454 /* Relocate data references within program code:
6455  *  - map references;
6456  *  - global variable references;
6457  *  - extern references.
6458  */
6459 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)6460 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6461 {
6462 	int i;
6463 
6464 	for (i = 0; i < prog->nr_reloc; i++) {
6465 		struct reloc_desc *relo = &prog->reloc_desc[i];
6466 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6467 		const struct bpf_map *map;
6468 		struct extern_desc *ext;
6469 
6470 		switch (relo->type) {
6471 		case RELO_LD64:
6472 			map = &obj->maps[relo->map_idx];
6473 			if (obj->gen_loader) {
6474 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6475 				insn[0].imm = relo->map_idx;
6476 			} else if (map->autocreate) {
6477 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6478 				insn[0].imm = map->fd;
6479 			} else {
6480 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6481 						   relo->map_idx, map);
6482 			}
6483 			break;
6484 		case RELO_DATA:
6485 			map = &obj->maps[relo->map_idx];
6486 			insn[1].imm = insn[0].imm + relo->sym_off;
6487 
6488 			if (relo->map_idx == obj->arena_map_idx)
6489 				insn[1].imm += obj->arena_data_off;
6490 
6491 			if (obj->gen_loader) {
6492 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6493 				insn[0].imm = relo->map_idx;
6494 			} else if (map->autocreate) {
6495 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6496 				insn[0].imm = map->fd;
6497 			} else {
6498 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6499 						   relo->map_idx, map);
6500 			}
6501 			break;
6502 		case RELO_EXTERN_LD64:
6503 			ext = &obj->externs[relo->ext_idx];
6504 			if (ext->type == EXT_KCFG) {
6505 				if (obj->gen_loader) {
6506 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6507 					insn[0].imm = obj->kconfig_map_idx;
6508 				} else {
6509 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6510 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6511 				}
6512 				insn[1].imm = ext->kcfg.data_off;
6513 			} else /* EXT_KSYM */ {
6514 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6515 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6516 					insn[0].imm = ext->ksym.kernel_btf_id;
6517 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6518 				} else { /* typeless ksyms or unresolved typed ksyms */
6519 					insn[0].imm = (__u32)ext->ksym.addr;
6520 					insn[1].imm = ext->ksym.addr >> 32;
6521 				}
6522 			}
6523 			break;
6524 		case RELO_EXTERN_CALL:
6525 			ext = &obj->externs[relo->ext_idx];
6526 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6527 			if (ext->is_set) {
6528 				insn[0].imm = ext->ksym.kernel_btf_id;
6529 				insn[0].off = ext->ksym.btf_fd_idx;
6530 			} else { /* unresolved weak kfunc call */
6531 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6532 						  relo->ext_idx, ext);
6533 			}
6534 			break;
6535 		case RELO_SUBPROG_ADDR:
6536 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6537 				pr_warn("prog '%s': relo #%d: bad insn\n",
6538 					prog->name, i);
6539 				return -EINVAL;
6540 			}
6541 			/* handled already */
6542 			break;
6543 		case RELO_CALL:
6544 			/* handled already */
6545 			break;
6546 		case RELO_CORE:
6547 			/* will be handled by bpf_program_record_relos() */
6548 			break;
6549 		case RELO_INSN_ARRAY: {
6550 			int map_fd;
6551 
6552 			map_fd = create_jt_map(obj, prog, relo);
6553 			if (map_fd < 0) {
6554 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6555 					prog->name, i, relo->sym_off);
6556 				return map_fd;
6557 			}
6558 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6559 			insn->imm = map_fd;
6560 			insn->off = 0;
6561 		}
6562 			break;
6563 		default:
6564 			pr_warn("prog '%s': relo #%d: bad relo type %u\n",
6565 				prog->name, i, relo->type);
6566 			return -EINVAL;
6567 		}
6568 	}
6569 
6570 	return 0;
6571 }
6572 
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)6573 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6574 				    const struct bpf_program *prog,
6575 				    const struct btf_ext_info *ext_info,
6576 				    void **prog_info, __u32 *prog_rec_cnt,
6577 				    __u32 *prog_rec_sz)
6578 {
6579 	void *copy_start = NULL, *copy_end = NULL;
6580 	void *rec, *rec_end, *new_prog_info;
6581 	const struct btf_ext_info_sec *sec;
6582 	size_t old_sz, new_sz;
6583 	int i, sec_num, sec_idx, off_adj;
6584 
6585 	sec_num = 0;
6586 	for_each_btf_ext_sec(ext_info, sec) {
6587 		sec_idx = ext_info->sec_idxs[sec_num];
6588 		sec_num++;
6589 		if (prog->sec_idx != sec_idx)
6590 			continue;
6591 
6592 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6593 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6594 
6595 			if (insn_off < prog->sec_insn_off)
6596 				continue;
6597 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6598 				break;
6599 
6600 			if (!copy_start)
6601 				copy_start = rec;
6602 			copy_end = rec + ext_info->rec_size;
6603 		}
6604 
6605 		if (!copy_start)
6606 			return -ENOENT;
6607 
6608 		/* append func/line info of a given (sub-)program to the main
6609 		 * program func/line info
6610 		 */
6611 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6612 		new_sz = old_sz + (copy_end - copy_start);
6613 		new_prog_info = realloc(*prog_info, new_sz);
6614 		if (!new_prog_info)
6615 			return -ENOMEM;
6616 		*prog_info = new_prog_info;
6617 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6618 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6619 
6620 		/* Kernel instruction offsets are in units of 8-byte
6621 		 * instructions, while .BTF.ext instruction offsets generated
6622 		 * by Clang are in units of bytes. So convert Clang offsets
6623 		 * into kernel offsets and adjust offset according to program
6624 		 * relocated position.
6625 		 */
6626 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6627 		rec = new_prog_info + old_sz;
6628 		rec_end = new_prog_info + new_sz;
6629 		for (; rec < rec_end; rec += ext_info->rec_size) {
6630 			__u32 *insn_off = rec;
6631 
6632 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6633 		}
6634 		*prog_rec_sz = ext_info->rec_size;
6635 		return 0;
6636 	}
6637 
6638 	return -ENOENT;
6639 }
6640 
6641 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6642 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6643 			      struct bpf_program *main_prog,
6644 			      const struct bpf_program *prog)
6645 {
6646 	int err;
6647 
6648 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6649 	 * support func/line info
6650 	 */
6651 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6652 		return 0;
6653 
6654 	/* only attempt func info relocation if main program's func_info
6655 	 * relocation was successful
6656 	 */
6657 	if (main_prog != prog && !main_prog->func_info)
6658 		goto line_info;
6659 
6660 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6661 				       &main_prog->func_info,
6662 				       &main_prog->func_info_cnt,
6663 				       &main_prog->func_info_rec_size);
6664 	if (err) {
6665 		if (err != -ENOENT) {
6666 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6667 				prog->name, errstr(err));
6668 			return err;
6669 		}
6670 		if (main_prog->func_info) {
6671 			/*
6672 			 * Some info has already been found but has problem
6673 			 * in the last btf_ext reloc. Must have to error out.
6674 			 */
6675 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6676 			return err;
6677 		}
6678 		/* Have problem loading the very first info. Ignore the rest. */
6679 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6680 			prog->name);
6681 	}
6682 
6683 line_info:
6684 	/* don't relocate line info if main program's relocation failed */
6685 	if (main_prog != prog && !main_prog->line_info)
6686 		return 0;
6687 
6688 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6689 				       &main_prog->line_info,
6690 				       &main_prog->line_info_cnt,
6691 				       &main_prog->line_info_rec_size);
6692 	if (err) {
6693 		if (err != -ENOENT) {
6694 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6695 				prog->name, errstr(err));
6696 			return err;
6697 		}
6698 		if (main_prog->line_info) {
6699 			/*
6700 			 * Some info has already been found but has problem
6701 			 * in the last btf_ext reloc. Must have to error out.
6702 			 */
6703 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6704 			return err;
6705 		}
6706 		/* Have problem loading the very first info. Ignore the rest. */
6707 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6708 			prog->name);
6709 	}
6710 	return 0;
6711 }
6712 
cmp_relo_by_insn_idx(const void * key,const void * elem)6713 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6714 {
6715 	size_t insn_idx = *(const size_t *)key;
6716 	const struct reloc_desc *relo = elem;
6717 
6718 	if (insn_idx == relo->insn_idx)
6719 		return 0;
6720 	return insn_idx < relo->insn_idx ? -1 : 1;
6721 }
6722 
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6723 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6724 {
6725 	if (!prog->nr_reloc)
6726 		return NULL;
6727 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6728 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6729 }
6730 
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6731 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6732 {
6733 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6734 	struct reloc_desc *relos;
6735 	int i;
6736 
6737 	if (main_prog == subprog)
6738 		return 0;
6739 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6740 	/* if new count is zero, reallocarray can return a valid NULL result;
6741 	 * in this case the previous pointer will be freed, so we *have to*
6742 	 * reassign old pointer to the new value (even if it's NULL)
6743 	 */
6744 	if (!relos && new_cnt)
6745 		return -ENOMEM;
6746 	if (subprog->nr_reloc)
6747 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6748 		       sizeof(*relos) * subprog->nr_reloc);
6749 
6750 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6751 		relos[i].insn_idx += subprog->sub_insn_off;
6752 	/* After insn_idx adjustment the 'relos' array is still sorted
6753 	 * by insn_idx and doesn't break bsearch.
6754 	 */
6755 	main_prog->reloc_desc = relos;
6756 	main_prog->nr_reloc = new_cnt;
6757 	return 0;
6758 }
6759 
save_subprog_offsets(struct bpf_program * main_prog,struct bpf_program * subprog)6760 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
6761 {
6762 	size_t size = sizeof(main_prog->subprogs[0]);
6763 	int cnt = main_prog->subprog_cnt;
6764 	void *tmp;
6765 
6766 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
6767 	if (!tmp)
6768 		return -ENOMEM;
6769 
6770 	main_prog->subprogs = tmp;
6771 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
6772 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
6773 	main_prog->subprog_cnt++;
6774 
6775 	return 0;
6776 }
6777 
6778 static int
bpf_object__append_subprog_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * subprog)6779 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6780 				struct bpf_program *subprog)
6781 {
6782 	struct bpf_insn *insns;
6783 	size_t new_cnt;
6784 	int err;
6785 
6786 	subprog->sub_insn_off = main_prog->insns_cnt;
6787 
6788 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6789 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6790 	if (!insns) {
6791 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6792 		return -ENOMEM;
6793 	}
6794 	main_prog->insns = insns;
6795 	main_prog->insns_cnt = new_cnt;
6796 
6797 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6798 	       subprog->insns_cnt * sizeof(*insns));
6799 
6800 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6801 		 main_prog->name, subprog->insns_cnt, subprog->name);
6802 
6803 	/* The subprog insns are now appended. Append its relos too. */
6804 	err = append_subprog_relos(main_prog, subprog);
6805 	if (err)
6806 		return err;
6807 
6808 	err = save_subprog_offsets(main_prog, subprog);
6809 	if (err) {
6810 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
6811 			main_prog->name, errstr(err));
6812 		return err;
6813 	}
6814 
6815 	return 0;
6816 }
6817 
6818 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6819 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6820 		       struct bpf_program *prog)
6821 {
6822 	size_t sub_insn_idx, insn_idx;
6823 	struct bpf_program *subprog;
6824 	struct reloc_desc *relo;
6825 	struct bpf_insn *insn;
6826 	int err;
6827 
6828 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6829 	if (err)
6830 		return err;
6831 
6832 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6833 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6834 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6835 			continue;
6836 
6837 		relo = find_prog_insn_relo(prog, insn_idx);
6838 		if (relo && relo->type == RELO_EXTERN_CALL)
6839 			/* kfunc relocations will be handled later
6840 			 * in bpf_object__relocate_data()
6841 			 */
6842 			continue;
6843 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6844 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %u\n",
6845 				prog->name, insn_idx, relo->type);
6846 			return -LIBBPF_ERRNO__RELOC;
6847 		}
6848 		if (relo) {
6849 			/* sub-program instruction index is a combination of
6850 			 * an offset of a symbol pointed to by relocation and
6851 			 * call instruction's imm field; for global functions,
6852 			 * call always has imm = -1, but for static functions
6853 			 * relocation is against STT_SECTION and insn->imm
6854 			 * points to a start of a static function
6855 			 *
6856 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6857 			 * the byte offset in the corresponding section.
6858 			 */
6859 			if (relo->type == RELO_CALL)
6860 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6861 			else
6862 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6863 		} else if (insn_is_pseudo_func(insn)) {
6864 			/*
6865 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6866 			 * functions are in the same section, so it shouldn't reach here.
6867 			 */
6868 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6869 				prog->name, insn_idx);
6870 			return -LIBBPF_ERRNO__RELOC;
6871 		} else {
6872 			/* if subprogram call is to a static function within
6873 			 * the same ELF section, there won't be any relocation
6874 			 * emitted, but it also means there is no additional
6875 			 * offset necessary, insns->imm is relative to
6876 			 * instruction's original position within the section
6877 			 */
6878 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6879 		}
6880 
6881 		/* we enforce that sub-programs should be in .text section */
6882 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6883 		if (!subprog) {
6884 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6885 				prog->name);
6886 			return -LIBBPF_ERRNO__RELOC;
6887 		}
6888 
6889 		/* if it's the first call instruction calling into this
6890 		 * subprogram (meaning this subprog hasn't been processed
6891 		 * yet) within the context of current main program:
6892 		 *   - append it at the end of main program's instructions blog;
6893 		 *   - process is recursively, while current program is put on hold;
6894 		 *   - if that subprogram calls some other not yet processes
6895 		 *   subprogram, same thing will happen recursively until
6896 		 *   there are no more unprocesses subprograms left to append
6897 		 *   and relocate.
6898 		 */
6899 		if (subprog->sub_insn_off == 0) {
6900 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6901 			if (err)
6902 				return err;
6903 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6904 			if (err)
6905 				return err;
6906 		}
6907 
6908 		/* main_prog->insns memory could have been re-allocated, so
6909 		 * calculate pointer again
6910 		 */
6911 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6912 		/* calculate correct instruction position within current main
6913 		 * prog; each main prog can have a different set of
6914 		 * subprograms appended (potentially in different order as
6915 		 * well), so position of any subprog can be different for
6916 		 * different main programs
6917 		 */
6918 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6919 
6920 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6921 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6922 	}
6923 
6924 	return 0;
6925 }
6926 
6927 /*
6928  * Relocate sub-program calls.
6929  *
6930  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6931  * main prog) is processed separately. For each subprog (non-entry functions,
6932  * that can be called from either entry progs or other subprogs) gets their
6933  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6934  * hasn't been yet appended and relocated within current main prog. Once its
6935  * relocated, sub_insn_off will point at the position within current main prog
6936  * where given subprog was appended. This will further be used to relocate all
6937  * the call instructions jumping into this subprog.
6938  *
6939  * We start with main program and process all call instructions. If the call
6940  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6941  * is zero), subprog instructions are appended at the end of main program's
6942  * instruction array. Then main program is "put on hold" while we recursively
6943  * process newly appended subprogram. If that subprogram calls into another
6944  * subprogram that hasn't been appended, new subprogram is appended again to
6945  * the *main* prog's instructions (subprog's instructions are always left
6946  * untouched, as they need to be in unmodified state for subsequent main progs
6947  * and subprog instructions are always sent only as part of a main prog) and
6948  * the process continues recursively. Once all the subprogs called from a main
6949  * prog or any of its subprogs are appended (and relocated), all their
6950  * positions within finalized instructions array are known, so it's easy to
6951  * rewrite call instructions with correct relative offsets, corresponding to
6952  * desired target subprog.
6953  *
6954  * Its important to realize that some subprogs might not be called from some
6955  * main prog and any of its called/used subprogs. Those will keep their
6956  * subprog->sub_insn_off as zero at all times and won't be appended to current
6957  * main prog and won't be relocated within the context of current main prog.
6958  * They might still be used from other main progs later.
6959  *
6960  * Visually this process can be shown as below. Suppose we have two main
6961  * programs mainA and mainB and BPF object contains three subprogs: subA,
6962  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6963  * subC both call subB:
6964  *
6965  *        +--------+ +-------+
6966  *        |        v v       |
6967  *     +--+---+ +--+-+-+ +---+--+
6968  *     | subA | | subB | | subC |
6969  *     +--+---+ +------+ +---+--+
6970  *        ^                  ^
6971  *        |                  |
6972  *    +---+-------+   +------+----+
6973  *    |   mainA   |   |   mainB   |
6974  *    +-----------+   +-----------+
6975  *
6976  * We'll start relocating mainA, will find subA, append it and start
6977  * processing sub A recursively:
6978  *
6979  *    +-----------+------+
6980  *    |   mainA   | subA |
6981  *    +-----------+------+
6982  *
6983  * At this point we notice that subB is used from subA, so we append it and
6984  * relocate (there are no further subcalls from subB):
6985  *
6986  *    +-----------+------+------+
6987  *    |   mainA   | subA | subB |
6988  *    +-----------+------+------+
6989  *
6990  * At this point, we relocate subA calls, then go one level up and finish with
6991  * relocation mainA calls. mainA is done.
6992  *
6993  * For mainB process is similar but results in different order. We start with
6994  * mainB and skip subA and subB, as mainB never calls them (at least
6995  * directly), but we see subC is needed, so we append and start processing it:
6996  *
6997  *    +-----------+------+
6998  *    |   mainB   | subC |
6999  *    +-----------+------+
7000  * Now we see subC needs subB, so we go back to it, append and relocate it:
7001  *
7002  *    +-----------+------+------+
7003  *    |   mainB   | subC | subB |
7004  *    +-----------+------+------+
7005  *
7006  * At this point we unwind recursion, relocate calls in subC, then in mainB.
7007  */
7008 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)7009 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
7010 {
7011 	struct bpf_program *subprog;
7012 	int i, err;
7013 
7014 	/* mark all subprogs as not relocated (yet) within the context of
7015 	 * current main program
7016 	 */
7017 	for (i = 0; i < obj->nr_programs; i++) {
7018 		subprog = &obj->programs[i];
7019 		if (!prog_is_subprog(obj, subprog))
7020 			continue;
7021 
7022 		subprog->sub_insn_off = 0;
7023 	}
7024 
7025 	err = bpf_object__reloc_code(obj, prog, prog);
7026 	if (err)
7027 		return err;
7028 
7029 	return 0;
7030 }
7031 
7032 static void
bpf_object__free_relocs(struct bpf_object * obj)7033 bpf_object__free_relocs(struct bpf_object *obj)
7034 {
7035 	struct bpf_program *prog;
7036 	int i;
7037 
7038 	/* free up relocation descriptors */
7039 	for (i = 0; i < obj->nr_programs; i++) {
7040 		prog = &obj->programs[i];
7041 		zfree(&prog->reloc_desc);
7042 		prog->nr_reloc = 0;
7043 	}
7044 }
7045 
cmp_relocs(const void * _a,const void * _b)7046 static int cmp_relocs(const void *_a, const void *_b)
7047 {
7048 	const struct reloc_desc *a = _a;
7049 	const struct reloc_desc *b = _b;
7050 
7051 	if (a->insn_idx != b->insn_idx)
7052 		return a->insn_idx < b->insn_idx ? -1 : 1;
7053 
7054 	/* no two relocations should have the same insn_idx, but ... */
7055 	if (a->type != b->type)
7056 		return a->type < b->type ? -1 : 1;
7057 
7058 	return 0;
7059 }
7060 
bpf_object__sort_relos(struct bpf_object * obj)7061 static void bpf_object__sort_relos(struct bpf_object *obj)
7062 {
7063 	int i;
7064 
7065 	for (i = 0; i < obj->nr_programs; i++) {
7066 		struct bpf_program *p = &obj->programs[i];
7067 
7068 		if (!p->nr_reloc)
7069 			continue;
7070 
7071 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7072 	}
7073 }
7074 
bpf_prog_assign_exc_cb(struct bpf_object * obj,struct bpf_program * prog)7075 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7076 {
7077 	const char *str = "exception_callback:";
7078 	size_t pfx_len = strlen(str);
7079 	int i, j, n;
7080 
7081 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7082 		return 0;
7083 
7084 	n = btf__type_cnt(obj->btf);
7085 	for (i = 1; i < n; i++) {
7086 		const char *name;
7087 		struct btf_type *t;
7088 
7089 		t = btf_type_by_id(obj->btf, i);
7090 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7091 			continue;
7092 
7093 		name = btf__str_by_offset(obj->btf, t->name_off);
7094 		if (strncmp(name, str, pfx_len) != 0)
7095 			continue;
7096 
7097 		t = btf_type_by_id(obj->btf, t->type);
7098 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7099 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7100 				prog->name);
7101 			return -EINVAL;
7102 		}
7103 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7104 			continue;
7105 		/* Multiple callbacks are specified for the same prog,
7106 		 * the verifier will eventually return an error for this
7107 		 * case, hence simply skip appending a subprog.
7108 		 */
7109 		if (prog->exception_cb_idx >= 0) {
7110 			prog->exception_cb_idx = -1;
7111 			break;
7112 		}
7113 
7114 		name += pfx_len;
7115 		if (str_is_empty(name)) {
7116 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7117 				prog->name);
7118 			return -EINVAL;
7119 		}
7120 
7121 		for (j = 0; j < obj->nr_programs; j++) {
7122 			struct bpf_program *subprog = &obj->programs[j];
7123 
7124 			if (!prog_is_subprog(obj, subprog))
7125 				continue;
7126 			if (strcmp(name, subprog->name) != 0)
7127 				continue;
7128 			/* Enforce non-hidden, as from verifier point of
7129 			 * view it expects global functions, whereas the
7130 			 * mark_btf_static fixes up linkage as static.
7131 			 */
7132 			if (!subprog->sym_global || subprog->mark_btf_static) {
7133 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7134 					prog->name, subprog->name);
7135 				return -EINVAL;
7136 			}
7137 			/* Let's see if we already saw a static exception callback with the same name */
7138 			if (prog->exception_cb_idx >= 0) {
7139 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7140 					prog->name, subprog->name);
7141 				return -EINVAL;
7142 			}
7143 			prog->exception_cb_idx = j;
7144 			break;
7145 		}
7146 
7147 		if (prog->exception_cb_idx >= 0)
7148 			continue;
7149 
7150 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7151 		return -ENOENT;
7152 	}
7153 
7154 	return 0;
7155 }
7156 
7157 static struct {
7158 	enum bpf_prog_type prog_type;
7159 	const char *ctx_name;
7160 } global_ctx_map[] = {
7161 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7162 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7163 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7164 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7165 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7166 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7167 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7168 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7169 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7170 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7171 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7172 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7173 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7174 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7175 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7176 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7177 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7178 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7179 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7180 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7181 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7182 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7183 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7184 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7185 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7186 	/* all other program types don't have "named" context structs */
7187 };
7188 
7189 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7190  * for below __builtin_types_compatible_p() checks;
7191  * with this approach we don't need any extra arch-specific #ifdef guards
7192  */
7193 struct pt_regs;
7194 struct user_pt_regs;
7195 struct user_regs_struct;
7196 
need_func_arg_type_fixup(const struct btf * btf,const struct bpf_program * prog,const char * subprog_name,int arg_idx,int arg_type_id,const char * ctx_name)7197 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7198 				     const char *subprog_name, int arg_idx,
7199 				     int arg_type_id, const char *ctx_name)
7200 {
7201 	const struct btf_type *t;
7202 	const char *tname;
7203 
7204 	/* check if existing parameter already matches verifier expectations */
7205 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7206 	if (!btf_is_ptr(t))
7207 		goto out_warn;
7208 
7209 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7210 	 * and perf_event programs, so check this case early on and forget
7211 	 * about it for subsequent checks
7212 	 */
7213 	while (btf_is_mod(t))
7214 		t = btf__type_by_id(btf, t->type);
7215 	if (btf_is_typedef(t) &&
7216 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7217 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7218 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7219 			return false; /* canonical type for kprobe/perf_event */
7220 	}
7221 
7222 	/* now we can ignore typedefs moving forward */
7223 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7224 
7225 	/* if it's `void *`, definitely fix up BTF info */
7226 	if (btf_is_void(t))
7227 		return true;
7228 
7229 	/* if it's already proper canonical type, no need to fix up */
7230 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7231 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7232 		return false;
7233 
7234 	/* special cases */
7235 	switch (prog->type) {
7236 	case BPF_PROG_TYPE_KPROBE:
7237 		/* `struct pt_regs *` is expected, but we need to fix up */
7238 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7239 			return true;
7240 		break;
7241 	case BPF_PROG_TYPE_PERF_EVENT:
7242 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7243 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7244 			return true;
7245 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7246 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7247 			return true;
7248 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7249 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7250 			return true;
7251 		break;
7252 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7253 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7254 		/* allow u64* as ctx */
7255 		if (btf_is_int(t) && t->size == 8)
7256 			return true;
7257 		break;
7258 	default:
7259 		break;
7260 	}
7261 
7262 out_warn:
7263 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7264 		prog->name, subprog_name, arg_idx, ctx_name);
7265 	return false;
7266 }
7267 
clone_func_btf_info(struct btf * btf,int orig_fn_id,struct bpf_program * prog)7268 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7269 {
7270 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7271 	int i, err, arg_cnt, fn_name_off, linkage;
7272 	struct btf_type *fn_t, *fn_proto_t, *t;
7273 	struct btf_param *p;
7274 
7275 	/* caller already validated FUNC -> FUNC_PROTO validity */
7276 	fn_t = btf_type_by_id(btf, orig_fn_id);
7277 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7278 
7279 	/* Note that each btf__add_xxx() operation invalidates
7280 	 * all btf_type and string pointers, so we need to be
7281 	 * very careful when cloning BTF types. BTF type
7282 	 * pointers have to be always refetched. And to avoid
7283 	 * problems with invalidated string pointers, we
7284 	 * add empty strings initially, then just fix up
7285 	 * name_off offsets in place. Offsets are stable for
7286 	 * existing strings, so that works out.
7287 	 */
7288 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7289 	linkage = btf_func_linkage(fn_t);
7290 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7291 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7292 	arg_cnt = btf_vlen(fn_proto_t);
7293 
7294 	/* clone FUNC_PROTO and its params */
7295 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7296 	if (fn_proto_id < 0)
7297 		return -EINVAL;
7298 
7299 	for (i = 0; i < arg_cnt; i++) {
7300 		int name_off;
7301 
7302 		/* copy original parameter data */
7303 		t = btf_type_by_id(btf, orig_proto_id);
7304 		p = &btf_params(t)[i];
7305 		name_off = p->name_off;
7306 
7307 		err = btf__add_func_param(btf, "", p->type);
7308 		if (err)
7309 			return err;
7310 
7311 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7312 		p = &btf_params(fn_proto_t)[i];
7313 		p->name_off = name_off; /* use remembered str offset */
7314 	}
7315 
7316 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7317 	 * entry program's name as a placeholder, which we replace immediately
7318 	 * with original name_off
7319 	 */
7320 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7321 	if (fn_id < 0)
7322 		return -EINVAL;
7323 
7324 	fn_t = btf_type_by_id(btf, fn_id);
7325 	fn_t->name_off = fn_name_off; /* reuse original string */
7326 
7327 	return fn_id;
7328 }
7329 
7330 /* Check if main program or global subprog's function prototype has `arg:ctx`
7331  * argument tags, and, if necessary, substitute correct type to match what BPF
7332  * verifier would expect, taking into account specific program type. This
7333  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7334  * have a native support for it in the verifier, making user's life much
7335  * easier.
7336  */
bpf_program_fixup_func_info(struct bpf_object * obj,struct bpf_program * prog)7337 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7338 {
7339 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7340 	struct bpf_func_info_min *func_rec;
7341 	struct btf_type *fn_t, *fn_proto_t;
7342 	struct btf *btf = obj->btf;
7343 	const struct btf_type *t;
7344 	struct btf_param *p;
7345 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7346 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7347 	int *orig_ids;
7348 
7349 	/* no .BTF.ext, no problem */
7350 	if (!obj->btf_ext || !prog->func_info)
7351 		return 0;
7352 
7353 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7354 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7355 		return 0;
7356 
7357 	/* some BPF program types just don't have named context structs, so
7358 	 * this fallback mechanism doesn't work for them
7359 	 */
7360 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7361 		if (global_ctx_map[i].prog_type != prog->type)
7362 			continue;
7363 		ctx_name = global_ctx_map[i].ctx_name;
7364 		break;
7365 	}
7366 	if (!ctx_name)
7367 		return 0;
7368 
7369 	/* remember original func BTF IDs to detect if we already cloned them */
7370 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7371 	if (!orig_ids)
7372 		return -ENOMEM;
7373 	for (i = 0; i < prog->func_info_cnt; i++) {
7374 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7375 		orig_ids[i] = func_rec->type_id;
7376 	}
7377 
7378 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7379 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7380 	 * clone and adjust FUNC -> FUNC_PROTO combo
7381 	 */
7382 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7383 		/* only DECL_TAG with "arg:ctx" value are interesting */
7384 		t = btf__type_by_id(btf, i);
7385 		if (!btf_is_decl_tag(t))
7386 			continue;
7387 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7388 			continue;
7389 
7390 		/* only global funcs need adjustment, if at all */
7391 		orig_fn_id = t->type;
7392 		fn_t = btf_type_by_id(btf, orig_fn_id);
7393 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7394 			continue;
7395 
7396 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7397 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7398 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7399 			continue;
7400 
7401 		/* find corresponding func_info record */
7402 		func_rec = NULL;
7403 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7404 			if (orig_ids[rec_idx] == t->type) {
7405 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7406 				break;
7407 			}
7408 		}
7409 		/* current main program doesn't call into this subprog */
7410 		if (!func_rec)
7411 			continue;
7412 
7413 		/* some more sanity checking of DECL_TAG */
7414 		arg_cnt = btf_vlen(fn_proto_t);
7415 		arg_idx = btf_decl_tag(t)->component_idx;
7416 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7417 			continue;
7418 
7419 		/* check if we should fix up argument type */
7420 		p = &btf_params(fn_proto_t)[arg_idx];
7421 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7422 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7423 			continue;
7424 
7425 		/* clone fn/fn_proto, unless we already did it for another arg */
7426 		if (func_rec->type_id == orig_fn_id) {
7427 			int fn_id;
7428 
7429 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7430 			if (fn_id < 0) {
7431 				err = fn_id;
7432 				goto err_out;
7433 			}
7434 
7435 			/* point func_info record to a cloned FUNC type */
7436 			func_rec->type_id = fn_id;
7437 		}
7438 
7439 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7440 		 * we do it just once per main BPF program, as all global
7441 		 * funcs share the same program type, so need only PTR ->
7442 		 * STRUCT type chain
7443 		 */
7444 		if (ptr_id == 0) {
7445 			struct_id = btf__add_struct(btf, ctx_name, 0);
7446 			ptr_id = btf__add_ptr(btf, struct_id);
7447 			if (ptr_id < 0 || struct_id < 0) {
7448 				err = -EINVAL;
7449 				goto err_out;
7450 			}
7451 		}
7452 
7453 		/* for completeness, clone DECL_TAG and point it to cloned param */
7454 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7455 		if (tag_id < 0) {
7456 			err = -EINVAL;
7457 			goto err_out;
7458 		}
7459 
7460 		/* all the BTF manipulations invalidated pointers, refetch them */
7461 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7462 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7463 
7464 		/* fix up type ID pointed to by param */
7465 		p = &btf_params(fn_proto_t)[arg_idx];
7466 		p->type = ptr_id;
7467 	}
7468 
7469 	free(orig_ids);
7470 	return 0;
7471 err_out:
7472 	free(orig_ids);
7473 	return err;
7474 }
7475 
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)7476 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7477 {
7478 	struct bpf_program *prog;
7479 	size_t i, j;
7480 	int err;
7481 
7482 	if (obj->btf_ext) {
7483 		err = bpf_object__relocate_core(obj, targ_btf_path);
7484 		if (err) {
7485 			pr_warn("failed to perform CO-RE relocations: %s\n",
7486 				errstr(err));
7487 			return err;
7488 		}
7489 		bpf_object__sort_relos(obj);
7490 	}
7491 
7492 	/* place globals at the end of the arena (if supported) */
7493 	if (obj->arena_map_idx >= 0 && kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF)) {
7494 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7495 
7496 		obj->arena_data_off = bpf_map_mmap_sz(arena_map) -
7497 				      roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7498 	}
7499 
7500 	/* Before relocating calls pre-process relocations and mark
7501 	 * few ld_imm64 instructions that points to subprogs.
7502 	 * Otherwise bpf_object__reloc_code() later would have to consider
7503 	 * all ld_imm64 insns as relocation candidates. That would
7504 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7505 	 * would increase and most of them will fail to find a relo.
7506 	 */
7507 	for (i = 0; i < obj->nr_programs; i++) {
7508 		prog = &obj->programs[i];
7509 		for (j = 0; j < prog->nr_reloc; j++) {
7510 			struct reloc_desc *relo = &prog->reloc_desc[j];
7511 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7512 
7513 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7514 			if (relo->type == RELO_SUBPROG_ADDR)
7515 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7516 		}
7517 	}
7518 
7519 	/* relocate subprogram calls and append used subprograms to main
7520 	 * programs; each copy of subprogram code needs to be relocated
7521 	 * differently for each main program, because its code location might
7522 	 * have changed.
7523 	 * Append subprog relos to main programs to allow data relos to be
7524 	 * processed after text is completely relocated.
7525 	 */
7526 	for (i = 0; i < obj->nr_programs; i++) {
7527 		prog = &obj->programs[i];
7528 		/* sub-program's sub-calls are relocated within the context of
7529 		 * its main program only
7530 		 */
7531 		if (prog_is_subprog(obj, prog))
7532 			continue;
7533 		if (!prog->autoload)
7534 			continue;
7535 
7536 		err = bpf_object__relocate_calls(obj, prog);
7537 		if (err) {
7538 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7539 				prog->name, errstr(err));
7540 			return err;
7541 		}
7542 
7543 		err = bpf_prog_assign_exc_cb(obj, prog);
7544 		if (err)
7545 			return err;
7546 		/* Now, also append exception callback if it has not been done already. */
7547 		if (prog->exception_cb_idx >= 0) {
7548 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7549 
7550 			/* Calling exception callback directly is disallowed, which the
7551 			 * verifier will reject later. In case it was processed already,
7552 			 * we can skip this step, otherwise for all other valid cases we
7553 			 * have to append exception callback now.
7554 			 */
7555 			if (subprog->sub_insn_off == 0) {
7556 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7557 				if (err)
7558 					return err;
7559 				err = bpf_object__reloc_code(obj, prog, subprog);
7560 				if (err)
7561 					return err;
7562 			}
7563 		}
7564 	}
7565 	for (i = 0; i < obj->nr_programs; i++) {
7566 		prog = &obj->programs[i];
7567 		if (prog_is_subprog(obj, prog))
7568 			continue;
7569 		if (!prog->autoload)
7570 			continue;
7571 
7572 		/* Process data relos for main programs */
7573 		err = bpf_object__relocate_data(obj, prog);
7574 		if (err) {
7575 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7576 				prog->name, errstr(err));
7577 			return err;
7578 		}
7579 
7580 		/* Fix up .BTF.ext information, if necessary */
7581 		err = bpf_program_fixup_func_info(obj, prog);
7582 		if (err) {
7583 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7584 				prog->name, errstr(err));
7585 			return err;
7586 		}
7587 	}
7588 
7589 	return 0;
7590 }
7591 
7592 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7593 					    Elf64_Shdr *shdr, Elf_Data *data);
7594 
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)7595 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7596 					 Elf64_Shdr *shdr, Elf_Data *data)
7597 {
7598 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7599 	int i, j, nrels, new_sz;
7600 	const struct btf_var_secinfo *vi = NULL;
7601 	const struct btf_type *sec, *var, *def;
7602 	struct bpf_map *map = NULL, *targ_map = NULL;
7603 	struct bpf_program *targ_prog = NULL;
7604 	bool is_prog_array, is_map_in_map;
7605 	const struct btf_member *member;
7606 	const char *name, *mname, *type;
7607 	unsigned int moff;
7608 	Elf64_Sym *sym;
7609 	Elf64_Rel *rel;
7610 	void *tmp;
7611 
7612 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7613 		return -EINVAL;
7614 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7615 	if (!sec)
7616 		return -EINVAL;
7617 
7618 	nrels = shdr->sh_size / shdr->sh_entsize;
7619 	for (i = 0; i < nrels; i++) {
7620 		rel = elf_rel_by_idx(data, i);
7621 		if (!rel) {
7622 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7623 			return -LIBBPF_ERRNO__FORMAT;
7624 		}
7625 
7626 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7627 		if (!sym) {
7628 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7629 				i, (size_t)ELF64_R_SYM(rel->r_info));
7630 			return -LIBBPF_ERRNO__FORMAT;
7631 		}
7632 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7633 
7634 		pr_debug(".maps relo #%d: for %zd value %zu rel->r_offset %zu name %u ('%s')\n",
7635 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7636 			 (size_t)rel->r_offset, sym->st_name, name);
7637 
7638 		for (j = 0; j < obj->nr_maps; j++) {
7639 			map = &obj->maps[j];
7640 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7641 				continue;
7642 
7643 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7644 			if (vi->offset <= rel->r_offset &&
7645 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7646 				break;
7647 		}
7648 		if (j == obj->nr_maps) {
7649 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7650 				i, name, (size_t)rel->r_offset);
7651 			return -EINVAL;
7652 		}
7653 
7654 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7655 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7656 		type = is_map_in_map ? "map" : "prog";
7657 		if (is_map_in_map) {
7658 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7659 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7660 					i, name);
7661 				return -LIBBPF_ERRNO__RELOC;
7662 			}
7663 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7664 			    map->def.key_size != sizeof(int)) {
7665 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7666 					i, map->name, sizeof(int));
7667 				return -EINVAL;
7668 			}
7669 			targ_map = bpf_object__find_map_by_name(obj, name);
7670 			if (!targ_map) {
7671 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7672 					i, name);
7673 				return -ESRCH;
7674 			}
7675 		} else if (is_prog_array) {
7676 			targ_prog = bpf_object__find_program_by_name(obj, name);
7677 			if (!targ_prog) {
7678 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7679 					i, name);
7680 				return -ESRCH;
7681 			}
7682 			if (targ_prog->sec_idx != sym->st_shndx ||
7683 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7684 			    prog_is_subprog(obj, targ_prog)) {
7685 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7686 					i, name);
7687 				return -LIBBPF_ERRNO__RELOC;
7688 			}
7689 		} else {
7690 			return -EINVAL;
7691 		}
7692 
7693 		var = btf__type_by_id(obj->btf, vi->type);
7694 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7695 		if (btf_vlen(def) == 0)
7696 			return -EINVAL;
7697 		member = btf_members(def) + btf_vlen(def) - 1;
7698 		mname = btf__name_by_offset(obj->btf, member->name_off);
7699 		if (strcmp(mname, "values"))
7700 			return -EINVAL;
7701 
7702 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7703 		if (rel->r_offset - vi->offset < moff)
7704 			return -EINVAL;
7705 
7706 		moff = rel->r_offset - vi->offset - moff;
7707 		/* here we use BPF pointer size, which is always 64 bit, as we
7708 		 * are parsing ELF that was built for BPF target
7709 		 */
7710 		if (moff % bpf_ptr_sz)
7711 			return -EINVAL;
7712 		moff /= bpf_ptr_sz;
7713 		if (moff >= map->init_slots_sz) {
7714 			new_sz = moff + 1;
7715 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7716 			if (!tmp)
7717 				return -ENOMEM;
7718 			map->init_slots = tmp;
7719 			memset(map->init_slots + map->init_slots_sz, 0,
7720 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7721 			map->init_slots_sz = new_sz;
7722 		}
7723 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7724 
7725 		pr_debug(".maps relo #%d: map '%s' slot [%u] points to %s '%s'\n",
7726 			 i, map->name, moff, type, name);
7727 	}
7728 
7729 	return 0;
7730 }
7731 
bpf_object__collect_relos(struct bpf_object * obj)7732 static int bpf_object__collect_relos(struct bpf_object *obj)
7733 {
7734 	int i, err;
7735 
7736 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7737 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7738 		Elf64_Shdr *shdr;
7739 		Elf_Data *data;
7740 		int idx;
7741 
7742 		if (sec_desc->sec_type != SEC_RELO)
7743 			continue;
7744 
7745 		shdr = sec_desc->shdr;
7746 		data = sec_desc->data;
7747 		idx = shdr->sh_info;
7748 
7749 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7750 			pr_warn("internal error at %d\n", __LINE__);
7751 			return -LIBBPF_ERRNO__INTERNAL;
7752 		}
7753 
7754 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7755 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7756 		else if (idx == obj->efile.btf_maps_shndx)
7757 			err = bpf_object__collect_map_relos(obj, shdr, data);
7758 		else
7759 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7760 		if (err)
7761 			return err;
7762 	}
7763 
7764 	bpf_object__sort_relos(obj);
7765 	return 0;
7766 }
7767 
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)7768 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7769 {
7770 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7771 	    BPF_OP(insn->code) == BPF_CALL &&
7772 	    BPF_SRC(insn->code) == BPF_K &&
7773 	    insn->src_reg == 0 &&
7774 	    insn->dst_reg == 0) {
7775 		    *func_id = insn->imm;
7776 		    return true;
7777 	}
7778 	return false;
7779 }
7780 
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)7781 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7782 {
7783 	struct bpf_insn *insn = prog->insns;
7784 	enum bpf_func_id func_id;
7785 	int i;
7786 
7787 	if (obj->gen_loader)
7788 		return 0;
7789 
7790 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7791 		if (!insn_is_helper_call(insn, &func_id))
7792 			continue;
7793 
7794 		/* on kernels that don't yet support
7795 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7796 		 * to bpf_probe_read() which works well for old kernels
7797 		 */
7798 		switch (func_id) {
7799 		case BPF_FUNC_probe_read_kernel:
7800 		case BPF_FUNC_probe_read_user:
7801 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7802 				insn->imm = BPF_FUNC_probe_read;
7803 			break;
7804 		case BPF_FUNC_probe_read_kernel_str:
7805 		case BPF_FUNC_probe_read_user_str:
7806 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7807 				insn->imm = BPF_FUNC_probe_read_str;
7808 			break;
7809 		default:
7810 			break;
7811 		}
7812 	}
7813 	return 0;
7814 }
7815 
7816 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7817 				     int *btf_obj_fd, int *btf_type_id);
7818 
is_tracing_multi(enum bpf_attach_type type)7819 static inline bool is_tracing_multi(enum bpf_attach_type type)
7820 {
7821 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
7822 	       type == BPF_TRACE_FSESSION_MULTI;
7823 }
7824 
find_attach_module(struct bpf_object * obj,const char * attach)7825 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
7826 {
7827 	const char *sep, *mod_name = NULL;
7828 	int i, mod_len, err;
7829 
7830 	/*
7831 	 * We expect attach string in the form of either
7832 	 * - function_pattern or
7833 	 * - <module>:function_pattern
7834 	 */
7835 	sep = strchr(attach, ':');
7836 	if (sep) {
7837 		mod_name = attach;
7838 		mod_len = sep - mod_name;
7839 	}
7840 	if (!mod_name)
7841 		return NULL;
7842 
7843 	err = load_module_btfs(obj);
7844 	if (err)
7845 		return NULL;
7846 
7847 	for (i = 0; i < obj->btf_module_cnt; i++) {
7848 		const struct module_btf *mod = &obj->btf_modules[i];
7849 
7850 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
7851 			return mod;
7852 	}
7853 	return NULL;
7854 }
7855 
tracing_multi_mod_fd(struct bpf_program * prog,int * btf_obj_fd)7856 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
7857 {
7858 	const char *attach_name, *sep;
7859 	const struct module_btf *mod;
7860 
7861 	*btf_obj_fd = 0;
7862 	attach_name = strchr(prog->sec_name, '/');
7863 
7864 	/* Program with no details in spec, using kernel btf. */
7865 	if (!attach_name)
7866 		return 0;
7867 
7868 	/* Program with no module section, using kernel btf. */
7869 	sep = strchr(++attach_name, ':');
7870 	if (!sep)
7871 		return 0;
7872 
7873 	/* Program with module specified, get its btf fd. */
7874 	mod = find_attach_module(prog->obj, attach_name);
7875 	if (!mod)
7876 		return -EINVAL;
7877 
7878 	*btf_obj_fd = mod->fd;
7879 	return 0;
7880 }
7881 
7882 /* 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)7883 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7884 				    struct bpf_prog_load_opts *opts, long cookie)
7885 {
7886 	enum sec_def_flags def = cookie;
7887 
7888 	/* old kernels might not support specifying expected_attach_type */
7889 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7890 		opts->expected_attach_type = 0;
7891 
7892 	if (def & SEC_SLEEPABLE)
7893 		opts->prog_flags |= BPF_F_SLEEPABLE;
7894 
7895 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7896 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7897 
7898 	/* special check for usdt to use uprobe_multi link */
7899 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7900 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7901 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7902 		 * update both.
7903 		 */
7904 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7905 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7906 	}
7907 
7908 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7909 		int btf_obj_fd = 0, btf_type_id = 0, err;
7910 		const char *attach_name;
7911 
7912 		attach_name = strchr(prog->sec_name, '/');
7913 		if (!attach_name) {
7914 			/* if BPF program is annotated with just SEC("fentry")
7915 			 * (or similar) without declaratively specifying
7916 			 * target, then it is expected that target will be
7917 			 * specified with bpf_program__set_attach_target() at
7918 			 * runtime before BPF object load step. If not, then
7919 			 * there is nothing to load into the kernel as BPF
7920 			 * verifier won't be able to validate BPF program
7921 			 * correctness anyways.
7922 			 */
7923 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7924 				prog->name);
7925 			return -EINVAL;
7926 		}
7927 		attach_name++; /* skip over / */
7928 
7929 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7930 		if (err)
7931 			return err;
7932 
7933 		/* cache resolved BTF FD and BTF type ID in the prog */
7934 		prog->attach_btf_obj_fd = btf_obj_fd;
7935 		prog->attach_btf_id = btf_type_id;
7936 
7937 		/* but by now libbpf common logic is not utilizing
7938 		 * prog->attach_btf_obj_fd/prog->attach_btf_id anymore because
7939 		 * this callback is called after opts were populated by
7940 		 * libbpf, so this callback has to update opts explicitly here
7941 		 */
7942 		opts->attach_btf_obj_fd = btf_obj_fd;
7943 		opts->attach_btf_id = btf_type_id;
7944 	}
7945 
7946 	if (is_tracing_multi(prog->expected_attach_type)) {
7947 		int err, btf_obj_fd = 0;
7948 
7949 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
7950 		if (err < 0)
7951 			return err;
7952 
7953 		prog->attach_btf_obj_fd = btf_obj_fd;
7954 		opts->attach_btf_obj_fd = btf_obj_fd;
7955 	}
7956 
7957 	return 0;
7958 }
7959 
7960 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7961 
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)7962 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7963 				struct bpf_insn *insns, int insns_cnt,
7964 				const char *license, __u32 kern_version, int *prog_fd)
7965 {
7966 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7967 	const char *prog_name = NULL;
7968 	size_t log_buf_size = 0;
7969 	char *log_buf = NULL, *tmp;
7970 	bool own_log_buf = true;
7971 	__u32 log_level = prog->log_level;
7972 	int ret, err;
7973 
7974 	/* Be more helpful by rejecting programs that can't be validated early
7975 	 * with more meaningful and actionable error message.
7976 	 */
7977 	switch (prog->type) {
7978 	case BPF_PROG_TYPE_UNSPEC:
7979 		/*
7980 		 * The program type must be set.  Most likely we couldn't find a proper
7981 		 * section definition at load time, and thus we didn't infer the type.
7982 		 */
7983 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7984 			prog->name, prog->sec_name);
7985 		return -EINVAL;
7986 	case BPF_PROG_TYPE_STRUCT_OPS:
7987 		if (prog->attach_btf_id == 0) {
7988 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7989 				prog->name);
7990 			return -EINVAL;
7991 		}
7992 		break;
7993 	default:
7994 		break;
7995 	}
7996 
7997 	if (!insns || !insns_cnt)
7998 		return -EINVAL;
7999 
8000 	if (kernel_supports(obj, FEAT_PROG_NAME))
8001 		prog_name = prog->name;
8002 	load_attr.attach_prog_fd = prog->attach_prog_fd;
8003 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
8004 	load_attr.attach_btf_id = prog->attach_btf_id;
8005 	load_attr.kern_version = kern_version;
8006 	load_attr.prog_ifindex = prog->prog_ifindex;
8007 	load_attr.expected_attach_type = prog->expected_attach_type;
8008 
8009 	/* specify func_info/line_info only if kernel supports them */
8010 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
8011 		load_attr.prog_btf_fd = btf__fd(obj->btf);
8012 		load_attr.func_info = prog->func_info;
8013 		load_attr.func_info_rec_size = prog->func_info_rec_size;
8014 		load_attr.func_info_cnt = prog->func_info_cnt;
8015 		load_attr.line_info = prog->line_info;
8016 		load_attr.line_info_rec_size = prog->line_info_rec_size;
8017 		load_attr.line_info_cnt = prog->line_info_cnt;
8018 	}
8019 	load_attr.log_level = log_level;
8020 	load_attr.prog_flags = prog->prog_flags;
8021 	load_attr.fd_array = obj->fd_array;
8022 
8023 	load_attr.token_fd = obj->token_fd;
8024 	if (obj->token_fd)
8025 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
8026 
8027 	/* adjust load_attr if sec_def provides custom preload callback */
8028 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
8029 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
8030 		if (err < 0) {
8031 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
8032 				prog->name, errstr(err));
8033 			return err;
8034 		}
8035 		insns = prog->insns;
8036 		insns_cnt = prog->insns_cnt;
8037 	}
8038 
8039 	if (obj->gen_loader) {
8040 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
8041 				   license, insns, insns_cnt, &load_attr,
8042 				   prog - obj->programs);
8043 		*prog_fd = -1;
8044 		return 0;
8045 	}
8046 
8047 retry_load:
8048 	/* if log_level is zero, we don't request logs initially even if
8049 	 * custom log_buf is specified; if the program load fails, then we'll
8050 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8051 	 * our own and retry the load to get details on what failed
8052 	 */
8053 	if (log_level) {
8054 		if (prog->log_buf) {
8055 			log_buf = prog->log_buf;
8056 			log_buf_size = prog->log_size;
8057 			own_log_buf = false;
8058 		} else if (obj->log_buf) {
8059 			log_buf = obj->log_buf;
8060 			log_buf_size = obj->log_size;
8061 			own_log_buf = false;
8062 		} else {
8063 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8064 			tmp = realloc(log_buf, log_buf_size);
8065 			if (!tmp) {
8066 				ret = -ENOMEM;
8067 				goto out;
8068 			}
8069 			log_buf = tmp;
8070 			log_buf[0] = '\0';
8071 			own_log_buf = true;
8072 		}
8073 	}
8074 
8075 	load_attr.log_buf = log_buf;
8076 	load_attr.log_size = log_buf_size;
8077 	load_attr.log_level = log_level;
8078 
8079 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8080 	if (ret >= 0) {
8081 		if (log_level && own_log_buf) {
8082 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8083 				 prog->name, log_buf);
8084 		}
8085 
8086 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8087 			struct bpf_map *map;
8088 			int i;
8089 
8090 			for (i = 0; i < obj->nr_maps; i++) {
8091 				map = &prog->obj->maps[i];
8092 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
8093 					continue;
8094 
8095 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8096 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8097 						prog->name, map->real_name, errstr(errno));
8098 					/* Don't fail hard if can't bind rodata. */
8099 				}
8100 			}
8101 		}
8102 
8103 		*prog_fd = ret;
8104 		ret = 0;
8105 		goto out;
8106 	}
8107 
8108 	if (log_level == 0) {
8109 		log_level = 1;
8110 		goto retry_load;
8111 	}
8112 	/* On ENOSPC, increase log buffer size and retry, unless custom
8113 	 * log_buf is specified.
8114 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
8115 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
8116 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
8117 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
8118 	 */
8119 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
8120 		goto retry_load;
8121 
8122 	ret = -errno;
8123 
8124 	/* post-process verifier log to improve error descriptions */
8125 	fixup_verifier_log(prog, log_buf, log_buf_size);
8126 
8127 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8128 	pr_perm_msg(ret);
8129 
8130 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8131 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8132 			prog->name, log_buf);
8133 	}
8134 
8135 out:
8136 	if (own_log_buf)
8137 		free(log_buf);
8138 	return ret;
8139 }
8140 
find_prev_line(char * buf,char * cur)8141 static char *find_prev_line(char *buf, char *cur)
8142 {
8143 	char *p;
8144 
8145 	if (cur == buf) /* end of a log buf */
8146 		return NULL;
8147 
8148 	p = cur - 1;
8149 	while (p - 1 >= buf && *(p - 1) != '\n')
8150 		p--;
8151 
8152 	return p;
8153 }
8154 
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)8155 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8156 		      char *orig, size_t orig_sz, const char *patch)
8157 {
8158 	/* size of the remaining log content to the right from the to-be-replaced part */
8159 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8160 	size_t patch_sz = strlen(patch);
8161 
8162 	if (patch_sz != orig_sz) {
8163 		/* If patch line(s) are longer than original piece of verifier log,
8164 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8165 		 * starting from after to-be-replaced part of the log.
8166 		 *
8167 		 * If patch line(s) are shorter than original piece of verifier log,
8168 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8169 		 * starting from after to-be-replaced part of the log
8170 		 *
8171 		 * We need to be careful about not overflowing available
8172 		 * buf_sz capacity. If that's the case, we'll truncate the end
8173 		 * of the original log, as necessary.
8174 		 */
8175 		if (patch_sz > orig_sz) {
8176 			if (orig + patch_sz >= buf + buf_sz) {
8177 				/* patch is big enough to cover remaining space completely */
8178 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8179 				rem_sz = 0;
8180 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8181 				/* patch causes part of remaining log to be truncated */
8182 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8183 			}
8184 		}
8185 		/* shift remaining log to the right by calculated amount */
8186 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8187 	}
8188 
8189 	memcpy(orig, patch, patch_sz);
8190 }
8191 
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)8192 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8193 				       char *buf, size_t buf_sz, size_t log_sz,
8194 				       char *line1, char *line2, char *line3)
8195 {
8196 	/* Expected log for failed and not properly guarded CO-RE relocation:
8197 	 * line1 -> 123: (85) call unknown#195896080
8198 	 * line2 -> invalid func unknown#195896080
8199 	 * line3 -> <anything else or end of buffer>
8200 	 *
8201 	 * "123" is the index of the instruction that was poisoned. We extract
8202 	 * instruction index to find corresponding CO-RE relocation and
8203 	 * replace this part of the log with more relevant information about
8204 	 * failed CO-RE relocation.
8205 	 */
8206 	const struct bpf_core_relo *relo;
8207 	struct bpf_core_spec spec;
8208 	char patch[512], spec_buf[256];
8209 	int insn_idx, err, spec_len;
8210 
8211 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8212 		return;
8213 
8214 	relo = find_relo_core(prog, insn_idx);
8215 	if (!relo)
8216 		return;
8217 
8218 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8219 	if (err)
8220 		return;
8221 
8222 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8223 	snprintf(patch, sizeof(patch),
8224 		 "%d: <invalid CO-RE relocation>\n"
8225 		 "failed to resolve CO-RE relocation %s%s\n",
8226 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8227 
8228 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8229 }
8230 
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)8231 static void fixup_log_missing_map_load(struct bpf_program *prog,
8232 				       char *buf, size_t buf_sz, size_t log_sz,
8233 				       char *line1, char *line2, char *line3)
8234 {
8235 	/* Expected log for failed and not properly guarded map reference:
8236 	 * line1 -> 123: (85) call unknown#2001000345
8237 	 * line2 -> invalid func unknown#2001000345
8238 	 * line3 -> <anything else or end of buffer>
8239 	 *
8240 	 * "123" is the index of the instruction that was poisoned.
8241 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8242 	 */
8243 	struct bpf_object *obj = prog->obj;
8244 	const struct bpf_map *map;
8245 	int insn_idx, map_idx;
8246 	char patch[128];
8247 
8248 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8249 		return;
8250 
8251 	map_idx -= POISON_LDIMM64_MAP_BASE;
8252 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8253 		return;
8254 	map = &obj->maps[map_idx];
8255 
8256 	snprintf(patch, sizeof(patch),
8257 		 "%d: <invalid BPF map reference>\n"
8258 		 "BPF map '%s' is referenced but wasn't created\n",
8259 		 insn_idx, map->name);
8260 
8261 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8262 }
8263 
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)8264 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8265 					 char *buf, size_t buf_sz, size_t log_sz,
8266 					 char *line1, char *line2, char *line3)
8267 {
8268 	/* Expected log for failed and not properly guarded kfunc call:
8269 	 * line1 -> 123: (85) call unknown#2002000345
8270 	 * line2 -> invalid func unknown#2002000345
8271 	 * line3 -> <anything else or end of buffer>
8272 	 *
8273 	 * "123" is the index of the instruction that was poisoned.
8274 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8275 	 */
8276 	struct bpf_object *obj = prog->obj;
8277 	const struct extern_desc *ext;
8278 	int insn_idx, ext_idx;
8279 	char patch[128];
8280 
8281 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8282 		return;
8283 
8284 	ext_idx -= POISON_CALL_KFUNC_BASE;
8285 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8286 		return;
8287 	ext = &obj->externs[ext_idx];
8288 
8289 	snprintf(patch, sizeof(patch),
8290 		 "%d: <invalid kfunc call>\n"
8291 		 "kfunc '%s' is referenced but wasn't resolved\n",
8292 		 insn_idx, ext->name);
8293 
8294 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8295 }
8296 
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)8297 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8298 {
8299 	/* look for familiar error patterns in last N lines of the log */
8300 	const size_t max_last_line_cnt = 10;
8301 	char *prev_line, *cur_line, *next_line;
8302 	size_t log_sz;
8303 	int i;
8304 
8305 	if (!buf)
8306 		return;
8307 
8308 	log_sz = strlen(buf) + 1;
8309 	next_line = buf + log_sz - 1;
8310 
8311 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8312 		cur_line = find_prev_line(buf, next_line);
8313 		if (!cur_line)
8314 			return;
8315 
8316 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8317 			prev_line = find_prev_line(buf, cur_line);
8318 			if (!prev_line)
8319 				continue;
8320 
8321 			/* failed CO-RE relocation case */
8322 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8323 						   prev_line, cur_line, next_line);
8324 			return;
8325 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8326 			prev_line = find_prev_line(buf, cur_line);
8327 			if (!prev_line)
8328 				continue;
8329 
8330 			/* reference to uncreated BPF map */
8331 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8332 						   prev_line, cur_line, next_line);
8333 			return;
8334 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8335 			prev_line = find_prev_line(buf, cur_line);
8336 			if (!prev_line)
8337 				continue;
8338 
8339 			/* reference to unresolved kfunc */
8340 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8341 						     prev_line, cur_line, next_line);
8342 			return;
8343 		}
8344 	}
8345 }
8346 
bpf_program_record_relos(struct bpf_program * prog)8347 static int bpf_program_record_relos(struct bpf_program *prog)
8348 {
8349 	struct bpf_object *obj = prog->obj;
8350 	int i;
8351 
8352 	for (i = 0; i < prog->nr_reloc; i++) {
8353 		struct reloc_desc *relo = &prog->reloc_desc[i];
8354 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8355 		int kind;
8356 
8357 		switch (relo->type) {
8358 		case RELO_EXTERN_LD64:
8359 			if (ext->type != EXT_KSYM)
8360 				continue;
8361 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8362 				BTF_KIND_VAR : BTF_KIND_FUNC;
8363 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8364 					       ext->is_weak, !ext->ksym.type_id,
8365 					       true, kind, relo->insn_idx);
8366 			break;
8367 		case RELO_EXTERN_CALL:
8368 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8369 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8370 					       relo->insn_idx);
8371 			break;
8372 		case RELO_CORE: {
8373 			struct bpf_core_relo cr = {
8374 				.insn_off = relo->insn_idx * 8,
8375 				.type_id = relo->core_relo->type_id,
8376 				.access_str_off = relo->core_relo->access_str_off,
8377 				.kind = relo->core_relo->kind,
8378 			};
8379 
8380 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8381 			break;
8382 		}
8383 		default:
8384 			continue;
8385 		}
8386 	}
8387 	return 0;
8388 }
8389 
8390 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)8391 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8392 {
8393 	struct bpf_program *prog;
8394 	size_t i;
8395 	int err;
8396 
8397 	for (i = 0; i < obj->nr_programs; i++) {
8398 		prog = &obj->programs[i];
8399 		if (prog_is_subprog(obj, prog))
8400 			continue;
8401 		if (!prog->autoload) {
8402 			pr_debug("prog '%s': skipped loading\n", prog->name);
8403 			continue;
8404 		}
8405 		prog->log_level |= log_level;
8406 
8407 		if (obj->gen_loader)
8408 			bpf_program_record_relos(prog);
8409 
8410 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8411 					   obj->license, obj->kern_version, &prog->fd);
8412 		if (err) {
8413 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8414 			return err;
8415 		}
8416 	}
8417 
8418 	bpf_object__free_relocs(obj);
8419 	return 0;
8420 }
8421 
bpf_object_prepare_progs(struct bpf_object * obj)8422 static int bpf_object_prepare_progs(struct bpf_object *obj)
8423 {
8424 	struct bpf_program *prog;
8425 	size_t i;
8426 	int err;
8427 
8428 	for (i = 0; i < obj->nr_programs; i++) {
8429 		prog = &obj->programs[i];
8430 		err = bpf_object__sanitize_prog(obj, prog);
8431 		if (err)
8432 			return err;
8433 	}
8434 	return 0;
8435 }
8436 
8437 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8438 
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)8439 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8440 {
8441 	struct bpf_program *prog;
8442 	int err;
8443 
8444 	bpf_object__for_each_program(prog, obj) {
8445 		prog->sec_def = find_sec_def(prog->sec_name);
8446 		if (!prog->sec_def) {
8447 			/* couldn't guess, but user might manually specify */
8448 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8449 				prog->name, prog->sec_name);
8450 			continue;
8451 		}
8452 
8453 		prog->type = prog->sec_def->prog_type;
8454 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8455 
8456 		/* sec_def can have custom callback which should be called
8457 		 * after bpf_program is initialized to adjust its properties
8458 		 */
8459 		if (prog->sec_def->prog_setup_fn) {
8460 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8461 			if (err < 0) {
8462 				pr_warn("prog '%s': failed to initialize: %s\n",
8463 					prog->name, errstr(err));
8464 				return err;
8465 			}
8466 		}
8467 	}
8468 
8469 	return 0;
8470 }
8471 
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name,const struct bpf_object_open_opts * opts)8472 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8473 					  const char *obj_name,
8474 					  const struct bpf_object_open_opts *opts)
8475 {
8476 	const char *kconfig, *btf_tmp_path, *token_path;
8477 	struct bpf_object *obj;
8478 	int err;
8479 	char *log_buf;
8480 	size_t log_size;
8481 	__u32 log_level;
8482 
8483 	if (obj_buf && !obj_name)
8484 		return ERR_PTR(-EINVAL);
8485 
8486 	if (elf_version(EV_CURRENT) == EV_NONE) {
8487 		pr_warn("failed to init libelf for %s\n",
8488 			path ? : "(mem buf)");
8489 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8490 	}
8491 
8492 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8493 		return ERR_PTR(-EINVAL);
8494 
8495 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8496 	if (obj_buf) {
8497 		path = obj_name;
8498 		pr_debug("loading object '%s' from buffer\n", obj_name);
8499 	} else {
8500 		pr_debug("loading object from %s\n", path);
8501 	}
8502 
8503 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8504 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8505 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8506 	if (log_size > UINT_MAX)
8507 		return ERR_PTR(-EINVAL);
8508 	if (log_size && !log_buf)
8509 		return ERR_PTR(-EINVAL);
8510 
8511 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8512 	/* if user didn't specify bpf_token_path explicitly, check if
8513 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8514 	 * option
8515 	 */
8516 	if (!token_path)
8517 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8518 	if (token_path && strlen(token_path) >= PATH_MAX)
8519 		return ERR_PTR(-ENAMETOOLONG);
8520 
8521 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8522 	if (IS_ERR(obj))
8523 		return obj;
8524 
8525 	obj->log_buf = log_buf;
8526 	obj->log_size = log_size;
8527 	obj->log_level = log_level;
8528 
8529 	if (token_path) {
8530 		obj->token_path = strdup(token_path);
8531 		if (!obj->token_path) {
8532 			err = -ENOMEM;
8533 			goto out;
8534 		}
8535 	}
8536 
8537 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8538 	if (btf_tmp_path) {
8539 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8540 			err = -ENAMETOOLONG;
8541 			goto out;
8542 		}
8543 		obj->btf_custom_path = strdup(btf_tmp_path);
8544 		if (!obj->btf_custom_path) {
8545 			err = -ENOMEM;
8546 			goto out;
8547 		}
8548 	}
8549 
8550 	kconfig = OPTS_GET(opts, kconfig, NULL);
8551 	if (kconfig) {
8552 		obj->kconfig = strdup(kconfig);
8553 		if (!obj->kconfig) {
8554 			err = -ENOMEM;
8555 			goto out;
8556 		}
8557 	}
8558 
8559 	err = bpf_object__elf_init(obj);
8560 	err = err ? : bpf_object__elf_collect(obj);
8561 	err = err ? : bpf_object__collect_externs(obj);
8562 	err = err ? : bpf_object_fixup_btf(obj);
8563 	err = err ? : bpf_object__init_maps(obj, opts);
8564 	err = err ? : bpf_object_init_progs(obj, opts);
8565 	err = err ? : bpf_object__collect_relos(obj);
8566 	if (err)
8567 		goto out;
8568 
8569 	bpf_object__elf_finish(obj);
8570 
8571 	return obj;
8572 out:
8573 	bpf_object__close(obj);
8574 	return ERR_PTR(err);
8575 }
8576 
8577 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)8578 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8579 {
8580 	if (!path)
8581 		return libbpf_err_ptr(-EINVAL);
8582 
8583 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8584 }
8585 
bpf_object__open(const char * path)8586 struct bpf_object *bpf_object__open(const char *path)
8587 {
8588 	return bpf_object__open_file(path, NULL);
8589 }
8590 
8591 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)8592 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8593 		     const struct bpf_object_open_opts *opts)
8594 {
8595 	char tmp_name[64];
8596 
8597 	if (!obj_buf || obj_buf_sz == 0)
8598 		return libbpf_err_ptr(-EINVAL);
8599 
8600 	/* create a (quite useless) default "name" for this memory buffer object */
8601 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8602 
8603 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8604 }
8605 
bpf_object_unload(struct bpf_object * obj)8606 static int bpf_object_unload(struct bpf_object *obj)
8607 {
8608 	size_t i;
8609 
8610 	if (!obj)
8611 		return libbpf_err(-EINVAL);
8612 
8613 	for (i = 0; i < obj->nr_maps; i++) {
8614 		zclose(obj->maps[i].fd);
8615 		if (obj->maps[i].st_ops)
8616 			zfree(&obj->maps[i].st_ops->kern_vdata);
8617 	}
8618 
8619 	for (i = 0; i < obj->nr_programs; i++)
8620 		bpf_program__unload(&obj->programs[i]);
8621 
8622 	return 0;
8623 }
8624 
bpf_object__sanitize_maps(struct bpf_object * obj)8625 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8626 {
8627 	struct bpf_map *m;
8628 
8629 	bpf_object__for_each_map(m, obj) {
8630 		if (!bpf_map__is_internal(m))
8631 			continue;
8632 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8633 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8634 	}
8635 
8636 	return 0;
8637 }
8638 
8639 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8640 			     const char *sym_name, void *ctx);
8641 
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)8642 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8643 {
8644 	char sym_type, sym_name[500];
8645 	unsigned long long sym_addr;
8646 	int ret, err = 0;
8647 	FILE *f;
8648 
8649 	f = fopen("/proc/kallsyms", "re");
8650 	if (!f) {
8651 		err = -errno;
8652 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8653 		return err;
8654 	}
8655 
8656 	while (true) {
8657 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8658 			     &sym_addr, &sym_type, sym_name);
8659 		if (ret == EOF && feof(f))
8660 			break;
8661 		if (ret != 3) {
8662 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8663 			err = -EINVAL;
8664 			break;
8665 		}
8666 
8667 		err = cb(sym_addr, sym_type, sym_name, ctx);
8668 		if (err)
8669 			break;
8670 	}
8671 
8672 	fclose(f);
8673 	return err;
8674 }
8675 
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)8676 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8677 		       const char *sym_name, void *ctx)
8678 {
8679 	struct bpf_object *obj = ctx;
8680 	const struct btf_type *t;
8681 	struct extern_desc *ext;
8682 	const char *res;
8683 
8684 	res = strstr(sym_name, ".llvm.");
8685 	if (sym_type == 'd' && res)
8686 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8687 	else
8688 		ext = find_extern_by_name(obj, sym_name);
8689 	if (!ext || ext->type != EXT_KSYM)
8690 		return 0;
8691 
8692 	t = btf__type_by_id(obj->btf, ext->btf_id);
8693 	if (!btf_is_var(t))
8694 		return 0;
8695 
8696 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8697 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8698 			sym_name, ext->ksym.addr, sym_addr);
8699 		return -EINVAL;
8700 	}
8701 	if (!ext->is_set) {
8702 		ext->is_set = true;
8703 		ext->ksym.addr = sym_addr;
8704 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8705 	}
8706 	return 0;
8707 }
8708 
bpf_object__read_kallsyms_file(struct bpf_object * obj)8709 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8710 {
8711 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8712 }
8713 
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)8714 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8715 			    __u16 kind, struct btf **res_btf,
8716 			    struct module_btf **res_mod_btf)
8717 {
8718 	struct module_btf *mod_btf;
8719 	struct btf *btf;
8720 	int i, id, err;
8721 
8722 	btf = obj->btf_vmlinux;
8723 	mod_btf = NULL;
8724 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8725 
8726 	if (id == -ENOENT) {
8727 		err = load_module_btfs(obj);
8728 		if (err)
8729 			return err;
8730 
8731 		for (i = 0; i < obj->btf_module_cnt; i++) {
8732 			/* we assume module_btf's BTF FD is always >0 */
8733 			mod_btf = &obj->btf_modules[i];
8734 			btf = mod_btf->btf;
8735 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8736 			if (id != -ENOENT)
8737 				break;
8738 		}
8739 	}
8740 	if (id <= 0)
8741 		return -ESRCH;
8742 
8743 	*res_btf = btf;
8744 	*res_mod_btf = mod_btf;
8745 	return id;
8746 }
8747 
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)8748 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8749 					       struct extern_desc *ext)
8750 {
8751 	const struct btf_type *targ_var, *targ_type;
8752 	__u32 targ_type_id, local_type_id;
8753 	struct module_btf *mod_btf = NULL;
8754 	const char *targ_var_name;
8755 	struct btf *btf = NULL;
8756 	int id, err;
8757 
8758 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8759 	if (id < 0) {
8760 		if (id == -ESRCH && ext->is_weak)
8761 			return 0;
8762 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8763 			ext->name);
8764 		return id;
8765 	}
8766 
8767 	/* find local type_id */
8768 	local_type_id = ext->ksym.type_id;
8769 
8770 	/* find target type_id */
8771 	targ_var = btf__type_by_id(btf, id);
8772 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8773 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8774 
8775 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8776 					btf, targ_type_id);
8777 	if (err <= 0) {
8778 		const struct btf_type *local_type;
8779 		const char *targ_name, *local_name;
8780 
8781 		local_type = btf__type_by_id(obj->btf, local_type_id);
8782 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8783 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8784 
8785 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%u] %s %s, but kernel has [%u] %s %s\n",
8786 			ext->name, local_type_id,
8787 			btf_kind_str(local_type), local_name, targ_type_id,
8788 			btf_kind_str(targ_type), targ_name);
8789 		return -EINVAL;
8790 	}
8791 
8792 	ext->is_set = true;
8793 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8794 	ext->ksym.kernel_btf_id = id;
8795 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8796 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8797 
8798 	return 0;
8799 }
8800 
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)8801 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8802 						struct extern_desc *ext)
8803 {
8804 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8805 	struct module_btf *mod_btf = NULL;
8806 	const struct btf_type *kern_func;
8807 	struct btf *kern_btf = NULL;
8808 	int ret;
8809 
8810 	local_func_proto_id = ext->ksym.type_id;
8811 
8812 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8813 				    &mod_btf);
8814 	if (kfunc_id < 0) {
8815 		if (kfunc_id == -ESRCH && ext->is_weak)
8816 			return 0;
8817 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8818 			ext->name);
8819 		return kfunc_id;
8820 	}
8821 
8822 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8823 	kfunc_proto_id = kern_func->type;
8824 
8825 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8826 					kern_btf, kfunc_proto_id);
8827 	if (ret <= 0) {
8828 		if (ext->is_weak)
8829 			return 0;
8830 
8831 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8832 			ext->name, local_func_proto_id,
8833 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8834 		return -EINVAL;
8835 	}
8836 
8837 	/* set index for module BTF fd in fd_array, if unset */
8838 	if (mod_btf && !mod_btf->fd_array_idx) {
8839 		/* insn->off is s16 */
8840 		if (obj->fd_array_cnt == INT16_MAX) {
8841 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8842 				ext->name, mod_btf->fd_array_idx);
8843 			return -E2BIG;
8844 		}
8845 		/* Cannot use index 0 for module BTF fd */
8846 		if (!obj->fd_array_cnt)
8847 			obj->fd_array_cnt = 1;
8848 
8849 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8850 					obj->fd_array_cnt + 1);
8851 		if (ret)
8852 			return ret;
8853 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8854 		/* we assume module BTF FD is always >0 */
8855 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8856 	}
8857 
8858 	ext->is_set = true;
8859 	ext->ksym.kernel_btf_id = kfunc_id;
8860 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8861 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8862 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8863 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8864 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8865 	 */
8866 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8867 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8868 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8869 
8870 	return 0;
8871 }
8872 
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)8873 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8874 {
8875 	const struct btf_type *t;
8876 	struct extern_desc *ext;
8877 	int i, err;
8878 
8879 	for (i = 0; i < obj->nr_extern; i++) {
8880 		ext = &obj->externs[i];
8881 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8882 			continue;
8883 
8884 		if (obj->gen_loader) {
8885 			ext->is_set = true;
8886 			ext->ksym.kernel_btf_obj_fd = 0;
8887 			ext->ksym.kernel_btf_id = 0;
8888 			continue;
8889 		}
8890 		t = btf__type_by_id(obj->btf, ext->btf_id);
8891 		if (btf_is_var(t))
8892 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8893 		else
8894 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8895 		if (err)
8896 			return err;
8897 	}
8898 	return 0;
8899 }
8900 
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)8901 static int bpf_object__resolve_externs(struct bpf_object *obj,
8902 				       const char *extra_kconfig)
8903 {
8904 	bool need_config = false, need_kallsyms = false;
8905 	bool need_vmlinux_btf = false;
8906 	struct extern_desc *ext;
8907 	void *kcfg_data = NULL;
8908 	int err, i;
8909 
8910 	if (obj->nr_extern == 0)
8911 		return 0;
8912 
8913 	if (obj->kconfig_map_idx >= 0)
8914 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8915 
8916 	for (i = 0; i < obj->nr_extern; i++) {
8917 		ext = &obj->externs[i];
8918 
8919 		if (ext->type == EXT_KSYM) {
8920 			if (ext->ksym.type_id)
8921 				need_vmlinux_btf = true;
8922 			else
8923 				need_kallsyms = true;
8924 			continue;
8925 		} else if (ext->type == EXT_KCFG) {
8926 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8927 			__u64 value = 0;
8928 
8929 			/* Kconfig externs need actual /proc/config.gz */
8930 			if (str_has_pfx(ext->name, "CONFIG_")) {
8931 				need_config = true;
8932 				continue;
8933 			}
8934 
8935 			/* Virtual kcfg externs are customly handled by libbpf */
8936 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8937 				value = get_kernel_version();
8938 				if (!value) {
8939 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8940 					return -EINVAL;
8941 				}
8942 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8943 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8944 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8945 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8946 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8947 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8948 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8949 				 * customly by libbpf (their values don't come from Kconfig).
8950 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8951 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8952 				 * externs.
8953 				 */
8954 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8955 				return -EINVAL;
8956 			}
8957 
8958 			err = set_kcfg_value_num(ext, ext_ptr, value);
8959 			if (err)
8960 				return err;
8961 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8962 				 ext->name, (unsigned long long)value);
8963 		} else {
8964 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8965 			return -EINVAL;
8966 		}
8967 	}
8968 	if (need_config && extra_kconfig) {
8969 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8970 		if (err)
8971 			return -EINVAL;
8972 		need_config = false;
8973 		for (i = 0; i < obj->nr_extern; i++) {
8974 			ext = &obj->externs[i];
8975 			if (ext->type == EXT_KCFG && !ext->is_set) {
8976 				need_config = true;
8977 				break;
8978 			}
8979 		}
8980 	}
8981 	if (need_config) {
8982 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8983 		if (err)
8984 			return -EINVAL;
8985 	}
8986 	if (need_kallsyms) {
8987 		err = bpf_object__read_kallsyms_file(obj);
8988 		if (err)
8989 			return -EINVAL;
8990 	}
8991 	if (need_vmlinux_btf) {
8992 		err = bpf_object__resolve_ksyms_btf_id(obj);
8993 		if (err)
8994 			return -EINVAL;
8995 	}
8996 	for (i = 0; i < obj->nr_extern; i++) {
8997 		ext = &obj->externs[i];
8998 
8999 		if (!ext->is_set && !ext->is_weak) {
9000 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
9001 			return -ESRCH;
9002 		} else if (!ext->is_set) {
9003 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
9004 				 ext->name);
9005 		}
9006 	}
9007 
9008 	return 0;
9009 }
9010 
bpf_map_prepare_vdata(const struct bpf_map * map)9011 static void bpf_map_prepare_vdata(const struct bpf_map *map)
9012 {
9013 	const struct btf_type *type;
9014 	struct bpf_struct_ops *st_ops;
9015 	__u32 i;
9016 
9017 	st_ops = map->st_ops;
9018 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
9019 	for (i = 0; i < btf_vlen(type); i++) {
9020 		struct bpf_program *prog = st_ops->progs[i];
9021 		void *kern_data;
9022 		int prog_fd;
9023 
9024 		if (!prog)
9025 			continue;
9026 
9027 		prog_fd = bpf_program__fd(prog);
9028 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9029 		*(unsigned long *)kern_data = prog_fd;
9030 	}
9031 }
9032 
bpf_object_prepare_struct_ops(struct bpf_object * obj)9033 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
9034 {
9035 	struct bpf_map *map;
9036 	int i;
9037 
9038 	for (i = 0; i < obj->nr_maps; i++) {
9039 		map = &obj->maps[i];
9040 
9041 		if (!bpf_map__is_struct_ops(map))
9042 			continue;
9043 
9044 		if (!map->autocreate)
9045 			continue;
9046 
9047 		bpf_map_prepare_vdata(map);
9048 	}
9049 
9050 	return 0;
9051 }
9052 
bpf_object_unpin(struct bpf_object * obj)9053 static void bpf_object_unpin(struct bpf_object *obj)
9054 {
9055 	int i;
9056 
9057 	/* unpin any maps that were auto-pinned during load */
9058 	for (i = 0; i < obj->nr_maps; i++)
9059 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9060 			bpf_map__unpin(&obj->maps[i], NULL);
9061 }
9062 
bpf_object_cleanup_btf(struct bpf_object * obj)9063 static void bpf_object_cleanup_btf(struct bpf_object *obj)
9064 {
9065 	int i;
9066 
9067 	/* clean up module BTFs */
9068 	for (i = 0; i < obj->btf_module_cnt; i++) {
9069 		close(obj->btf_modules[i].fd);
9070 		btf__free(obj->btf_modules[i].btf);
9071 		free(obj->btf_modules[i].name);
9072 	}
9073 	obj->btf_module_cnt = 0;
9074 	obj->btf_module_cap = 0;
9075 	obj->btf_modules_loaded = false;
9076 	zfree(&obj->btf_modules);
9077 
9078 	/* clean up vmlinux BTF */
9079 	btf__free(obj->btf_vmlinux);
9080 	obj->btf_vmlinux = NULL;
9081 }
9082 
bpf_object_post_load_cleanup(struct bpf_object * obj)9083 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
9084 {
9085 	/* clean up fd_array */
9086 	zfree(&obj->fd_array);
9087 
9088 	/* clean up BTF */
9089 	bpf_object_cleanup_btf(obj);
9090 }
9091 
bpf_object_prepare(struct bpf_object * obj,const char * target_btf_path)9092 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
9093 {
9094 	int err;
9095 
9096 	if (obj->state >= OBJ_PREPARED) {
9097 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
9098 		return -EINVAL;
9099 	}
9100 
9101 	err = bpf_object_prepare_token(obj);
9102 	err = err ? : bpf_object__probe_loading(obj);
9103 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
9104 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
9105 	err = err ? : bpf_object__sanitize_maps(obj);
9106 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
9107 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
9108 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
9109 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
9110 	err = err ? : bpf_object__create_maps(obj);
9111 	err = err ? : bpf_object_prepare_progs(obj);
9112 
9113 	if (err) {
9114 		bpf_object_unpin(obj);
9115 		bpf_object_unload(obj);
9116 		obj->state = OBJ_LOADED;
9117 		return err;
9118 	}
9119 
9120 	obj->state = OBJ_PREPARED;
9121 	return 0;
9122 }
9123 
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)9124 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
9125 {
9126 	int err;
9127 
9128 	if (!obj)
9129 		return libbpf_err(-EINVAL);
9130 
9131 	if (obj->state >= OBJ_LOADED) {
9132 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9133 		return libbpf_err(-EINVAL);
9134 	}
9135 
9136 	/* Disallow kernel loading programs of non-native endianness but
9137 	 * permit cross-endian creation of "light skeleton".
9138 	 */
9139 	if (obj->gen_loader) {
9140 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
9141 	} else if (!is_native_endianness(obj)) {
9142 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9143 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9144 	}
9145 
9146 	if (obj->state < OBJ_PREPARED) {
9147 		err = bpf_object_prepare(obj, target_btf_path);
9148 		if (err)
9149 			return libbpf_err(err);
9150 	}
9151 	err = bpf_object__load_progs(obj, extra_log_level);
9152 	err = err ? : bpf_object_init_prog_arrays(obj);
9153 	err = err ? : bpf_object_prepare_struct_ops(obj);
9154 
9155 	if (obj->gen_loader) {
9156 		/* reset FDs */
9157 		if (obj->btf)
9158 			btf__set_fd(obj->btf, -1);
9159 		if (!err)
9160 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9161 	}
9162 
9163 	bpf_object_post_load_cleanup(obj);
9164 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9165 
9166 	if (err) {
9167 		bpf_object_unpin(obj);
9168 		bpf_object_unload(obj);
9169 		pr_warn("failed to load object '%s'\n", obj->path);
9170 		return libbpf_err(err);
9171 	}
9172 
9173 	return 0;
9174 }
9175 
bpf_object__prepare(struct bpf_object * obj)9176 int bpf_object__prepare(struct bpf_object *obj)
9177 {
9178 	return libbpf_err(bpf_object_prepare(obj, NULL));
9179 }
9180 
bpf_object__load(struct bpf_object * obj)9181 int bpf_object__load(struct bpf_object *obj)
9182 {
9183 	return bpf_object_load(obj, 0, NULL);
9184 }
9185 
make_parent_dir(const char * path)9186 static int make_parent_dir(const char *path)
9187 {
9188 	char *dname, *dir;
9189 	int err = 0;
9190 
9191 	dname = strdup(path);
9192 	if (dname == NULL)
9193 		return -ENOMEM;
9194 
9195 	dir = dirname(dname);
9196 	if (mkdir(dir, 0700) && errno != EEXIST)
9197 		err = -errno;
9198 
9199 	free(dname);
9200 	if (err) {
9201 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9202 	}
9203 	return err;
9204 }
9205 
check_path(const char * path)9206 static int check_path(const char *path)
9207 {
9208 	struct statfs st_fs;
9209 	char *dname, *dir;
9210 	int err = 0;
9211 
9212 	if (path == NULL)
9213 		return -EINVAL;
9214 
9215 	dname = strdup(path);
9216 	if (dname == NULL)
9217 		return -ENOMEM;
9218 
9219 	dir = dirname(dname);
9220 	if (statfs(dir, &st_fs)) {
9221 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9222 		err = -errno;
9223 	}
9224 	free(dname);
9225 
9226 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9227 		pr_warn("specified path %s is not on BPF FS\n", path);
9228 		err = -EINVAL;
9229 	}
9230 
9231 	return err;
9232 }
9233 
bpf_program__pin(struct bpf_program * prog,const char * path)9234 int bpf_program__pin(struct bpf_program *prog, const char *path)
9235 {
9236 	int err;
9237 
9238 	if (prog->fd < 0) {
9239 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9240 		return libbpf_err(-EINVAL);
9241 	}
9242 
9243 	err = make_parent_dir(path);
9244 	if (err)
9245 		return libbpf_err(err);
9246 
9247 	err = check_path(path);
9248 	if (err)
9249 		return libbpf_err(err);
9250 
9251 	if (bpf_obj_pin(prog->fd, path)) {
9252 		err = -errno;
9253 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9254 		return libbpf_err(err);
9255 	}
9256 
9257 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9258 	return 0;
9259 }
9260 
bpf_program__unpin(struct bpf_program * prog,const char * path)9261 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9262 {
9263 	int err;
9264 
9265 	if (prog->fd < 0) {
9266 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9267 		return libbpf_err(-EINVAL);
9268 	}
9269 
9270 	err = check_path(path);
9271 	if (err)
9272 		return libbpf_err(err);
9273 
9274 	err = unlink(path);
9275 	if (err)
9276 		return libbpf_err(-errno);
9277 
9278 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9279 	return 0;
9280 }
9281 
bpf_map__pin(struct bpf_map * map,const char * path)9282 int bpf_map__pin(struct bpf_map *map, const char *path)
9283 {
9284 	int err;
9285 
9286 	if (map == NULL) {
9287 		pr_warn("invalid map pointer\n");
9288 		return libbpf_err(-EINVAL);
9289 	}
9290 
9291 	if (map->fd < 0) {
9292 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9293 		return libbpf_err(-EINVAL);
9294 	}
9295 
9296 	if (map->pin_path) {
9297 		if (path && strcmp(path, map->pin_path)) {
9298 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9299 				bpf_map__name(map), map->pin_path, path);
9300 			return libbpf_err(-EINVAL);
9301 		} else if (map->pinned) {
9302 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9303 				 bpf_map__name(map), map->pin_path);
9304 			return 0;
9305 		}
9306 	} else {
9307 		if (!path) {
9308 			pr_warn("missing a path to pin map '%s' at\n",
9309 				bpf_map__name(map));
9310 			return libbpf_err(-EINVAL);
9311 		} else if (map->pinned) {
9312 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9313 			return libbpf_err(-EEXIST);
9314 		}
9315 
9316 		map->pin_path = strdup(path);
9317 		if (!map->pin_path) {
9318 			err = -errno;
9319 			goto out_err;
9320 		}
9321 	}
9322 
9323 	err = make_parent_dir(map->pin_path);
9324 	if (err)
9325 		return libbpf_err(err);
9326 
9327 	err = check_path(map->pin_path);
9328 	if (err)
9329 		return libbpf_err(err);
9330 
9331 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9332 		err = -errno;
9333 		goto out_err;
9334 	}
9335 
9336 	map->pinned = true;
9337 	pr_debug("pinned map '%s'\n", map->pin_path);
9338 
9339 	return 0;
9340 
9341 out_err:
9342 	pr_warn("failed to pin map: %s\n", errstr(err));
9343 	return libbpf_err(err);
9344 }
9345 
bpf_map__unpin(struct bpf_map * map,const char * path)9346 int bpf_map__unpin(struct bpf_map *map, const char *path)
9347 {
9348 	int err;
9349 
9350 	if (map == NULL) {
9351 		pr_warn("invalid map pointer\n");
9352 		return libbpf_err(-EINVAL);
9353 	}
9354 
9355 	if (map->pin_path) {
9356 		if (path && strcmp(path, map->pin_path)) {
9357 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9358 				bpf_map__name(map), map->pin_path, path);
9359 			return libbpf_err(-EINVAL);
9360 		}
9361 		path = map->pin_path;
9362 	} else if (!path) {
9363 		pr_warn("no path to unpin map '%s' from\n",
9364 			bpf_map__name(map));
9365 		return libbpf_err(-EINVAL);
9366 	}
9367 
9368 	err = check_path(path);
9369 	if (err)
9370 		return libbpf_err(err);
9371 
9372 	err = unlink(path);
9373 	if (err != 0)
9374 		return libbpf_err(-errno);
9375 
9376 	map->pinned = false;
9377 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9378 
9379 	return 0;
9380 }
9381 
bpf_map__set_pin_path(struct bpf_map * map,const char * path)9382 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9383 {
9384 	char *new = NULL;
9385 
9386 	if (path) {
9387 		new = strdup(path);
9388 		if (!new)
9389 			return libbpf_err(-errno);
9390 	}
9391 
9392 	free(map->pin_path);
9393 	map->pin_path = new;
9394 	return 0;
9395 }
9396 
9397 __alias(bpf_map__pin_path)
9398 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9399 
bpf_map__pin_path(const struct bpf_map * map)9400 const char *bpf_map__pin_path(const struct bpf_map *map)
9401 {
9402 	return map->pin_path;
9403 }
9404 
bpf_map__is_pinned(const struct bpf_map * map)9405 bool bpf_map__is_pinned(const struct bpf_map *map)
9406 {
9407 	return map->pinned;
9408 }
9409 
sanitize_pin_path(char * s)9410 static void sanitize_pin_path(char *s)
9411 {
9412 	/* bpffs disallows periods in path names */
9413 	while (*s) {
9414 		if (*s == '.')
9415 			*s = '_';
9416 		s++;
9417 	}
9418 }
9419 
bpf_object__pin_maps(struct bpf_object * obj,const char * path)9420 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9421 {
9422 	struct bpf_map *map;
9423 	int err;
9424 
9425 	if (!obj)
9426 		return libbpf_err(-ENOENT);
9427 
9428 	if (obj->state < OBJ_PREPARED) {
9429 		pr_warn("object not yet loaded; load it first\n");
9430 		return libbpf_err(-ENOENT);
9431 	}
9432 
9433 	bpf_object__for_each_map(map, obj) {
9434 		char *pin_path = NULL;
9435 		char buf[PATH_MAX];
9436 
9437 		if (!map->autocreate)
9438 			continue;
9439 
9440 		if (path) {
9441 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9442 			if (err)
9443 				goto err_unpin_maps;
9444 			sanitize_pin_path(buf);
9445 			pin_path = buf;
9446 		} else if (!map->pin_path) {
9447 			continue;
9448 		}
9449 
9450 		err = bpf_map__pin(map, pin_path);
9451 		if (err)
9452 			goto err_unpin_maps;
9453 	}
9454 
9455 	return 0;
9456 
9457 err_unpin_maps:
9458 	while ((map = bpf_object__prev_map(obj, map))) {
9459 		if (!map->pin_path)
9460 			continue;
9461 
9462 		bpf_map__unpin(map, NULL);
9463 	}
9464 
9465 	return libbpf_err(err);
9466 }
9467 
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)9468 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9469 {
9470 	struct bpf_map *map;
9471 	int err;
9472 
9473 	if (!obj)
9474 		return libbpf_err(-ENOENT);
9475 
9476 	bpf_object__for_each_map(map, obj) {
9477 		char *pin_path = NULL;
9478 		char buf[PATH_MAX];
9479 
9480 		if (path) {
9481 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9482 			if (err)
9483 				return libbpf_err(err);
9484 			sanitize_pin_path(buf);
9485 			pin_path = buf;
9486 		} else if (!map->pin_path) {
9487 			continue;
9488 		}
9489 
9490 		err = bpf_map__unpin(map, pin_path);
9491 		if (err)
9492 			return libbpf_err(err);
9493 	}
9494 
9495 	return 0;
9496 }
9497 
bpf_object__pin_programs(struct bpf_object * obj,const char * path)9498 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9499 {
9500 	struct bpf_program *prog;
9501 	char buf[PATH_MAX];
9502 	int err;
9503 
9504 	if (!obj)
9505 		return libbpf_err(-ENOENT);
9506 
9507 	if (obj->state < OBJ_LOADED) {
9508 		pr_warn("object not yet loaded; load it first\n");
9509 		return libbpf_err(-ENOENT);
9510 	}
9511 
9512 	bpf_object__for_each_program(prog, obj) {
9513 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9514 		if (err)
9515 			goto err_unpin_programs;
9516 
9517 		err = bpf_program__pin(prog, buf);
9518 		if (err)
9519 			goto err_unpin_programs;
9520 	}
9521 
9522 	return 0;
9523 
9524 err_unpin_programs:
9525 	while ((prog = bpf_object__prev_program(obj, prog))) {
9526 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9527 			continue;
9528 
9529 		bpf_program__unpin(prog, buf);
9530 	}
9531 
9532 	return libbpf_err(err);
9533 }
9534 
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)9535 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9536 {
9537 	struct bpf_program *prog;
9538 	int err;
9539 
9540 	if (!obj)
9541 		return libbpf_err(-ENOENT);
9542 
9543 	bpf_object__for_each_program(prog, obj) {
9544 		char buf[PATH_MAX];
9545 
9546 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9547 		if (err)
9548 			return libbpf_err(err);
9549 
9550 		err = bpf_program__unpin(prog, buf);
9551 		if (err)
9552 			return libbpf_err(err);
9553 	}
9554 
9555 	return 0;
9556 }
9557 
bpf_object__pin(struct bpf_object * obj,const char * path)9558 int bpf_object__pin(struct bpf_object *obj, const char *path)
9559 {
9560 	int err;
9561 
9562 	err = bpf_object__pin_maps(obj, path);
9563 	if (err)
9564 		return libbpf_err(err);
9565 
9566 	err = bpf_object__pin_programs(obj, path);
9567 	if (err) {
9568 		bpf_object__unpin_maps(obj, path);
9569 		return libbpf_err(err);
9570 	}
9571 
9572 	return 0;
9573 }
9574 
bpf_object__unpin(struct bpf_object * obj,const char * path)9575 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9576 {
9577 	int err;
9578 
9579 	err = bpf_object__unpin_programs(obj, path);
9580 	if (err)
9581 		return libbpf_err(err);
9582 
9583 	err = bpf_object__unpin_maps(obj, path);
9584 	if (err)
9585 		return libbpf_err(err);
9586 
9587 	return 0;
9588 }
9589 
bpf_map__destroy(struct bpf_map * map)9590 static void bpf_map__destroy(struct bpf_map *map)
9591 {
9592 	if (map->inner_map) {
9593 		bpf_map__destroy(map->inner_map);
9594 		zfree(&map->inner_map);
9595 	}
9596 
9597 	zfree(&map->init_slots);
9598 	map->init_slots_sz = 0;
9599 
9600 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9601 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9602 	map->mmaped = NULL;
9603 
9604 	if (map->st_ops) {
9605 		zfree(&map->st_ops->data);
9606 		zfree(&map->st_ops->progs);
9607 		zfree(&map->st_ops->kern_func_off);
9608 		zfree(&map->st_ops);
9609 	}
9610 
9611 	zfree(&map->name);
9612 	zfree(&map->real_name);
9613 	zfree(&map->pin_path);
9614 
9615 	if (map->fd >= 0)
9616 		zclose(map->fd);
9617 }
9618 
bpf_object__close(struct bpf_object * obj)9619 void bpf_object__close(struct bpf_object *obj)
9620 {
9621 	size_t i;
9622 
9623 	if (IS_ERR_OR_NULL(obj))
9624 		return;
9625 
9626 	/*
9627 	 * if user called bpf_object__prepare() without ever getting to
9628 	 * bpf_object__load(), we need to clean up stuff that is normally
9629 	 * cleaned up at the end of loading step
9630 	 */
9631 	bpf_object_post_load_cleanup(obj);
9632 
9633 	usdt_manager_free(obj->usdt_man);
9634 	obj->usdt_man = NULL;
9635 
9636 	bpf_gen__free(obj->gen_loader);
9637 	bpf_object__elf_finish(obj);
9638 	bpf_object_unload(obj);
9639 	btf__free(obj->btf);
9640 	btf__free(obj->btf_vmlinux);
9641 	btf_ext__free(obj->btf_ext);
9642 
9643 	for (i = 0; i < obj->nr_maps; i++)
9644 		bpf_map__destroy(&obj->maps[i]);
9645 
9646 	zfree(&obj->btf_custom_path);
9647 	zfree(&obj->kconfig);
9648 
9649 	for (i = 0; i < obj->nr_extern; i++) {
9650 		zfree(&obj->externs[i].name);
9651 		zfree(&obj->externs[i].essent_name);
9652 	}
9653 
9654 	zfree(&obj->externs);
9655 	obj->nr_extern = 0;
9656 
9657 	zfree(&obj->maps);
9658 	obj->nr_maps = 0;
9659 
9660 	if (obj->programs && obj->nr_programs) {
9661 		for (i = 0; i < obj->nr_programs; i++)
9662 			bpf_program__exit(&obj->programs[i]);
9663 	}
9664 	zfree(&obj->programs);
9665 
9666 	zfree(&obj->feat_cache);
9667 	zfree(&obj->token_path);
9668 	if (obj->token_fd > 0)
9669 		close(obj->token_fd);
9670 
9671 	zfree(&obj->arena_data);
9672 
9673 	zfree(&obj->jumptables_data);
9674 	obj->jumptables_data_sz = 0;
9675 
9676 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9677 		close(obj->jumptable_maps[i].fd);
9678 	zfree(&obj->jumptable_maps);
9679 
9680 	free(obj);
9681 }
9682 
bpf_object__name(const struct bpf_object * obj)9683 const char *bpf_object__name(const struct bpf_object *obj)
9684 {
9685 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9686 }
9687 
bpf_object__kversion(const struct bpf_object * obj)9688 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9689 {
9690 	return obj ? obj->kern_version : 0;
9691 }
9692 
bpf_object__token_fd(const struct bpf_object * obj)9693 int bpf_object__token_fd(const struct bpf_object *obj)
9694 {
9695 	return obj->token_fd ?: -1;
9696 }
9697 
bpf_object__btf(const struct bpf_object * obj)9698 struct btf *bpf_object__btf(const struct bpf_object *obj)
9699 {
9700 	return obj ? obj->btf : NULL;
9701 }
9702 
bpf_object__btf_fd(const struct bpf_object * obj)9703 int bpf_object__btf_fd(const struct bpf_object *obj)
9704 {
9705 	return obj->btf ? btf__fd(obj->btf) : -1;
9706 }
9707 
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)9708 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9709 {
9710 	if (obj->state >= OBJ_LOADED)
9711 		return libbpf_err(-EINVAL);
9712 
9713 	obj->kern_version = kern_version;
9714 
9715 	return 0;
9716 }
9717 
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)9718 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9719 {
9720 	struct bpf_gen *gen;
9721 
9722 	if (!opts)
9723 		return libbpf_err(-EFAULT);
9724 	if (!OPTS_VALID(opts, gen_loader_opts))
9725 		return libbpf_err(-EINVAL);
9726 	gen = calloc(1, sizeof(*gen));
9727 	if (!gen)
9728 		return libbpf_err(-ENOMEM);
9729 	gen->opts = opts;
9730 	gen->swapped_endian = !is_native_endianness(obj);
9731 	obj->gen_loader = gen;
9732 	return 0;
9733 }
9734 
9735 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)9736 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9737 		    bool forward)
9738 {
9739 	size_t nr_programs = obj->nr_programs;
9740 	ssize_t idx;
9741 
9742 	if (!nr_programs)
9743 		return NULL;
9744 
9745 	if (!p)
9746 		/* Iter from the beginning */
9747 		return forward ? &obj->programs[0] :
9748 			&obj->programs[nr_programs - 1];
9749 
9750 	if (p->obj != obj) {
9751 		pr_warn("error: program handler doesn't match object\n");
9752 		return errno = EINVAL, NULL;
9753 	}
9754 
9755 	idx = (p - obj->programs) + (forward ? 1 : -1);
9756 	if (idx >= obj->nr_programs || idx < 0)
9757 		return NULL;
9758 	return &obj->programs[idx];
9759 }
9760 
9761 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)9762 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9763 {
9764 	struct bpf_program *prog = prev;
9765 
9766 	do {
9767 		prog = __bpf_program__iter(prog, obj, true);
9768 	} while (prog && prog_is_subprog(obj, prog));
9769 
9770 	return prog;
9771 }
9772 
9773 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)9774 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9775 {
9776 	struct bpf_program *prog = next;
9777 
9778 	do {
9779 		prog = __bpf_program__iter(prog, obj, false);
9780 	} while (prog && prog_is_subprog(obj, prog));
9781 
9782 	return prog;
9783 }
9784 
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)9785 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9786 {
9787 	prog->prog_ifindex = ifindex;
9788 }
9789 
bpf_program__name(const struct bpf_program * prog)9790 const char *bpf_program__name(const struct bpf_program *prog)
9791 {
9792 	return prog->name;
9793 }
9794 
bpf_program__section_name(const struct bpf_program * prog)9795 const char *bpf_program__section_name(const struct bpf_program *prog)
9796 {
9797 	return prog->sec_name;
9798 }
9799 
bpf_program__autoload(const struct bpf_program * prog)9800 bool bpf_program__autoload(const struct bpf_program *prog)
9801 {
9802 	return prog->autoload;
9803 }
9804 
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)9805 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9806 {
9807 	if (prog->obj->state >= OBJ_LOADED)
9808 		return libbpf_err(-EINVAL);
9809 
9810 	prog->autoload = autoload;
9811 	return 0;
9812 }
9813 
bpf_program__autoattach(const struct bpf_program * prog)9814 bool bpf_program__autoattach(const struct bpf_program *prog)
9815 {
9816 	return prog->autoattach;
9817 }
9818 
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)9819 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9820 {
9821 	prog->autoattach = autoattach;
9822 }
9823 
bpf_program__insns(const struct bpf_program * prog)9824 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9825 {
9826 	return prog->insns;
9827 }
9828 
bpf_program__insn_cnt(const struct bpf_program * prog)9829 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9830 {
9831 	return prog->insns_cnt;
9832 }
9833 
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)9834 int bpf_program__set_insns(struct bpf_program *prog,
9835 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9836 {
9837 	struct bpf_insn *insns;
9838 
9839 	if (prog->obj->state >= OBJ_LOADED)
9840 		return libbpf_err(-EBUSY);
9841 
9842 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9843 	/* NULL is a valid return from reallocarray if the new count is zero */
9844 	if (!insns && new_insn_cnt) {
9845 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9846 		return libbpf_err(-ENOMEM);
9847 	}
9848 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9849 
9850 	prog->insns = insns;
9851 	prog->insns_cnt = new_insn_cnt;
9852 	return 0;
9853 }
9854 
bpf_program__fd(const struct bpf_program * prog)9855 int bpf_program__fd(const struct bpf_program *prog)
9856 {
9857 	if (!prog)
9858 		return libbpf_err(-EINVAL);
9859 
9860 	if (prog->fd < 0)
9861 		return libbpf_err(-ENOENT);
9862 
9863 	return prog->fd;
9864 }
9865 
9866 __alias(bpf_program__type)
9867 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9868 
bpf_program__type(const struct bpf_program * prog)9869 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9870 {
9871 	return prog->type;
9872 }
9873 
9874 static size_t custom_sec_def_cnt;
9875 static struct bpf_sec_def *custom_sec_defs;
9876 static struct bpf_sec_def custom_fallback_def;
9877 static bool has_custom_fallback_def;
9878 static int last_custom_sec_def_handler_id;
9879 
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)9880 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9881 {
9882 	if (prog->obj->state >= OBJ_LOADED)
9883 		return libbpf_err(-EBUSY);
9884 
9885 	/* if type is not changed, do nothing */
9886 	if (prog->type == type)
9887 		return 0;
9888 
9889 	prog->type = type;
9890 
9891 	/* If a program type was changed, we need to reset associated SEC()
9892 	 * handler, as it will be invalid now. The only exception is a generic
9893 	 * fallback handler, which by definition is program type-agnostic and
9894 	 * is a catch-all custom handler, optionally set by the application,
9895 	 * so should be able to handle any type of BPF program.
9896 	 */
9897 	if (prog->sec_def != &custom_fallback_def)
9898 		prog->sec_def = NULL;
9899 	return 0;
9900 }
9901 
9902 __alias(bpf_program__expected_attach_type)
9903 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9904 
bpf_program__expected_attach_type(const struct bpf_program * prog)9905 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9906 {
9907 	return prog->expected_attach_type;
9908 }
9909 
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)9910 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9911 					   enum bpf_attach_type type)
9912 {
9913 	if (prog->obj->state >= OBJ_LOADED)
9914 		return libbpf_err(-EBUSY);
9915 
9916 	prog->expected_attach_type = type;
9917 	return 0;
9918 }
9919 
bpf_program__flags(const struct bpf_program * prog)9920 __u32 bpf_program__flags(const struct bpf_program *prog)
9921 {
9922 	return prog->prog_flags;
9923 }
9924 
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)9925 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9926 {
9927 	if (prog->obj->state >= OBJ_LOADED)
9928 		return libbpf_err(-EBUSY);
9929 
9930 	prog->prog_flags = flags;
9931 	return 0;
9932 }
9933 
bpf_program__log_level(const struct bpf_program * prog)9934 __u32 bpf_program__log_level(const struct bpf_program *prog)
9935 {
9936 	return prog->log_level;
9937 }
9938 
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)9939 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9940 {
9941 	if (prog->obj->state >= OBJ_LOADED)
9942 		return libbpf_err(-EBUSY);
9943 
9944 	prog->log_level = log_level;
9945 	return 0;
9946 }
9947 
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)9948 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9949 {
9950 	*log_size = prog->log_size;
9951 	return prog->log_buf;
9952 }
9953 
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)9954 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9955 {
9956 	if (log_size && !log_buf)
9957 		return libbpf_err(-EINVAL);
9958 	if (prog->log_size > UINT_MAX)
9959 		return libbpf_err(-EINVAL);
9960 	if (prog->obj->state >= OBJ_LOADED)
9961 		return libbpf_err(-EBUSY);
9962 
9963 	prog->log_buf = log_buf;
9964 	prog->log_size = log_size;
9965 	return 0;
9966 }
9967 
bpf_program__func_info(const struct bpf_program * prog)9968 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9969 {
9970 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9971 		return libbpf_err_ptr(-EOPNOTSUPP);
9972 	return prog->func_info;
9973 }
9974 
bpf_program__func_info_cnt(const struct bpf_program * prog)9975 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9976 {
9977 	return prog->func_info_cnt;
9978 }
9979 
bpf_program__line_info(const struct bpf_program * prog)9980 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9981 {
9982 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9983 		return libbpf_err_ptr(-EOPNOTSUPP);
9984 	return prog->line_info;
9985 }
9986 
bpf_program__line_info_cnt(const struct bpf_program * prog)9987 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9988 {
9989 	return prog->line_info_cnt;
9990 }
9991 
bpf_program__clone(struct bpf_program * prog,const struct bpf_prog_load_opts * opts)9992 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
9993 {
9994 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
9995 	struct bpf_object *obj;
9996 	const void *info;
9997 	__u32 info_cnt, info_rec_size;
9998 	int err, fd, prog_btf_fd;
9999 
10000 	if (!prog)
10001 		return libbpf_err(-EINVAL);
10002 
10003 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
10004 		return libbpf_err(-EINVAL);
10005 
10006 	obj = prog->obj;
10007 	if (obj->state < OBJ_PREPARED)
10008 		return libbpf_err(-EINVAL);
10009 
10010 	/*
10011 	 * Caller-provided opts take priority; fall back to
10012 	 * prog/object defaults when the caller leaves them zero.
10013 	 */
10014 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
10015 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
10016 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
10017 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
10018 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
10019 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
10020 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
10021 	if (attr.token_fd)
10022 		attr.prog_flags |= BPF_F_TOKEN_FD;
10023 
10024 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
10025 	if (!prog_btf_fd && obj->btf)
10026 		prog_btf_fd = btf__fd(obj->btf);
10027 
10028 	/* BTF func/line info: only pass if kernel supports it */
10029 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
10030 		attr.prog_btf_fd = prog_btf_fd;
10031 
10032 		/* func_info/line_info triples: all-or-nothing from caller */
10033 		info = OPTS_GET(opts, func_info, NULL);
10034 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
10035 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
10036 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10037 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
10038 				prog->name);
10039 			return libbpf_err(-EINVAL);
10040 		}
10041 		attr.func_info = info ?: prog->func_info;
10042 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
10043 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
10044 
10045 		info = OPTS_GET(opts, line_info, NULL);
10046 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
10047 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
10048 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10049 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
10050 				prog->name);
10051 			return libbpf_err(-EINVAL);
10052 		}
10053 		attr.line_info = info ?: prog->line_info;
10054 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
10055 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
10056 	}
10057 
10058 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
10059 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
10060 	attr.log_size = OPTS_GET(opts, log_size, 0);
10061 	attr.log_level = OPTS_GET(opts, log_level, 0);
10062 
10063 	/*
10064 	 * Fields below may be mutated by prog_prepare_load_fn:
10065 	 * Seed them from prog/obj defaults here;
10066 	 * Later override with caller-provided opts.
10067 	 */
10068 	attr.expected_attach_type = prog->expected_attach_type;
10069 	attr.attach_btf_id = prog->attach_btf_id;
10070 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
10071 
10072 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
10073 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
10074 		if (err)
10075 			return libbpf_err(err);
10076 	}
10077 
10078 	/* Re-apply caller overrides for output fields */
10079 	if (OPTS_GET(opts, expected_attach_type, 0))
10080 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
10081 	if (OPTS_GET(opts, attach_btf_id, 0))
10082 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
10083 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
10084 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
10085 
10086 	/*
10087 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
10088 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
10089 	 * required maps themselves using bpf_prog_bind_map().
10090 	 */
10091 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
10092 			   &attr);
10093 
10094 	return libbpf_err(fd);
10095 }
10096 
10097 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
10098 	.sec = (char *)sec_pfx,						    \
10099 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
10100 	.expected_attach_type = atype,					    \
10101 	.cookie = (long)(flags),					    \
10102 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
10103 	__VA_ARGS__							    \
10104 }
10105 
10106 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10107 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10108 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10109 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10110 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10111 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10112 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10113 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10114 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10115 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10116 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10117 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10118 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10119 
10120 static const struct bpf_sec_def section_defs[] = {
10121 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
10122 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
10123 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
10124 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
10125 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
10126 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
10127 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
10128 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
10129 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
10130 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10131 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10132 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10133 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10134 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10135 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10136 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10137 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10138 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10139 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10140 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10141 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10142 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10143 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10144 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10145 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10146 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10147 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10148 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10149 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10150 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10151 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10152 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10153 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10154 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10155 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10156 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10157 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10158 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10159 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10160 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10161 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10162 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10163 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10164 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10165 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10166 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10167 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10168 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10169 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10170 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10171 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10172 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
10173 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10174 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
10175 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
10176 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10177 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10178 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10179 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10180 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10181 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10182 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10183 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10184 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10185 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10186 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10187 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10188 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10189 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10190 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10191 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10192 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10193 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10194 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10195 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10196 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10197 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10198 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10199 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10200 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10201 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10202 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10203 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10204 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10205 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10206 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10207 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10208 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10209 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10210 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10211 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10212 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10213 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10214 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10215 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10216 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10217 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10218 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10219 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10220 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10221 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10222 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10223 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10224 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10225 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10226 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10227 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10228 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10229 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10230 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10231 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10232 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10233 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10234 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10235 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10236 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10237 };
10238 
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)10239 int libbpf_register_prog_handler(const char *sec,
10240 				 enum bpf_prog_type prog_type,
10241 				 enum bpf_attach_type exp_attach_type,
10242 				 const struct libbpf_prog_handler_opts *opts)
10243 {
10244 	struct bpf_sec_def *sec_def;
10245 
10246 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10247 		return libbpf_err(-EINVAL);
10248 
10249 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10250 		return libbpf_err(-E2BIG);
10251 
10252 	if (sec) {
10253 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10254 					      sizeof(*sec_def));
10255 		if (!sec_def)
10256 			return libbpf_err(-ENOMEM);
10257 
10258 		custom_sec_defs = sec_def;
10259 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10260 	} else {
10261 		if (has_custom_fallback_def)
10262 			return libbpf_err(-EBUSY);
10263 
10264 		sec_def = &custom_fallback_def;
10265 	}
10266 
10267 	sec_def->sec = sec ? strdup(sec) : NULL;
10268 	if (sec && !sec_def->sec)
10269 		return libbpf_err(-ENOMEM);
10270 
10271 	sec_def->prog_type = prog_type;
10272 	sec_def->expected_attach_type = exp_attach_type;
10273 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10274 
10275 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10276 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10277 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10278 
10279 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10280 
10281 	if (sec)
10282 		custom_sec_def_cnt++;
10283 	else
10284 		has_custom_fallback_def = true;
10285 
10286 	return sec_def->handler_id;
10287 }
10288 
libbpf_unregister_prog_handler(int handler_id)10289 int libbpf_unregister_prog_handler(int handler_id)
10290 {
10291 	struct bpf_sec_def *sec_defs;
10292 	int i;
10293 
10294 	if (handler_id <= 0)
10295 		return libbpf_err(-EINVAL);
10296 
10297 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10298 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10299 		has_custom_fallback_def = false;
10300 		return 0;
10301 	}
10302 
10303 	for (i = 0; i < custom_sec_def_cnt; i++) {
10304 		if (custom_sec_defs[i].handler_id == handler_id)
10305 			break;
10306 	}
10307 
10308 	if (i == custom_sec_def_cnt)
10309 		return libbpf_err(-ENOENT);
10310 
10311 	free(custom_sec_defs[i].sec);
10312 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10313 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10314 	custom_sec_def_cnt--;
10315 
10316 	/* try to shrink the array, but it's ok if we couldn't */
10317 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10318 	/* if new count is zero, reallocarray can return a valid NULL result;
10319 	 * in this case the previous pointer will be freed, so we *have to*
10320 	 * reassign old pointer to the new value (even if it's NULL)
10321 	 */
10322 	if (sec_defs || custom_sec_def_cnt == 0)
10323 		custom_sec_defs = sec_defs;
10324 
10325 	return 0;
10326 }
10327 
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)10328 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10329 {
10330 	size_t len = strlen(sec_def->sec);
10331 
10332 	/* "type/" always has to have proper SEC("type/extras") form */
10333 	if (sec_def->sec[len - 1] == '/') {
10334 		if (str_has_pfx(sec_name, sec_def->sec))
10335 			return true;
10336 		return false;
10337 	}
10338 
10339 	/* "type+" means it can be either exact SEC("type") or
10340 	 * well-formed SEC("type/extras") with proper '/' separator
10341 	 */
10342 	if (sec_def->sec[len - 1] == '+') {
10343 		len--;
10344 		/* not even a prefix */
10345 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10346 			return false;
10347 		/* exact match or has '/' separator */
10348 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10349 			return true;
10350 		return false;
10351 	}
10352 
10353 	return strcmp(sec_name, sec_def->sec) == 0;
10354 }
10355 
find_sec_def(const char * sec_name)10356 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10357 {
10358 	const struct bpf_sec_def *sec_def;
10359 	int i, n;
10360 
10361 	n = custom_sec_def_cnt;
10362 	for (i = 0; i < n; i++) {
10363 		sec_def = &custom_sec_defs[i];
10364 		if (sec_def_matches(sec_def, sec_name))
10365 			return sec_def;
10366 	}
10367 
10368 	n = ARRAY_SIZE(section_defs);
10369 	for (i = 0; i < n; i++) {
10370 		sec_def = &section_defs[i];
10371 		if (sec_def_matches(sec_def, sec_name))
10372 			return sec_def;
10373 	}
10374 
10375 	if (has_custom_fallback_def)
10376 		return &custom_fallback_def;
10377 
10378 	return NULL;
10379 }
10380 
10381 #define MAX_TYPE_NAME_SIZE 32
10382 
libbpf_get_type_names(bool attach_type)10383 static char *libbpf_get_type_names(bool attach_type)
10384 {
10385 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10386 	char *buf;
10387 
10388 	buf = malloc(len);
10389 	if (!buf)
10390 		return NULL;
10391 
10392 	buf[0] = '\0';
10393 	/* Forge string buf with all available names */
10394 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10395 		const struct bpf_sec_def *sec_def = &section_defs[i];
10396 
10397 		if (attach_type) {
10398 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10399 				continue;
10400 
10401 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10402 				continue;
10403 		}
10404 
10405 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10406 			free(buf);
10407 			return NULL;
10408 		}
10409 		strcat(buf, " ");
10410 		strcat(buf, section_defs[i].sec);
10411 	}
10412 
10413 	return buf;
10414 }
10415 
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)10416 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10417 			     enum bpf_attach_type *expected_attach_type)
10418 {
10419 	const struct bpf_sec_def *sec_def;
10420 	char *type_names;
10421 
10422 	if (!name)
10423 		return libbpf_err(-EINVAL);
10424 
10425 	sec_def = find_sec_def(name);
10426 	if (sec_def) {
10427 		*prog_type = sec_def->prog_type;
10428 		*expected_attach_type = sec_def->expected_attach_type;
10429 		return 0;
10430 	}
10431 
10432 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10433 	type_names = libbpf_get_type_names(false);
10434 	if (type_names != NULL) {
10435 		pr_debug("supported section(type) names are:%s\n", type_names);
10436 		free(type_names);
10437 	}
10438 
10439 	return libbpf_err(-ESRCH);
10440 }
10441 
libbpf_bpf_attach_type_str(enum bpf_attach_type t)10442 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10443 {
10444 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10445 		return NULL;
10446 
10447 	return attach_type_name[t];
10448 }
10449 
libbpf_bpf_link_type_str(enum bpf_link_type t)10450 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10451 {
10452 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10453 		return NULL;
10454 
10455 	return link_type_name[t];
10456 }
10457 
libbpf_bpf_map_type_str(enum bpf_map_type t)10458 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10459 {
10460 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10461 		return NULL;
10462 
10463 	return map_type_name[t];
10464 }
10465 
libbpf_bpf_prog_type_str(enum bpf_prog_type t)10466 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10467 {
10468 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10469 		return NULL;
10470 
10471 	return prog_type_name[t];
10472 }
10473 
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)10474 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10475 						     int sec_idx,
10476 						     size_t offset)
10477 {
10478 	struct bpf_map *map;
10479 	size_t i;
10480 
10481 	for (i = 0; i < obj->nr_maps; i++) {
10482 		map = &obj->maps[i];
10483 		if (!bpf_map__is_struct_ops(map))
10484 			continue;
10485 		if (map->sec_idx == sec_idx &&
10486 		    map->sec_offset <= offset &&
10487 		    offset - map->sec_offset < map->def.value_size)
10488 			return map;
10489 	}
10490 
10491 	return NULL;
10492 }
10493 
10494 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10495  * st_ops->data for shadow type.
10496  */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)10497 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10498 					    Elf64_Shdr *shdr, Elf_Data *data)
10499 {
10500 	const struct btf_type *type;
10501 	const struct btf_member *member;
10502 	struct bpf_struct_ops *st_ops;
10503 	struct bpf_program *prog;
10504 	unsigned int shdr_idx;
10505 	const struct btf *btf;
10506 	struct bpf_map *map;
10507 	unsigned int moff, insn_idx;
10508 	const char *name;
10509 	__u32 member_idx;
10510 	Elf64_Sym *sym;
10511 	Elf64_Rel *rel;
10512 	int i, nrels;
10513 
10514 	btf = obj->btf;
10515 	nrels = shdr->sh_size / shdr->sh_entsize;
10516 	for (i = 0; i < nrels; i++) {
10517 		rel = elf_rel_by_idx(data, i);
10518 		if (!rel) {
10519 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10520 			return -LIBBPF_ERRNO__FORMAT;
10521 		}
10522 
10523 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10524 		if (!sym) {
10525 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10526 				(size_t)ELF64_R_SYM(rel->r_info));
10527 			return -LIBBPF_ERRNO__FORMAT;
10528 		}
10529 
10530 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10531 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10532 		if (!map) {
10533 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10534 				(size_t)rel->r_offset);
10535 			return -EINVAL;
10536 		}
10537 
10538 		moff = rel->r_offset - map->sec_offset;
10539 		shdr_idx = sym->st_shndx;
10540 		st_ops = map->st_ops;
10541 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %u (\'%s\')\n",
10542 			 map->name,
10543 			 (long long)(rel->r_info >> 32),
10544 			 (long long)sym->st_value,
10545 			 shdr_idx, (size_t)rel->r_offset,
10546 			 map->sec_offset, sym->st_name, name);
10547 
10548 		if (shdr_idx >= SHN_LORESERVE) {
10549 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10550 				map->name, (size_t)rel->r_offset, shdr_idx);
10551 			return -LIBBPF_ERRNO__RELOC;
10552 		}
10553 		if (sym->st_value % BPF_INSN_SZ) {
10554 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10555 				map->name, (unsigned long long)sym->st_value);
10556 			return -LIBBPF_ERRNO__FORMAT;
10557 		}
10558 		insn_idx = sym->st_value / BPF_INSN_SZ;
10559 
10560 		type = btf__type_by_id(btf, st_ops->type_id);
10561 		member = find_member_by_offset(type, moff * 8);
10562 		if (!member) {
10563 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10564 				map->name, moff);
10565 			return -EINVAL;
10566 		}
10567 		member_idx = member - btf_members(type);
10568 		name = btf__name_by_offset(btf, member->name_off);
10569 
10570 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10571 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10572 				map->name, name);
10573 			return -EINVAL;
10574 		}
10575 
10576 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10577 		if (!prog) {
10578 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10579 				map->name, shdr_idx, name);
10580 			return -EINVAL;
10581 		}
10582 
10583 		/* prevent the use of BPF prog with invalid type */
10584 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10585 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10586 				map->name, prog->name);
10587 			return -EINVAL;
10588 		}
10589 
10590 		st_ops->progs[member_idx] = prog;
10591 
10592 		/* st_ops->data will be exposed to users, being returned by
10593 		 * bpf_map__initial_value() as a pointer to the shadow
10594 		 * type. All function pointers in the original struct type
10595 		 * should be converted to a pointer to struct bpf_program
10596 		 * in the shadow type.
10597 		 */
10598 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10599 	}
10600 
10601 	return 0;
10602 }
10603 
10604 #define BTF_TRACE_PREFIX "btf_trace_"
10605 #define BTF_LSM_PREFIX "bpf_lsm_"
10606 #define BTF_ITER_PREFIX "bpf_iter_"
10607 #define BTF_MAX_NAME_SIZE 128
10608 
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)10609 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10610 				const char **prefix, int *kind)
10611 {
10612 	switch (attach_type) {
10613 	case BPF_TRACE_RAW_TP:
10614 		*prefix = BTF_TRACE_PREFIX;
10615 		*kind = BTF_KIND_TYPEDEF;
10616 		break;
10617 	case BPF_LSM_MAC:
10618 	case BPF_LSM_CGROUP:
10619 		*prefix = BTF_LSM_PREFIX;
10620 		*kind = BTF_KIND_FUNC;
10621 		break;
10622 	case BPF_TRACE_ITER:
10623 		*prefix = BTF_ITER_PREFIX;
10624 		*kind = BTF_KIND_FUNC;
10625 		break;
10626 	default:
10627 		*prefix = "";
10628 		*kind = BTF_KIND_FUNC;
10629 	}
10630 }
10631 
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)10632 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10633 				   const char *name, __u32 kind)
10634 {
10635 	char btf_type_name[BTF_MAX_NAME_SIZE];
10636 	int ret;
10637 
10638 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10639 		       "%s%s", prefix, name);
10640 	/* snprintf returns the number of characters written excluding the
10641 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10642 	 * indicates truncation.
10643 	 */
10644 	if (ret < 0 || ret >= sizeof(btf_type_name))
10645 		return -ENAMETOOLONG;
10646 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10647 }
10648 
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)10649 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10650 				     enum bpf_attach_type attach_type)
10651 {
10652 	const char *prefix;
10653 	int kind;
10654 
10655 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10656 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10657 }
10658 
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)10659 int libbpf_find_vmlinux_btf_id(const char *name,
10660 			       enum bpf_attach_type attach_type)
10661 {
10662 	struct btf *btf;
10663 	int err;
10664 
10665 	btf = btf__load_vmlinux_btf();
10666 	err = libbpf_get_error(btf);
10667 	if (err) {
10668 		pr_warn("vmlinux BTF is not found\n");
10669 		return libbpf_err(err);
10670 	}
10671 
10672 	err = find_attach_btf_id(btf, name, attach_type);
10673 	if (err <= 0)
10674 		pr_warn("%s is not found in vmlinux BTF\n", name);
10675 
10676 	btf__free(btf);
10677 	return libbpf_err(err);
10678 }
10679 
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd,int token_fd)10680 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10681 {
10682 	struct bpf_prog_info info;
10683 	__u32 info_len = sizeof(info);
10684 	struct btf *btf;
10685 	int err;
10686 
10687 	memset(&info, 0, info_len);
10688 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10689 	if (err) {
10690 		pr_warn("failed bpf_prog_get_info_by_fd for FD %u: %s\n",
10691 			attach_prog_fd, errstr(err));
10692 		return err;
10693 	}
10694 
10695 	err = -EINVAL;
10696 	if (!info.btf_id) {
10697 		pr_warn("The target program doesn't have BTF\n");
10698 		goto out;
10699 	}
10700 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10701 	err = libbpf_get_error(btf);
10702 	if (err) {
10703 		pr_warn("Failed to get BTF %u of the program: %s\n", info.btf_id, errstr(err));
10704 		goto out;
10705 	}
10706 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10707 	btf__free(btf);
10708 	if (err <= 0) {
10709 		pr_warn("%s is not found in prog's BTF\n", name);
10710 		goto out;
10711 	}
10712 out:
10713 	return err;
10714 }
10715 
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)10716 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10717 			      enum bpf_attach_type attach_type,
10718 			      int *btf_obj_fd, int *btf_type_id)
10719 {
10720 	int ret, i, mod_len = 0;
10721 	const char *fn_name, *mod_name = NULL;
10722 
10723 	fn_name = strchr(attach_name, ':');
10724 	if (fn_name) {
10725 		mod_name = attach_name;
10726 		mod_len = fn_name - mod_name;
10727 		fn_name++;
10728 	}
10729 
10730 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10731 		ret = find_attach_btf_id(obj->btf_vmlinux,
10732 					 mod_name ? fn_name : attach_name,
10733 					 attach_type);
10734 		if (ret > 0) {
10735 			*btf_obj_fd = 0; /* vmlinux BTF */
10736 			*btf_type_id = ret;
10737 			return 0;
10738 		}
10739 		if (ret != -ENOENT)
10740 			return ret;
10741 	}
10742 
10743 	ret = load_module_btfs(obj);
10744 	if (ret)
10745 		return ret;
10746 
10747 	for (i = 0; i < obj->btf_module_cnt; i++) {
10748 		const struct module_btf *mod = &obj->btf_modules[i];
10749 
10750 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10751 			continue;
10752 
10753 		ret = find_attach_btf_id(mod->btf,
10754 					 mod_name ? fn_name : attach_name,
10755 					 attach_type);
10756 		if (ret > 0) {
10757 			*btf_obj_fd = mod->fd;
10758 			*btf_type_id = ret;
10759 			return 0;
10760 		}
10761 		if (ret == -ENOENT)
10762 			continue;
10763 
10764 		return ret;
10765 	}
10766 
10767 	return -ESRCH;
10768 }
10769 
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)10770 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10771 				     int *btf_obj_fd, int *btf_type_id)
10772 {
10773 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10774 	__u32 attach_prog_fd = prog->attach_prog_fd;
10775 	int err = 0;
10776 
10777 	/* BPF program's BTF ID */
10778 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10779 		if (!attach_prog_fd) {
10780 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10781 			return -EINVAL;
10782 		}
10783 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10784 		if (err < 0) {
10785 			pr_warn("prog '%s': failed to find BPF program (FD %u) BTF ID for '%s': %s\n",
10786 				prog->name, attach_prog_fd, attach_name, errstr(err));
10787 			return err;
10788 		}
10789 		*btf_obj_fd = 0;
10790 		*btf_type_id = err;
10791 		return 0;
10792 	}
10793 
10794 	/* kernel/module BTF ID */
10795 	if (prog->obj->gen_loader) {
10796 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10797 		*btf_obj_fd = 0;
10798 		*btf_type_id = 1;
10799 	} else {
10800 		err = find_kernel_btf_id(prog->obj, attach_name,
10801 					 attach_type, btf_obj_fd,
10802 					 btf_type_id);
10803 	}
10804 	if (err) {
10805 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10806 			prog->name, attach_name, errstr(err));
10807 		return err;
10808 	}
10809 	return 0;
10810 }
10811 
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)10812 int libbpf_attach_type_by_name(const char *name,
10813 			       enum bpf_attach_type *attach_type)
10814 {
10815 	char *type_names;
10816 	const struct bpf_sec_def *sec_def;
10817 
10818 	if (!name)
10819 		return libbpf_err(-EINVAL);
10820 
10821 	sec_def = find_sec_def(name);
10822 	if (!sec_def) {
10823 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10824 		type_names = libbpf_get_type_names(true);
10825 		if (type_names != NULL) {
10826 			pr_debug("attachable section(type) names are:%s\n", type_names);
10827 			free(type_names);
10828 		}
10829 
10830 		return libbpf_err(-EINVAL);
10831 	}
10832 
10833 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10834 		return libbpf_err(-EINVAL);
10835 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10836 		return libbpf_err(-EINVAL);
10837 
10838 	*attach_type = sec_def->expected_attach_type;
10839 	return 0;
10840 }
10841 
bpf_map__fd(const struct bpf_map * map)10842 int bpf_map__fd(const struct bpf_map *map)
10843 {
10844 	if (!map)
10845 		return libbpf_err(-EINVAL);
10846 	if (!map_is_created(map))
10847 		return -1;
10848 	return map->fd;
10849 }
10850 
map_uses_real_name(const struct bpf_map * map)10851 static bool map_uses_real_name(const struct bpf_map *map)
10852 {
10853 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10854 	 * their user-visible name differs from kernel-visible name. Users see
10855 	 * such map's corresponding ELF section name as a map name.
10856 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10857 	 * maps to know which name has to be returned to the user.
10858 	 * Map name of the custom .percpu.* maps might be truncated to
10859 	 * BPF_OBJ_NAME_LEN-1 chars in internal_map_name(). Hence, percpu data
10860 	 * maps must use real name for their user-visible name.
10861 	 */
10862 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10863 		return true;
10864 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10865 		return true;
10866 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
10867 		return true;
10868 	return false;
10869 }
10870 
bpf_map__name(const struct bpf_map * map)10871 const char *bpf_map__name(const struct bpf_map *map)
10872 {
10873 	if (!map)
10874 		return NULL;
10875 
10876 	if (map_uses_real_name(map))
10877 		return map->real_name;
10878 
10879 	return map->name;
10880 }
10881 
bpf_map__type(const struct bpf_map * map)10882 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10883 {
10884 	return map->def.type;
10885 }
10886 
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)10887 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10888 {
10889 	if (map_is_created(map))
10890 		return libbpf_err(-EBUSY);
10891 	map->def.type = type;
10892 	return 0;
10893 }
10894 
bpf_map__map_flags(const struct bpf_map * map)10895 __u32 bpf_map__map_flags(const struct bpf_map *map)
10896 {
10897 	return map->def.map_flags;
10898 }
10899 
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)10900 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10901 {
10902 	if (map_is_created(map))
10903 		return libbpf_err(-EBUSY);
10904 	map->def.map_flags = flags;
10905 	return 0;
10906 }
10907 
bpf_map__map_extra(const struct bpf_map * map)10908 __u64 bpf_map__map_extra(const struct bpf_map *map)
10909 {
10910 	return map->map_extra;
10911 }
10912 
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)10913 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10914 {
10915 	if (map_is_created(map))
10916 		return libbpf_err(-EBUSY);
10917 	map->map_extra = map_extra;
10918 	return 0;
10919 }
10920 
bpf_map__numa_node(const struct bpf_map * map)10921 __u32 bpf_map__numa_node(const struct bpf_map *map)
10922 {
10923 	return map->numa_node;
10924 }
10925 
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)10926 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10927 {
10928 	if (map_is_created(map))
10929 		return libbpf_err(-EBUSY);
10930 	map->numa_node = numa_node;
10931 	return 0;
10932 }
10933 
bpf_map__key_size(const struct bpf_map * map)10934 __u32 bpf_map__key_size(const struct bpf_map *map)
10935 {
10936 	return map->def.key_size;
10937 }
10938 
bpf_map__set_key_size(struct bpf_map * map,__u32 size)10939 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10940 {
10941 	if (map_is_created(map))
10942 		return libbpf_err(-EBUSY);
10943 	map->def.key_size = size;
10944 	return 0;
10945 }
10946 
bpf_map__value_size(const struct bpf_map * map)10947 __u32 bpf_map__value_size(const struct bpf_map *map)
10948 {
10949 	return map->def.value_size;
10950 }
10951 
map_btf_datasec_resize(struct bpf_map * map,__u32 size)10952 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10953 {
10954 	struct btf *btf;
10955 	struct btf_type *datasec_type, *var_type;
10956 	struct btf_var_secinfo *var;
10957 	const struct btf_type *array_type;
10958 	const struct btf_array *array;
10959 	int vlen, element_sz, new_array_id;
10960 	__u32 nr_elements;
10961 
10962 	/* check btf existence */
10963 	btf = bpf_object__btf(map->obj);
10964 	if (!btf)
10965 		return -ENOENT;
10966 
10967 	/* verify map is datasec */
10968 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10969 	if (!btf_is_datasec(datasec_type)) {
10970 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10971 			bpf_map__name(map));
10972 		return -EINVAL;
10973 	}
10974 
10975 	/* verify datasec has at least one var */
10976 	vlen = btf_vlen(datasec_type);
10977 	if (vlen == 0) {
10978 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10979 			bpf_map__name(map));
10980 		return -EINVAL;
10981 	}
10982 
10983 	/* verify last var in the datasec is an array */
10984 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10985 	var_type = btf_type_by_id(btf, var->type);
10986 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10987 	if (!btf_is_array(array_type)) {
10988 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10989 			bpf_map__name(map));
10990 		return -EINVAL;
10991 	}
10992 
10993 	/* verify request size aligns with array */
10994 	array = btf_array(array_type);
10995 	element_sz = btf__resolve_size(btf, array->type);
10996 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10997 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10998 			bpf_map__name(map), element_sz, size);
10999 		return -EINVAL;
11000 	}
11001 
11002 	/* create a new array based on the existing array, but with new length */
11003 	nr_elements = (size - var->offset) / element_sz;
11004 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
11005 	if (new_array_id < 0)
11006 		return new_array_id;
11007 
11008 	/* adding a new btf type invalidates existing pointers to btf objects,
11009 	 * so refresh pointers before proceeding
11010 	 */
11011 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
11012 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11013 	var_type = btf_type_by_id(btf, var->type);
11014 
11015 	/* finally update btf info */
11016 	datasec_type->size = size;
11017 	var->size = size - var->offset;
11018 	var_type->type = new_array_id;
11019 
11020 	return 0;
11021 }
11022 
bpf_map__set_value_size(struct bpf_map * map,__u32 size)11023 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
11024 {
11025 	if (map_is_created(map))
11026 		return libbpf_err(-EBUSY);
11027 
11028 	if (map->mmaped) {
11029 		size_t mmap_old_sz, mmap_new_sz;
11030 		int err;
11031 
11032 		if (map->def.type != BPF_MAP_TYPE_ARRAY &&
11033 		    map->def.type != BPF_MAP_TYPE_PERCPU_ARRAY)
11034 			return libbpf_err(-EOPNOTSUPP);
11035 
11036 		mmap_old_sz = bpf_map_mmap_sz(map);
11037 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
11038 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
11039 		if (err) {
11040 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
11041 				bpf_map__name(map), errstr(err));
11042 			return libbpf_err(err);
11043 		}
11044 		err = map_btf_datasec_resize(map, size);
11045 		if (err && err != -ENOENT) {
11046 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
11047 				bpf_map__name(map), errstr(err));
11048 			map->btf_value_type_id = 0;
11049 			map->btf_key_type_id = 0;
11050 		}
11051 	}
11052 
11053 	map->def.value_size = size;
11054 	return 0;
11055 }
11056 
bpf_map__btf_key_type_id(const struct bpf_map * map)11057 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
11058 {
11059 	return map ? map->btf_key_type_id : 0;
11060 }
11061 
bpf_map__btf_value_type_id(const struct bpf_map * map)11062 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
11063 {
11064 	return map ? map->btf_value_type_id : 0;
11065 }
11066 
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)11067 int bpf_map__set_initial_value(struct bpf_map *map,
11068 			       const void *data, size_t size)
11069 {
11070 	size_t actual_sz;
11071 
11072 	if (map_is_created(map))
11073 		return libbpf_err(-EBUSY);
11074 
11075 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
11076 		return libbpf_err(-EINVAL);
11077 
11078 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11079 		actual_sz = map->obj->arena_data_sz;
11080 	else
11081 		actual_sz = map->def.value_size;
11082 	if (size != actual_sz)
11083 		return libbpf_err(-EINVAL);
11084 
11085 	memcpy(map->mmaped, data, size);
11086 	return 0;
11087 }
11088 
bpf_map__initial_value(const struct bpf_map * map,size_t * psize)11089 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
11090 {
11091 	if (bpf_map__is_struct_ops(map)) {
11092 		if (psize)
11093 			*psize = map->def.value_size;
11094 		return map->st_ops->data;
11095 	}
11096 
11097 	if (!map->mmaped)
11098 		return NULL;
11099 
11100 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11101 		*psize = map->obj->arena_data_sz;
11102 	else
11103 		*psize = map->def.value_size;
11104 
11105 	return map->mmaped;
11106 }
11107 
bpf_map__is_internal(const struct bpf_map * map)11108 bool bpf_map__is_internal(const struct bpf_map *map)
11109 {
11110 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
11111 }
11112 
bpf_map__ifindex(const struct bpf_map * map)11113 __u32 bpf_map__ifindex(const struct bpf_map *map)
11114 {
11115 	return map->map_ifindex;
11116 }
11117 
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)11118 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
11119 {
11120 	if (map_is_created(map))
11121 		return libbpf_err(-EBUSY);
11122 	map->map_ifindex = ifindex;
11123 	return 0;
11124 }
11125 
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)11126 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
11127 {
11128 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
11129 		pr_warn("error: unsupported map type\n");
11130 		return libbpf_err(-EINVAL);
11131 	}
11132 	if (map->inner_map_fd != -1) {
11133 		pr_warn("error: inner_map_fd already specified\n");
11134 		return libbpf_err(-EINVAL);
11135 	}
11136 	if (map->inner_map) {
11137 		bpf_map__destroy(map->inner_map);
11138 		zfree(&map->inner_map);
11139 	}
11140 	map->inner_map_fd = fd;
11141 	return 0;
11142 }
11143 
bpf_map__set_exclusive_program(struct bpf_map * map,struct bpf_program * prog)11144 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
11145 {
11146 	if (map_is_created(map)) {
11147 		pr_warn("exclusive programs must be set before map creation\n");
11148 		return libbpf_err(-EINVAL);
11149 	}
11150 
11151 	if (map->obj != prog->obj) {
11152 		pr_warn("excl_prog and map must be from the same bpf object\n");
11153 		return libbpf_err(-EINVAL);
11154 	}
11155 
11156 	map->excl_prog = prog;
11157 	return 0;
11158 }
11159 
bpf_map__exclusive_program(struct bpf_map * map)11160 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11161 {
11162 	return map->excl_prog;
11163 }
11164 
11165 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)11166 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11167 {
11168 	ssize_t idx;
11169 	struct bpf_map *s, *e;
11170 
11171 	if (!obj || !obj->maps)
11172 		return errno = EINVAL, NULL;
11173 
11174 	s = obj->maps;
11175 	e = obj->maps + obj->nr_maps;
11176 
11177 	if ((m < s) || (m >= e)) {
11178 		pr_warn("error in %s: map handler doesn't belong to object\n",
11179 			 __func__);
11180 		return errno = EINVAL, NULL;
11181 	}
11182 
11183 	idx = (m - obj->maps) + i;
11184 	if (idx >= obj->nr_maps || idx < 0)
11185 		return NULL;
11186 	return &obj->maps[idx];
11187 }
11188 
11189 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)11190 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11191 {
11192 	if (prev == NULL && obj != NULL)
11193 		return obj->maps;
11194 
11195 	return __bpf_map__iter(prev, obj, 1);
11196 }
11197 
11198 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)11199 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11200 {
11201 	if (next == NULL && obj != NULL) {
11202 		if (!obj->nr_maps)
11203 			return NULL;
11204 		return obj->maps + obj->nr_maps - 1;
11205 	}
11206 
11207 	return __bpf_map__iter(next, obj, -1);
11208 }
11209 
11210 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)11211 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11212 {
11213 	struct bpf_map *pos;
11214 
11215 	bpf_object__for_each_map(pos, obj) {
11216 		/* if it's a special internal map name (which always starts
11217 		 * with dot) then check if that special name matches the
11218 		 * real map name (ELF section name)
11219 		 */
11220 		if (name[0] == '.') {
11221 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11222 				return pos;
11223 			continue;
11224 		}
11225 		/* otherwise map name has to be an exact match */
11226 		if (map_uses_real_name(pos)) {
11227 			if (strcmp(pos->real_name, name) == 0)
11228 				return pos;
11229 			continue;
11230 		}
11231 		if (strcmp(pos->name, name) == 0)
11232 			return pos;
11233 	}
11234 	return errno = ENOENT, NULL;
11235 }
11236 
11237 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)11238 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11239 {
11240 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11241 }
11242 
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz,__u64 flags)11243 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11244 			   size_t value_sz, bool check_value_sz, __u64 flags)
11245 {
11246 	if (!map_is_created(map)) /* map is not yet created */
11247 		return -ENOENT;
11248 
11249 	if (map->def.key_size != key_sz) {
11250 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11251 			map->name, key_sz, map->def.key_size);
11252 		return -EINVAL;
11253 	}
11254 
11255 	if (map->fd < 0) {
11256 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11257 		return -EINVAL;
11258 	}
11259 
11260 	if (!check_value_sz)
11261 		return 0;
11262 
11263 	switch (map->def.type) {
11264 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11265 	case BPF_MAP_TYPE_PERCPU_HASH:
11266 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11267 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11268 		int num_cpu = libbpf_num_possible_cpus();
11269 		size_t elem_sz = roundup(map->def.value_size, 8);
11270 
11271 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11272 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11273 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11274 					map->name);
11275 				return -EINVAL;
11276 			}
11277 			if (map->def.value_size != value_sz) {
11278 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11279 					map->name, value_sz, map->def.value_size);
11280 				return -EINVAL;
11281 			}
11282 			break;
11283 		}
11284 
11285 		if (value_sz != num_cpu * elem_sz) {
11286 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zu\n",
11287 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11288 			return -EINVAL;
11289 		}
11290 		break;
11291 	}
11292 	default:
11293 		if (map->def.value_size != value_sz) {
11294 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11295 				map->name, value_sz, map->def.value_size);
11296 			return -EINVAL;
11297 		}
11298 		break;
11299 	}
11300 	return 0;
11301 }
11302 
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)11303 int bpf_map__lookup_elem(const struct bpf_map *map,
11304 			 const void *key, size_t key_sz,
11305 			 void *value, size_t value_sz, __u64 flags)
11306 {
11307 	int err;
11308 
11309 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11310 	if (err)
11311 		return libbpf_err(err);
11312 
11313 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11314 }
11315 
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)11316 int bpf_map__update_elem(const struct bpf_map *map,
11317 			 const void *key, size_t key_sz,
11318 			 const void *value, size_t value_sz, __u64 flags)
11319 {
11320 	int err;
11321 
11322 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11323 	if (err)
11324 		return libbpf_err(err);
11325 
11326 	return bpf_map_update_elem(map->fd, key, value, flags);
11327 }
11328 
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)11329 int bpf_map__delete_elem(const struct bpf_map *map,
11330 			 const void *key, size_t key_sz, __u64 flags)
11331 {
11332 	int err;
11333 
11334 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11335 	if (err)
11336 		return libbpf_err(err);
11337 
11338 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11339 }
11340 
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)11341 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11342 				    const void *key, size_t key_sz,
11343 				    void *value, size_t value_sz, __u64 flags)
11344 {
11345 	int err;
11346 
11347 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11348 	if (err)
11349 		return libbpf_err(err);
11350 
11351 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11352 }
11353 
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)11354 int bpf_map__get_next_key(const struct bpf_map *map,
11355 			  const void *cur_key, void *next_key, size_t key_sz)
11356 {
11357 	int err;
11358 
11359 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11360 	if (err)
11361 		return libbpf_err(err);
11362 
11363 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11364 }
11365 
libbpf_get_error(const void * ptr)11366 long libbpf_get_error(const void *ptr)
11367 {
11368 	if (!IS_ERR_OR_NULL(ptr))
11369 		return 0;
11370 
11371 	if (IS_ERR(ptr))
11372 		errno = -PTR_ERR(ptr);
11373 
11374 	/* If ptr == NULL, then errno should be already set by the failing
11375 	 * API, because libbpf never returns NULL on success and it now always
11376 	 * sets errno on error. So no extra errno handling for ptr == NULL
11377 	 * case.
11378 	 */
11379 	return -errno;
11380 }
11381 
11382 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)11383 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11384 {
11385 	int ret;
11386 	int prog_fd = bpf_program__fd(prog);
11387 
11388 	if (prog_fd < 0) {
11389 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11390 			prog->name);
11391 		return libbpf_err(-EINVAL);
11392 	}
11393 
11394 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11395 	return libbpf_err_errno(ret);
11396 }
11397 
11398 /* Release "ownership" of underlying BPF resource (typically, BPF program
11399  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11400  * link, when destructed through bpf_link__destroy() call won't attempt to
11401  * detach/unregisted that BPF resource. This is useful in situations where,
11402  * say, attached BPF program has to outlive userspace program that attached it
11403  * in the system. Depending on type of BPF program, though, there might be
11404  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11405  * exit of userspace program doesn't trigger automatic detachment and clean up
11406  * inside the kernel.
11407  */
bpf_link__disconnect(struct bpf_link * link)11408 void bpf_link__disconnect(struct bpf_link *link)
11409 {
11410 	link->disconnected = true;
11411 }
11412 
bpf_link__destroy(struct bpf_link * link)11413 int bpf_link__destroy(struct bpf_link *link)
11414 {
11415 	int err = 0;
11416 
11417 	if (IS_ERR_OR_NULL(link))
11418 		return 0;
11419 
11420 	if (!link->disconnected && link->detach)
11421 		err = link->detach(link);
11422 	if (link->pin_path)
11423 		free(link->pin_path);
11424 	if (link->dealloc)
11425 		link->dealloc(link);
11426 	else
11427 		free(link);
11428 
11429 	return libbpf_err(err);
11430 }
11431 
bpf_link__fd(const struct bpf_link * link)11432 int bpf_link__fd(const struct bpf_link *link)
11433 {
11434 	return link->fd;
11435 }
11436 
bpf_link__pin_path(const struct bpf_link * link)11437 const char *bpf_link__pin_path(const struct bpf_link *link)
11438 {
11439 	return link->pin_path;
11440 }
11441 
bpf_link__detach_fd(struct bpf_link * link)11442 static int bpf_link__detach_fd(struct bpf_link *link)
11443 {
11444 	return libbpf_err_errno(close(link->fd));
11445 }
11446 
bpf_link__open(const char * path)11447 struct bpf_link *bpf_link__open(const char *path)
11448 {
11449 	struct bpf_link *link;
11450 	int fd;
11451 
11452 	fd = bpf_obj_get(path);
11453 	if (fd < 0) {
11454 		fd = -errno;
11455 		pr_warn("failed to open link at %s: %d\n", path, fd);
11456 		return libbpf_err_ptr(fd);
11457 	}
11458 
11459 	link = calloc(1, sizeof(*link));
11460 	if (!link) {
11461 		close(fd);
11462 		return libbpf_err_ptr(-ENOMEM);
11463 	}
11464 	link->detach = &bpf_link__detach_fd;
11465 	link->fd = fd;
11466 
11467 	link->pin_path = strdup(path);
11468 	if (!link->pin_path) {
11469 		bpf_link__destroy(link);
11470 		return libbpf_err_ptr(-ENOMEM);
11471 	}
11472 
11473 	return link;
11474 }
11475 
bpf_link__detach(struct bpf_link * link)11476 int bpf_link__detach(struct bpf_link *link)
11477 {
11478 	return bpf_link_detach(link->fd) ? -errno : 0;
11479 }
11480 
bpf_link__pin(struct bpf_link * link,const char * path)11481 int bpf_link__pin(struct bpf_link *link, const char *path)
11482 {
11483 	int err;
11484 
11485 	if (link->pin_path)
11486 		return libbpf_err(-EBUSY);
11487 	err = make_parent_dir(path);
11488 	if (err)
11489 		return libbpf_err(err);
11490 	err = check_path(path);
11491 	if (err)
11492 		return libbpf_err(err);
11493 
11494 	link->pin_path = strdup(path);
11495 	if (!link->pin_path)
11496 		return libbpf_err(-ENOMEM);
11497 
11498 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11499 		err = -errno;
11500 		zfree(&link->pin_path);
11501 		return libbpf_err(err);
11502 	}
11503 
11504 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11505 	return 0;
11506 }
11507 
bpf_link__unpin(struct bpf_link * link)11508 int bpf_link__unpin(struct bpf_link *link)
11509 {
11510 	int err;
11511 
11512 	if (!link->pin_path)
11513 		return libbpf_err(-EINVAL);
11514 
11515 	err = unlink(link->pin_path);
11516 	if (err != 0)
11517 		return -errno;
11518 
11519 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11520 	zfree(&link->pin_path);
11521 	return 0;
11522 }
11523 
11524 struct bpf_link_perf {
11525 	struct bpf_link link;
11526 	int perf_event_fd;
11527 	/* legacy kprobe support: keep track of probe identifier and type */
11528 	char *legacy_probe_name;
11529 	bool legacy_is_kprobe;
11530 	bool legacy_is_retprobe;
11531 };
11532 
11533 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11534 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11535 
bpf_link_perf_detach(struct bpf_link * link)11536 static int bpf_link_perf_detach(struct bpf_link *link)
11537 {
11538 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11539 	int err = 0;
11540 
11541 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11542 		err = -errno;
11543 
11544 	if (perf_link->perf_event_fd != link->fd)
11545 		close(perf_link->perf_event_fd);
11546 	close(link->fd);
11547 
11548 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11549 	if (perf_link->legacy_probe_name) {
11550 		if (perf_link->legacy_is_kprobe) {
11551 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11552 							 perf_link->legacy_is_retprobe);
11553 		} else {
11554 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11555 							 perf_link->legacy_is_retprobe);
11556 		}
11557 	}
11558 
11559 	return err;
11560 }
11561 
bpf_link_perf_dealloc(struct bpf_link * link)11562 static void bpf_link_perf_dealloc(struct bpf_link *link)
11563 {
11564 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11565 
11566 	free(perf_link->legacy_probe_name);
11567 	free(perf_link);
11568 }
11569 
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)11570 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11571 						     const struct bpf_perf_event_opts *opts)
11572 {
11573 	struct bpf_link_perf *link;
11574 	int prog_fd, link_fd = -1, err;
11575 	bool force_ioctl_attach;
11576 
11577 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11578 		return libbpf_err_ptr(-EINVAL);
11579 
11580 	if (pfd < 0) {
11581 		pr_warn("prog '%s': invalid perf event FD %d\n",
11582 			prog->name, pfd);
11583 		return libbpf_err_ptr(-EINVAL);
11584 	}
11585 	prog_fd = bpf_program__fd(prog);
11586 	if (prog_fd < 0) {
11587 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11588 			prog->name);
11589 		return libbpf_err_ptr(-EINVAL);
11590 	}
11591 
11592 	link = calloc(1, sizeof(*link));
11593 	if (!link)
11594 		return libbpf_err_ptr(-ENOMEM);
11595 	link->link.detach = &bpf_link_perf_detach;
11596 	link->link.dealloc = &bpf_link_perf_dealloc;
11597 	link->perf_event_fd = pfd;
11598 
11599 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11600 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11601 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11602 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11603 
11604 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11605 		if (link_fd < 0) {
11606 			err = -errno;
11607 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11608 				prog->name, pfd, errstr(err));
11609 			goto err_out;
11610 		}
11611 		link->link.fd = link_fd;
11612 	} else {
11613 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11614 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11615 			err = -EOPNOTSUPP;
11616 			goto err_out;
11617 		}
11618 
11619 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11620 			err = -errno;
11621 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11622 				prog->name, pfd, errstr(err));
11623 			if (err == -EPROTO)
11624 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11625 					prog->name, pfd);
11626 			goto err_out;
11627 		}
11628 		link->link.fd = pfd;
11629 	}
11630 
11631 	if (!OPTS_GET(opts, dont_enable, false)) {
11632 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11633 			err = -errno;
11634 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11635 				prog->name, pfd, errstr(err));
11636 			goto err_out;
11637 		}
11638 	}
11639 
11640 	return &link->link;
11641 err_out:
11642 	if (link_fd >= 0)
11643 		close(link_fd);
11644 	free(link);
11645 	return libbpf_err_ptr(err);
11646 }
11647 
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)11648 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11649 {
11650 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11651 }
11652 
11653 /*
11654  * this function is expected to parse integer in the range of [0, 2^31-1] from
11655  * given file using scanf format string fmt. If actual parsed value is
11656  * negative, the result might be indistinguishable from error
11657  */
parse_uint_from_file(const char * file,const char * fmt)11658 static int parse_uint_from_file(const char *file, const char *fmt)
11659 {
11660 	int err, ret;
11661 	FILE *f;
11662 
11663 	f = fopen(file, "re");
11664 	if (!f) {
11665 		err = -errno;
11666 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11667 		return err;
11668 	}
11669 	err = fscanf(f, fmt, &ret);
11670 	if (err != 1) {
11671 		err = err == EOF ? -EIO : -errno;
11672 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11673 		fclose(f);
11674 		return err;
11675 	}
11676 	fclose(f);
11677 	return ret;
11678 }
11679 
determine_kprobe_perf_type(void)11680 static int determine_kprobe_perf_type(void)
11681 {
11682 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11683 
11684 	return parse_uint_from_file(file, "%d\n");
11685 }
11686 
determine_uprobe_perf_type(void)11687 static int determine_uprobe_perf_type(void)
11688 {
11689 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11690 
11691 	return parse_uint_from_file(file, "%d\n");
11692 }
11693 
determine_kprobe_retprobe_bit(void)11694 static int determine_kprobe_retprobe_bit(void)
11695 {
11696 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11697 
11698 	return parse_uint_from_file(file, "config:%d\n");
11699 }
11700 
determine_uprobe_retprobe_bit(void)11701 static int determine_uprobe_retprobe_bit(void)
11702 {
11703 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11704 
11705 	return parse_uint_from_file(file, "config:%d\n");
11706 }
11707 
11708 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11709 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11710 
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)11711 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11712 				 uint64_t offset, int pid, size_t ref_ctr_off)
11713 {
11714 	const size_t attr_sz = sizeof(struct perf_event_attr);
11715 	struct perf_event_attr attr;
11716 	int type, pfd;
11717 
11718 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11719 		return -EINVAL;
11720 
11721 	memset(&attr, 0, attr_sz);
11722 
11723 	type = uprobe ? determine_uprobe_perf_type()
11724 		      : determine_kprobe_perf_type();
11725 	if (type < 0) {
11726 		pr_warn("failed to determine %s perf type: %s\n",
11727 			uprobe ? "uprobe" : "kprobe",
11728 			errstr(type));
11729 		return type;
11730 	}
11731 	if (retprobe) {
11732 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11733 				 : determine_kprobe_retprobe_bit();
11734 
11735 		if (bit < 0) {
11736 			pr_warn("failed to determine %s retprobe bit: %s\n",
11737 				uprobe ? "uprobe" : "kprobe",
11738 				errstr(bit));
11739 			return bit;
11740 		}
11741 		attr.config |= 1 << bit;
11742 	}
11743 	attr.size = attr_sz;
11744 	attr.type = type;
11745 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11746 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11747 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11748 
11749 	/* pid filter is meaningful only for uprobes */
11750 	pfd = syscall(__NR_perf_event_open, &attr,
11751 		      pid < 0 ? -1 : pid /* pid */,
11752 		      pid == -1 ? 0 : -1 /* cpu */,
11753 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11754 	return pfd >= 0 ? pfd : -errno;
11755 }
11756 
append_to_file(const char * file,const char * fmt,...)11757 static int append_to_file(const char *file, const char *fmt, ...)
11758 {
11759 	int fd, n, err = 0;
11760 	va_list ap;
11761 	char buf[1024];
11762 
11763 	va_start(ap, fmt);
11764 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11765 	va_end(ap);
11766 
11767 	if (n < 0 || n >= sizeof(buf))
11768 		return -EINVAL;
11769 
11770 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11771 	if (fd < 0)
11772 		return -errno;
11773 
11774 	if (write(fd, buf, n) < 0)
11775 		err = -errno;
11776 
11777 	close(fd);
11778 	return err;
11779 }
11780 
11781 #define DEBUGFS "/sys/kernel/debug/tracing"
11782 #define TRACEFS "/sys/kernel/tracing"
11783 
use_debugfs(void)11784 static bool use_debugfs(void)
11785 {
11786 	static int has_debugfs = -1;
11787 
11788 	if (has_debugfs < 0)
11789 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11790 
11791 	return has_debugfs == 1;
11792 }
11793 
tracefs_path(void)11794 static const char *tracefs_path(void)
11795 {
11796 	return use_debugfs() ? DEBUGFS : TRACEFS;
11797 }
11798 
tracefs_kprobe_events(void)11799 static const char *tracefs_kprobe_events(void)
11800 {
11801 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11802 }
11803 
tracefs_uprobe_events(void)11804 static const char *tracefs_uprobe_events(void)
11805 {
11806 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11807 }
11808 
tracefs_available_filter_functions(void)11809 static const char *tracefs_available_filter_functions(void)
11810 {
11811 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11812 			     : TRACEFS"/available_filter_functions";
11813 }
11814 
tracefs_available_filter_functions_addrs(void)11815 static const char *tracefs_available_filter_functions_addrs(void)
11816 {
11817 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11818 			     : TRACEFS"/available_filter_functions_addrs";
11819 }
11820 
gen_probe_legacy_event_name(char * buf,size_t buf_sz,const char * name,size_t offset)11821 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11822 					const char *name, size_t offset)
11823 {
11824 	static int index = 0;
11825 	int i;
11826 
11827 	snprintf(buf, buf_sz, "libbpf_%d_%d_%s_0x%zx", getpid(),
11828 		 __sync_fetch_and_add(&index, 1), name, offset);
11829 
11830 	/* sanitize name in the probe name */
11831 	for (i = 0; buf[i]; i++) {
11832 		if (!isalnum(buf[i]))
11833 			buf[i] = '_';
11834 	}
11835 }
11836 
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)11837 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11838 				   const char *kfunc_name, size_t offset)
11839 {
11840 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11841 			      retprobe ? 'r' : 'p',
11842 			      retprobe ? "kretprobes" : "kprobes",
11843 			      probe_name, kfunc_name, offset);
11844 }
11845 
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)11846 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11847 {
11848 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11849 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11850 }
11851 
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)11852 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11853 {
11854 	char file[256];
11855 
11856 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11857 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11858 
11859 	return parse_uint_from_file(file, "%d\n");
11860 }
11861 
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)11862 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11863 					 const char *kfunc_name, size_t offset, int pid)
11864 {
11865 	const size_t attr_sz = sizeof(struct perf_event_attr);
11866 	struct perf_event_attr attr;
11867 	int type, pfd, err;
11868 
11869 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11870 	if (err < 0) {
11871 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11872 			kfunc_name, offset,
11873 			errstr(err));
11874 		return err;
11875 	}
11876 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11877 	if (type < 0) {
11878 		err = type;
11879 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11880 			kfunc_name, offset,
11881 			errstr(err));
11882 		goto err_clean_legacy;
11883 	}
11884 
11885 	memset(&attr, 0, attr_sz);
11886 	attr.size = attr_sz;
11887 	attr.config = type;
11888 	attr.type = PERF_TYPE_TRACEPOINT;
11889 
11890 	pfd = syscall(__NR_perf_event_open, &attr,
11891 		      pid < 0 ? -1 : pid, /* pid */
11892 		      pid == -1 ? 0 : -1, /* cpu */
11893 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11894 	if (pfd < 0) {
11895 		err = -errno;
11896 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11897 			errstr(err));
11898 		goto err_clean_legacy;
11899 	}
11900 	return pfd;
11901 
11902 err_clean_legacy:
11903 	/* Clear the newly added legacy kprobe_event */
11904 	remove_kprobe_event_legacy(probe_name, retprobe);
11905 	return err;
11906 }
11907 
arch_specific_syscall_pfx(void)11908 static const char *arch_specific_syscall_pfx(void)
11909 {
11910 #if defined(__x86_64__)
11911 	return "x64";
11912 #elif defined(__i386__)
11913 	return "ia32";
11914 #elif defined(__s390x__)
11915 	return "s390x";
11916 #elif defined(__arm__)
11917 	return "arm";
11918 #elif defined(__aarch64__)
11919 	return "arm64";
11920 #elif defined(__mips__)
11921 	return "mips";
11922 #elif defined(__riscv)
11923 	return "riscv";
11924 #elif defined(__powerpc__)
11925 	return "powerpc";
11926 #elif defined(__powerpc64__)
11927 	return "powerpc64";
11928 #else
11929 	return NULL;
11930 #endif
11931 }
11932 
probe_kern_syscall_wrapper(int token_fd)11933 int probe_kern_syscall_wrapper(int token_fd)
11934 {
11935 	char syscall_name[64];
11936 	const char *ksys_pfx;
11937 
11938 	ksys_pfx = arch_specific_syscall_pfx();
11939 	if (!ksys_pfx)
11940 		return 0;
11941 
11942 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11943 
11944 	if (determine_kprobe_perf_type() >= 0) {
11945 		int pfd;
11946 
11947 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11948 		if (pfd >= 0)
11949 			close(pfd);
11950 
11951 		return pfd >= 0 ? 1 : 0;
11952 	} else { /* legacy mode */
11953 		char probe_name[MAX_EVENT_NAME_LEN];
11954 
11955 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11956 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11957 			return 0;
11958 
11959 		(void)remove_kprobe_event_legacy(probe_name, false);
11960 		return 1;
11961 	}
11962 }
11963 
11964 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)11965 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11966 				const char *func_name,
11967 				const struct bpf_kprobe_opts *opts)
11968 {
11969 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11970 	enum probe_attach_mode attach_mode;
11971 	char *legacy_probe = NULL;
11972 	struct bpf_link *link;
11973 	size_t offset;
11974 	bool retprobe, legacy;
11975 	int pfd, err;
11976 
11977 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11978 		return libbpf_err_ptr(-EINVAL);
11979 
11980 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11981 	retprobe = OPTS_GET(opts, retprobe, false);
11982 	offset = OPTS_GET(opts, offset, 0);
11983 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11984 
11985 	legacy = determine_kprobe_perf_type() < 0;
11986 	switch (attach_mode) {
11987 	case PROBE_ATTACH_MODE_LEGACY:
11988 		legacy = true;
11989 		pe_opts.force_ioctl_attach = true;
11990 		break;
11991 	case PROBE_ATTACH_MODE_PERF:
11992 		if (legacy)
11993 			return libbpf_err_ptr(-ENOTSUP);
11994 		pe_opts.force_ioctl_attach = true;
11995 		break;
11996 	case PROBE_ATTACH_MODE_LINK:
11997 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11998 			return libbpf_err_ptr(-ENOTSUP);
11999 		break;
12000 	case PROBE_ATTACH_MODE_DEFAULT:
12001 		break;
12002 	default:
12003 		return libbpf_err_ptr(-EINVAL);
12004 	}
12005 	if (!func_name && legacy)
12006 		return libbpf_err_ptr(-EOPNOTSUPP);
12007 
12008 	if (!legacy) {
12009 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
12010 					    func_name, offset,
12011 					    -1 /* pid */, 0 /* ref_ctr_off */);
12012 	} else {
12013 		char probe_name[MAX_EVENT_NAME_LEN];
12014 
12015 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12016 					    func_name, offset);
12017 
12018 		legacy_probe = strdup(probe_name);
12019 		if (!legacy_probe)
12020 			return libbpf_err_ptr(-ENOMEM);
12021 
12022 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
12023 						    offset, -1 /* pid */);
12024 	}
12025 	if (pfd < 0) {
12026 		err = pfd;
12027 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
12028 			prog->name, retprobe ? "kretprobe" : "kprobe",
12029 			func_name ?: "", func_name ? "+" : "",
12030 			offset, errstr(err));
12031 		goto err_out;
12032 	}
12033 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12034 	err = libbpf_get_error(link);
12035 	if (err) {
12036 		close(pfd);
12037 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
12038 			prog->name, retprobe ? "kretprobe" : "kprobe",
12039 			func_name ?: "", func_name ? "+" : "",
12040 			offset, errstr(err));
12041 		goto err_clean_legacy;
12042 	}
12043 	if (legacy) {
12044 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12045 
12046 		perf_link->legacy_probe_name = legacy_probe;
12047 		perf_link->legacy_is_kprobe = true;
12048 		perf_link->legacy_is_retprobe = retprobe;
12049 	}
12050 
12051 	return link;
12052 
12053 err_clean_legacy:
12054 	if (legacy)
12055 		remove_kprobe_event_legacy(legacy_probe, retprobe);
12056 err_out:
12057 	free(legacy_probe);
12058 	return libbpf_err_ptr(err);
12059 }
12060 
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)12061 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
12062 					    bool retprobe,
12063 					    const char *func_name)
12064 {
12065 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
12066 		.retprobe = retprobe,
12067 	);
12068 
12069 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
12070 }
12071 
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)12072 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
12073 					      const char *syscall_name,
12074 					      const struct bpf_ksyscall_opts *opts)
12075 {
12076 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
12077 	char func_name[128];
12078 
12079 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
12080 		return libbpf_err_ptr(-EINVAL);
12081 
12082 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
12083 		/* arch_specific_syscall_pfx() should never return NULL here
12084 		 * because it is guarded by kernel_supports(). However, since
12085 		 * compiler does not know that we have an explicit conditional
12086 		 * as well.
12087 		 */
12088 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
12089 			 arch_specific_syscall_pfx() ? : "", syscall_name);
12090 	} else {
12091 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
12092 	}
12093 
12094 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
12095 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12096 
12097 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
12098 }
12099 
12100 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)12101 bool glob_match(const char *str, const char *pat)
12102 {
12103 	while (*str && *pat && *pat != '*') {
12104 		if (*pat == '?') {      /* Matches any single character */
12105 			str++;
12106 			pat++;
12107 			continue;
12108 		}
12109 		if (*str != *pat)
12110 			return false;
12111 		str++;
12112 		pat++;
12113 	}
12114 	/* Check wild card */
12115 	if (*pat == '*') {
12116 		while (*pat == '*')
12117 			pat++;
12118 		if (!*pat) /* Tail wild card matches all */
12119 			return true;
12120 		while (*str)
12121 			if (glob_match(str++, pat))
12122 				return true;
12123 	}
12124 	return !*str && !*pat;
12125 }
12126 
12127 struct kprobe_multi_resolve {
12128 	const char *pattern;
12129 	unsigned long *addrs;
12130 	size_t cap;
12131 	size_t cnt;
12132 };
12133 
12134 struct avail_kallsyms_data {
12135 	char **syms;
12136 	size_t cnt;
12137 	struct kprobe_multi_resolve *res;
12138 };
12139 
avail_func_cmp(const void * a,const void * b)12140 static int avail_func_cmp(const void *a, const void *b)
12141 {
12142 	return strcmp(*(const char **)a, *(const char **)b);
12143 }
12144 
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)12145 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
12146 			     const char *sym_name, void *ctx)
12147 {
12148 	struct avail_kallsyms_data *data = ctx;
12149 	struct kprobe_multi_resolve *res = data->res;
12150 	int err;
12151 
12152 	if (!glob_match(sym_name, res->pattern))
12153 		return 0;
12154 
12155 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12156 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12157 		 * function names reported in available_filter_functions, but
12158 		 * don't do so for kallsyms. While this is clearly a kernel
12159 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12160 		 * make multi-kprobe usability a bit better: if no match is
12161 		 * found, we will strip .llvm. suffix and try one more time.
12162 		 *
12163 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12164 		 */
12165 		char sym_trim[256], *psym_trim = sym_trim;
12166 		const char *sym_sfx;
12167 
12168 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12169 			return 0;
12170 
12171 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12172 		 * coercion differences and get proper `const char **` pointer
12173 		 * which avail_func_cmp() expects
12174 		 */
12175 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12176 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12177 			return 0;
12178 	}
12179 
12180 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12181 	if (err)
12182 		return err;
12183 
12184 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12185 	return 0;
12186 }
12187 
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)12188 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12189 {
12190 	const char *available_functions_file = tracefs_available_filter_functions();
12191 	struct avail_kallsyms_data data;
12192 	char sym_name[500];
12193 	FILE *f;
12194 	int err = 0, ret, i;
12195 	char **syms = NULL;
12196 	size_t cap = 0, cnt = 0;
12197 
12198 	f = fopen(available_functions_file, "re");
12199 	if (!f) {
12200 		err = -errno;
12201 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12202 		return err;
12203 	}
12204 
12205 	while (true) {
12206 		char *name;
12207 
12208 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12209 		if (ret == EOF && feof(f))
12210 			break;
12211 
12212 		if (ret != 1) {
12213 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12214 			err = -EINVAL;
12215 			goto cleanup;
12216 		}
12217 
12218 		if (!glob_match(sym_name, res->pattern))
12219 			continue;
12220 
12221 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12222 		if (err)
12223 			goto cleanup;
12224 
12225 		name = strdup(sym_name);
12226 		if (!name) {
12227 			err = -errno;
12228 			goto cleanup;
12229 		}
12230 
12231 		syms[cnt++] = name;
12232 	}
12233 
12234 	/* no entries found, bail out */
12235 	if (cnt == 0) {
12236 		err = -ENOENT;
12237 		goto cleanup;
12238 	}
12239 
12240 	/* sort available functions */
12241 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12242 
12243 	data.syms = syms;
12244 	data.res = res;
12245 	data.cnt = cnt;
12246 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12247 
12248 	if (res->cnt == 0)
12249 		err = -ENOENT;
12250 
12251 cleanup:
12252 	for (i = 0; i < cnt; i++)
12253 		free((char *)syms[i]);
12254 	free(syms);
12255 
12256 	fclose(f);
12257 	return err;
12258 }
12259 
has_available_filter_functions_addrs(void)12260 static bool has_available_filter_functions_addrs(void)
12261 {
12262 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12263 }
12264 
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)12265 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12266 {
12267 	const char *available_path = tracefs_available_filter_functions_addrs();
12268 	char sym_name[500];
12269 	FILE *f;
12270 	int ret, err = 0;
12271 	unsigned long long sym_addr;
12272 
12273 	f = fopen(available_path, "re");
12274 	if (!f) {
12275 		err = -errno;
12276 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12277 		return err;
12278 	}
12279 
12280 	while (true) {
12281 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12282 		if (ret == EOF && feof(f))
12283 			break;
12284 
12285 		if (ret != 2) {
12286 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12287 				ret);
12288 			err = -EINVAL;
12289 			goto cleanup;
12290 		}
12291 
12292 		if (!glob_match(sym_name, res->pattern))
12293 			continue;
12294 
12295 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12296 					sizeof(*res->addrs), res->cnt + 1);
12297 		if (err)
12298 			goto cleanup;
12299 
12300 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12301 	}
12302 
12303 	if (res->cnt == 0)
12304 		err = -ENOENT;
12305 
12306 cleanup:
12307 	fclose(f);
12308 	return err;
12309 }
12310 
12311 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)12312 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12313 				      const char *pattern,
12314 				      const struct bpf_kprobe_multi_opts *opts)
12315 {
12316 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12317 	struct kprobe_multi_resolve res = {
12318 		.pattern = pattern,
12319 	};
12320 	enum bpf_attach_type attach_type;
12321 	struct bpf_link *link = NULL;
12322 	const unsigned long *addrs;
12323 	int err, link_fd, prog_fd;
12324 	bool retprobe, session, unique_match;
12325 	const __u64 *cookies;
12326 	const char **syms;
12327 	size_t cnt;
12328 
12329 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12330 		return libbpf_err_ptr(-EINVAL);
12331 
12332 	prog_fd = bpf_program__fd(prog);
12333 	if (prog_fd < 0) {
12334 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12335 			prog->name);
12336 		return libbpf_err_ptr(-EINVAL);
12337 	}
12338 
12339 	syms    = OPTS_GET(opts, syms, false);
12340 	addrs   = OPTS_GET(opts, addrs, false);
12341 	cnt     = OPTS_GET(opts, cnt, false);
12342 	cookies = OPTS_GET(opts, cookies, false);
12343 	unique_match = OPTS_GET(opts, unique_match, false);
12344 
12345 	if (!pattern && !addrs && !syms)
12346 		return libbpf_err_ptr(-EINVAL);
12347 	if (pattern && (addrs || syms || cookies || cnt))
12348 		return libbpf_err_ptr(-EINVAL);
12349 	if (!pattern && !cnt)
12350 		return libbpf_err_ptr(-EINVAL);
12351 	if (!pattern && unique_match)
12352 		return libbpf_err_ptr(-EINVAL);
12353 	if (addrs && syms)
12354 		return libbpf_err_ptr(-EINVAL);
12355 
12356 	/*
12357 	 * Exact function name (no wildcards) without unique_match:
12358 	 * bypass kallsyms parsing and pass the symbol directly to the
12359 	 * kernel via syms[] array.  When unique_match is set, fall
12360 	 * through to the slow path which detects duplicate symbols.
12361 	 */
12362 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12363 		syms = &pattern;
12364 		cnt = 1;
12365 	} else if (pattern) {
12366 		if (has_available_filter_functions_addrs())
12367 			err = libbpf_available_kprobes_parse(&res);
12368 		else
12369 			err = libbpf_available_kallsyms_parse(&res);
12370 		if (err)
12371 			goto error;
12372 
12373 		if (unique_match && res.cnt != 1) {
12374 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12375 				prog->name, pattern, res.cnt);
12376 			err = -EINVAL;
12377 			goto error;
12378 		}
12379 
12380 		addrs = res.addrs;
12381 		cnt = res.cnt;
12382 	}
12383 
12384 	retprobe = OPTS_GET(opts, retprobe, false);
12385 	session  = OPTS_GET(opts, session, false);
12386 
12387 	if (retprobe && session)
12388 		return libbpf_err_ptr(-EINVAL);
12389 
12390 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12391 
12392 	lopts.kprobe_multi.syms = syms;
12393 	lopts.kprobe_multi.addrs = addrs;
12394 	lopts.kprobe_multi.cookies = cookies;
12395 	lopts.kprobe_multi.cnt = cnt;
12396 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12397 
12398 	link = calloc(1, sizeof(*link));
12399 	if (!link) {
12400 		err = -ENOMEM;
12401 		goto error;
12402 	}
12403 	link->detach = &bpf_link__detach_fd;
12404 
12405 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12406 	if (link_fd < 0) {
12407 		err = -errno;
12408 		/*
12409 		 * Normalize error code: when exact name bypasses kallsyms
12410 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
12411 		 * Convert to ENOENT for API consistency with the pattern
12412 		 * matching path which returns ENOENT from userspace.
12413 		 */
12414 		if (err == -ESRCH)
12415 			err = -ENOENT;
12416 		pr_warn("prog '%s': failed to attach: %s\n",
12417 			prog->name, errstr(err));
12418 		goto error;
12419 	}
12420 	link->fd = link_fd;
12421 	free(res.addrs);
12422 	return link;
12423 
12424 error:
12425 	free(link);
12426 	free(res.addrs);
12427 	return libbpf_err_ptr(err);
12428 }
12429 
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12430 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12431 {
12432 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12433 	long offset = 0;
12434 	const char *func_name;
12435 	char *func;
12436 	int n;
12437 
12438 	*link = NULL;
12439 
12440 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12441 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12442 		return 0;
12443 
12444 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12445 	if (opts.retprobe)
12446 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12447 	else
12448 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12449 
12450 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12451 	if (n < 1) {
12452 		pr_warn("kprobe name is invalid: %s\n", func_name);
12453 		return -EINVAL;
12454 	}
12455 
12456 	if (offset < 0) {
12457 		free(func);
12458 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
12459 		return -EINVAL;
12460 	}
12461 
12462 	if (opts.retprobe && offset != 0) {
12463 		free(func);
12464 		pr_warn("kretprobes do not support offset specification\n");
12465 		return -EINVAL;
12466 	}
12467 
12468 	opts.offset = offset;
12469 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12470 	free(func);
12471 	return libbpf_get_error(*link);
12472 }
12473 
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12474 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12475 {
12476 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12477 	const char *syscall_name;
12478 
12479 	*link = NULL;
12480 
12481 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12482 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12483 		return 0;
12484 
12485 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12486 	if (opts.retprobe)
12487 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12488 	else
12489 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12490 
12491 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12492 	return *link ? 0 : -errno;
12493 }
12494 
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12495 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12496 {
12497 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12498 	const char *spec;
12499 	char *pattern;
12500 	int n;
12501 
12502 	*link = NULL;
12503 
12504 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12505 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12506 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12507 		return 0;
12508 
12509 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12510 	if (opts.retprobe)
12511 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12512 	else
12513 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12514 
12515 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12516 	if (n < 1) {
12517 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12518 		return -EINVAL;
12519 	}
12520 
12521 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12522 	free(pattern);
12523 	return libbpf_get_error(*link);
12524 }
12525 
attach_kprobe_session(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12526 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12527 				 struct bpf_link **link)
12528 {
12529 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12530 	const char *spec;
12531 	char *pattern;
12532 	int n;
12533 
12534 	*link = NULL;
12535 
12536 	/* no auto-attach for SEC("kprobe.session") */
12537 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12538 		return 0;
12539 
12540 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12541 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12542 	if (n < 1) {
12543 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12544 		return -EINVAL;
12545 	}
12546 
12547 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12548 	free(pattern);
12549 	return *link ? 0 : -errno;
12550 }
12551 
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12552 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12553 {
12554 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12555 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12556 	int n, ret = -EINVAL;
12557 
12558 	*link = NULL;
12559 
12560 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12561 		   &probe_type, &binary_path, &func_name);
12562 	switch (n) {
12563 	case 1:
12564 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12565 		ret = 0;
12566 		break;
12567 	case 3:
12568 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12569 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12570 
12571 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12572 		ret = libbpf_get_error(*link);
12573 		break;
12574 	default:
12575 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12576 			prog->sec_name);
12577 		break;
12578 	}
12579 	free(probe_type);
12580 	free(binary_path);
12581 	free(func_name);
12582 	return ret;
12583 }
12584 
12585 #define MAX_BPF_FUNC_ARGS 12
12586 
btf_type_is_modifier(const struct btf_type * t)12587 static bool btf_type_is_modifier(const struct btf_type *t)
12588 {
12589 	switch (BTF_INFO_KIND(t->info)) {
12590 	case BTF_KIND_TYPEDEF:
12591 	case BTF_KIND_VOLATILE:
12592 	case BTF_KIND_CONST:
12593 	case BTF_KIND_RESTRICT:
12594 	case BTF_KIND_TYPE_TAG:
12595 		return true;
12596 	default:
12597 		return false;
12598 	}
12599 }
12600 
12601 #define MAX_RESOLVE_DEPTH 32
12602 
btf_get_type_size(const struct btf * btf,__u32 type_id,const struct btf_type ** ret_type)12603 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
12604 			     const struct btf_type **ret_type)
12605 {
12606 	const struct btf_type *t;
12607 	int i;
12608 
12609 	*ret_type = btf__type_by_id(btf, 0);
12610 	if (!type_id)
12611 		return 0;
12612 	t = btf__type_by_id(btf, type_id);
12613 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
12614 		t = btf__type_by_id(btf, t->type);
12615 	if (!t || i == MAX_RESOLVE_DEPTH)
12616 		return -EINVAL;
12617 	*ret_type = t;
12618 	if (btf_is_ptr(t))
12619 		return btf__pointer_size(btf);
12620 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
12621 		return t->size;
12622 	return -EINVAL;
12623 }
12624 
btf_type_is_traceable_func(const struct btf * btf,const struct btf_type * t)12625 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
12626 {
12627 	const struct btf_param *args;
12628 	const struct btf_type *proto;
12629 	__u32 i, nargs;
12630 	int ret;
12631 
12632 	if (!btf_is_func(t))
12633 		return false;
12634 	proto = btf__type_by_id(btf, t->type);
12635 	if (!proto || !btf_is_func_proto(proto))
12636 		return false;
12637 
12638 	args = (const struct btf_param *)(proto + 1);
12639 	nargs = btf_vlen(proto);
12640 	if (nargs > MAX_BPF_FUNC_ARGS)
12641 		return false;
12642 
12643 	/* No support for struct return type. */
12644 	ret = btf_get_type_size(btf, proto->type, &t);
12645 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
12646 		return false;
12647 
12648 	for (i = 0; i < nargs; i++) {
12649 		/* No support for variable args. */
12650 		if (i == nargs - 1 && args[i].type == 0)
12651 			return false;
12652 		ret = btf_get_type_size(btf, args[i].type, &t);
12653 		/* No support of struct argument size greater than 16 bytes. */
12654 		if (ret < 0 || ret > 16)
12655 			return false;
12656 		/* No support for void argument. */
12657 		if (ret == 0)
12658 			return false;
12659 	}
12660 
12661 	return true;
12662 }
12663 
12664 static int
collect_btf_func_ids_by_glob(const struct btf * btf,const char * pattern,__u32 ** ids)12665 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
12666 {
12667 	__u32 type_id, nr_types = btf__type_cnt(btf);
12668 	size_t cap = 0, cnt = 0;
12669 
12670 	if (!pattern)
12671 		return -EINVAL;
12672 
12673 	for (type_id = 1; type_id < nr_types; type_id++) {
12674 		const struct btf_type *t = btf__type_by_id(btf, type_id);
12675 		const char *name;
12676 		int err;
12677 
12678 		if (btf_kind(t) != BTF_KIND_FUNC)
12679 			continue;
12680 		name = btf__name_by_offset(btf, t->name_off);
12681 		if (!name)
12682 			continue;
12683 
12684 		if (!glob_match(name, pattern))
12685 			continue;
12686 		if (!btf_type_is_traceable_func(btf, t))
12687 			continue;
12688 
12689 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
12690 		if (err) {
12691 			free(*ids);
12692 			return -ENOMEM;
12693 		}
12694 		(*ids)[cnt++] = type_id;
12695 	}
12696 
12697 	return cnt;
12698 }
12699 
collect_func_ids_by_glob(const struct bpf_program * prog,const char * pattern,__u32 ** ids)12700 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
12701 {
12702 	struct bpf_object *obj = prog->obj;
12703 	const struct module_btf *mod;
12704 	struct btf *btf = NULL;
12705 	const char *sep;
12706 	int err;
12707 
12708 	err = bpf_object__load_vmlinux_btf(obj, true);
12709 	if (err)
12710 		return err;
12711 
12712 	/* In case we have module specified, we will find its btf and use that. */
12713 	sep = strchr(pattern, ':');
12714 	if (sep) {
12715 		mod = find_attach_module(obj, pattern);
12716 		if (!mod) {
12717 			err = -EINVAL;
12718 			goto cleanup;
12719 		}
12720 		btf = mod->btf;
12721 		pattern = sep + 1;
12722 	} else {
12723 		/* Program is loaded for kernel module. */
12724 		if (prog->attach_btf_obj_fd) {
12725 			err = -EINVAL;
12726 			goto cleanup;
12727 		}
12728 		btf = obj->btf_vmlinux;
12729 	}
12730 
12731 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
12732 
12733 cleanup:
12734 	bpf_object_cleanup_btf(obj);
12735 	return err;
12736 }
12737 
12738 struct bpf_link *
bpf_program__attach_tracing_multi(const struct bpf_program * prog,const char * pattern,const struct bpf_tracing_multi_opts * opts)12739 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
12740 				  const struct bpf_tracing_multi_opts *opts)
12741 {
12742 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12743 	int prog_fd, link_fd, err, cnt;
12744 	__u32 *free_ids = NULL;
12745 	struct bpf_link *link;
12746 	const __u64 *cookies;
12747 	const __u32 *ids;
12748 
12749 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
12750 		return libbpf_err_ptr(-EINVAL);
12751 
12752 	prog_fd = bpf_program__fd(prog);
12753 	if (prog_fd < 0) {
12754 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12755 			prog->name);
12756 		return libbpf_err_ptr(-EINVAL);
12757 	}
12758 
12759 	cnt = OPTS_GET(opts, cnt, 0);
12760 	ids = OPTS_GET(opts, ids, NULL);
12761 	cookies = OPTS_GET(opts, cookies, NULL);
12762 
12763 	if (!!ids != !!cnt)
12764 		return libbpf_err_ptr(-EINVAL);
12765 	if (pattern && (ids || cookies))
12766 		return libbpf_err_ptr(-EINVAL);
12767 	if (!pattern && !ids)
12768 		return libbpf_err_ptr(-EINVAL);
12769 
12770 	if (pattern) {
12771 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
12772 		if (cnt < 0)
12773 			return libbpf_err_ptr(cnt);
12774 		if (cnt == 0)
12775 			return libbpf_err_ptr(-EINVAL);
12776 		ids = (const __u32 *) free_ids;
12777 	}
12778 
12779 	lopts.tracing_multi.ids = ids;
12780 	lopts.tracing_multi.cookies = cookies;
12781 	lopts.tracing_multi.cnt = cnt;
12782 
12783 	link = calloc(1, sizeof(*link));
12784 	if (!link) {
12785 		err = -ENOMEM;
12786 		goto error;
12787 	}
12788 	link->detach = &bpf_link__detach_fd;
12789 
12790 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
12791 	if (link_fd < 0) {
12792 		err = -errno;
12793 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
12794 		goto error;
12795 	}
12796 	link->fd = link_fd;
12797 	free(free_ids);
12798 	return link;
12799 
12800 error:
12801 	free(link);
12802 	free(free_ids);
12803 	return libbpf_err_ptr(err);
12804 }
12805 
attach_tracing_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12806 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12807 {
12808 	static const char *const prefixes[] = {
12809 		"fentry.multi",
12810 		"fexit.multi",
12811 		"fsession.multi",
12812 		"fentry.multi.s",
12813 		"fexit.multi.s",
12814 		"fsession.multi.s",
12815 	};
12816 	const char *spec = NULL;
12817 	char *pattern;
12818 	size_t i;
12819 	int n;
12820 
12821 	*link = NULL;
12822 
12823 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12824 		size_t pfx_len;
12825 
12826 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12827 			continue;
12828 
12829 		pfx_len = strlen(prefixes[i]);
12830 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
12831 		if (prog->sec_name[pfx_len] == '\0')
12832 			return 0;
12833 
12834 		if (prog->sec_name[pfx_len] != '/')
12835 			continue;
12836 
12837 		spec = prog->sec_name + pfx_len + 1;
12838 		break;
12839 	}
12840 
12841 	if (!spec) {
12842 		pr_warn("prog '%s': invalid section name '%s'\n",
12843 			prog->name, prog->sec_name);
12844 		return -EINVAL;
12845 	}
12846 
12847 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
12848 	if (n < 1) {
12849 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
12850 		return -EINVAL;
12851 	}
12852 
12853 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
12854 	free(pattern);
12855 	return libbpf_get_error(*link);
12856 }
12857 
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)12858 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12859 					  const char *binary_path, size_t offset)
12860 {
12861 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12862 			      retprobe ? 'r' : 'p',
12863 			      retprobe ? "uretprobes" : "uprobes",
12864 			      probe_name, binary_path, offset);
12865 }
12866 
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)12867 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12868 {
12869 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12870 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12871 }
12872 
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)12873 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12874 {
12875 	char file[512];
12876 
12877 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12878 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12879 
12880 	return parse_uint_from_file(file, "%d\n");
12881 }
12882 
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)12883 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12884 					 const char *binary_path, size_t offset, int pid)
12885 {
12886 	const size_t attr_sz = sizeof(struct perf_event_attr);
12887 	struct perf_event_attr attr;
12888 	int type, pfd, err;
12889 
12890 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12891 	if (err < 0) {
12892 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12893 			binary_path, (size_t)offset, errstr(err));
12894 		return err;
12895 	}
12896 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12897 	if (type < 0) {
12898 		err = type;
12899 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12900 			binary_path, offset, errstr(err));
12901 		goto err_clean_legacy;
12902 	}
12903 
12904 	memset(&attr, 0, attr_sz);
12905 	attr.size = attr_sz;
12906 	attr.config = type;
12907 	attr.type = PERF_TYPE_TRACEPOINT;
12908 
12909 	pfd = syscall(__NR_perf_event_open, &attr,
12910 		      pid < 0 ? -1 : pid, /* pid */
12911 		      pid == -1 ? 0 : -1, /* cpu */
12912 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12913 	if (pfd < 0) {
12914 		err = -errno;
12915 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12916 		goto err_clean_legacy;
12917 	}
12918 	return pfd;
12919 
12920 err_clean_legacy:
12921 	/* Clear the newly added legacy uprobe_event */
12922 	remove_uprobe_event_legacy(probe_name, retprobe);
12923 	return err;
12924 }
12925 
12926 /* Find offset of function name in archive specified by path. Currently
12927  * supported are .zip files that do not compress their contents, as used on
12928  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12929  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12930  * library functions.
12931  *
12932  * An overview of the APK format specifically provided here:
12933  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12934  */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)12935 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12936 					      const char *func_name)
12937 {
12938 	struct zip_archive *archive;
12939 	struct zip_entry entry;
12940 	long ret;
12941 	Elf *elf;
12942 
12943 	archive = zip_archive_open(archive_path);
12944 	if (IS_ERR(archive)) {
12945 		ret = PTR_ERR(archive);
12946 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12947 		return ret;
12948 	}
12949 
12950 	ret = zip_archive_find_entry(archive, file_name, &entry);
12951 	if (ret) {
12952 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12953 			archive_path, ret);
12954 		goto out;
12955 	}
12956 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12957 		 (unsigned long)entry.data_offset);
12958 
12959 	if (entry.compression) {
12960 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12961 			archive_path);
12962 		ret = -LIBBPF_ERRNO__FORMAT;
12963 		goto out;
12964 	}
12965 
12966 	elf = elf_memory((void *)entry.data, entry.data_length);
12967 	if (!elf) {
12968 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12969 			elf_errmsg(-1));
12970 		ret = -LIBBPF_ERRNO__LIBELF;
12971 		goto out;
12972 	}
12973 
12974 	ret = elf_find_func_offset(elf, file_name, func_name);
12975 	if (ret > 0) {
12976 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12977 			 func_name, file_name, archive_path, entry.data_offset, (unsigned long)ret,
12978 			 (unsigned long)(ret + entry.data_offset));
12979 		ret += entry.data_offset;
12980 	}
12981 	elf_end(elf);
12982 
12983 out:
12984 	zip_archive_close(archive);
12985 	return ret;
12986 }
12987 
arch_specific_lib_paths(void)12988 static const char *arch_specific_lib_paths(void)
12989 {
12990 	/*
12991 	 * Based on https://packages.debian.org/sid/libc6.
12992 	 *
12993 	 * Assume that the traced program is built for the same architecture
12994 	 * as libbpf, which should cover the vast majority of cases.
12995 	 */
12996 #if defined(__x86_64__)
12997 	return "/lib/x86_64-linux-gnu";
12998 #elif defined(__i386__)
12999 	return "/lib/i386-linux-gnu";
13000 #elif defined(__s390x__)
13001 	return "/lib/s390x-linux-gnu";
13002 #elif defined(__arm__) && defined(__SOFTFP__)
13003 	return "/lib/arm-linux-gnueabi";
13004 #elif defined(__arm__) && !defined(__SOFTFP__)
13005 	return "/lib/arm-linux-gnueabihf";
13006 #elif defined(__aarch64__)
13007 	return "/lib/aarch64-linux-gnu";
13008 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
13009 	return "/lib/mips64el-linux-gnuabi64";
13010 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
13011 	return "/lib/mipsel-linux-gnu";
13012 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
13013 	return "/lib/powerpc64le-linux-gnu";
13014 #elif defined(__sparc__) && defined(__arch64__)
13015 	return "/lib/sparc64-linux-gnu";
13016 #elif defined(__riscv) && __riscv_xlen == 64
13017 	return "/lib/riscv64-linux-gnu";
13018 #else
13019 	return NULL;
13020 #endif
13021 }
13022 
13023 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)13024 static int resolve_full_path(const char *file, char *result, size_t result_sz)
13025 {
13026 	const char *search_paths[4] = {};
13027 	int i, perm;
13028 
13029 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
13030 		search_paths[0] = getenv("LD_LIBRARY_PATH");
13031 		search_paths[1] = "/usr/lib64:/usr/lib";
13032 		search_paths[2] = arch_specific_lib_paths();
13033 		search_paths[3] = "/lib64:/lib";
13034 		perm = R_OK;
13035 	} else {
13036 		search_paths[0] = getenv("PATH");
13037 		search_paths[1] = "/usr/bin:/usr/sbin";
13038 		perm = R_OK | X_OK;
13039 	}
13040 
13041 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
13042 		const char *s;
13043 
13044 		if (!search_paths[i])
13045 			continue;
13046 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
13047 			const char *next_path;
13048 			int seg_len;
13049 
13050 			if (s[0] == ':')
13051 				s++;
13052 			next_path = strchr(s, ':');
13053 			seg_len = next_path ? next_path - s : strlen(s);
13054 			if (!seg_len)
13055 				continue;
13056 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
13057 			/* ensure it has required permissions */
13058 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
13059 				continue;
13060 			pr_debug("resolved '%s' to '%s'\n", file, result);
13061 			return 0;
13062 		}
13063 	}
13064 	return -ENOENT;
13065 }
13066 
13067 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)13068 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
13069 				 pid_t pid,
13070 				 const char *path,
13071 				 const char *func_pattern,
13072 				 const struct bpf_uprobe_multi_opts *opts)
13073 {
13074 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
13075 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13076 	unsigned long *resolved_offsets = NULL;
13077 	enum bpf_attach_type attach_type;
13078 	int err = 0, link_fd, prog_fd;
13079 	struct bpf_link *link = NULL;
13080 	char full_path[PATH_MAX];
13081 	bool retprobe, session;
13082 	const __u64 *cookies;
13083 	const char **syms;
13084 	size_t cnt;
13085 
13086 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
13087 		return libbpf_err_ptr(-EINVAL);
13088 
13089 	prog_fd = bpf_program__fd(prog);
13090 	if (prog_fd < 0) {
13091 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13092 			prog->name);
13093 		return libbpf_err_ptr(-EINVAL);
13094 	}
13095 
13096 	syms = OPTS_GET(opts, syms, NULL);
13097 	offsets = OPTS_GET(opts, offsets, NULL);
13098 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
13099 	cookies = OPTS_GET(opts, cookies, NULL);
13100 	cnt = OPTS_GET(opts, cnt, 0);
13101 	retprobe = OPTS_GET(opts, retprobe, false);
13102 	session  = OPTS_GET(opts, session, false);
13103 
13104 	/*
13105 	 * User can specify 2 mutually exclusive set of inputs:
13106 	 *
13107 	 * 1) use only path/func_pattern/pid arguments
13108 	 *
13109 	 * 2) use path/pid with allowed combinations of:
13110 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
13111 	 *
13112 	 *    - syms and offsets are mutually exclusive
13113 	 *    - ref_ctr_offsets and cookies are optional
13114 	 *
13115 	 * Any other usage results in error.
13116 	 */
13117 
13118 	if (!path)
13119 		return libbpf_err_ptr(-EINVAL);
13120 	if (!func_pattern && cnt == 0)
13121 		return libbpf_err_ptr(-EINVAL);
13122 
13123 	if (func_pattern) {
13124 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
13125 			return libbpf_err_ptr(-EINVAL);
13126 	} else {
13127 		if (!!syms == !!offsets)
13128 			return libbpf_err_ptr(-EINVAL);
13129 	}
13130 
13131 	if (retprobe && session)
13132 		return libbpf_err_ptr(-EINVAL);
13133 
13134 	if (func_pattern) {
13135 		if (!strchr(path, '/')) {
13136 			err = resolve_full_path(path, full_path, sizeof(full_path));
13137 			if (err) {
13138 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13139 					prog->name, path, errstr(err));
13140 				return libbpf_err_ptr(err);
13141 			}
13142 			path = full_path;
13143 		}
13144 
13145 		err = elf_resolve_pattern_offsets(path, func_pattern,
13146 						  &resolved_offsets, &cnt);
13147 		if (err < 0)
13148 			return libbpf_err_ptr(err);
13149 		offsets = resolved_offsets;
13150 	} else if (syms) {
13151 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
13152 		if (err < 0)
13153 			return libbpf_err_ptr(err);
13154 		offsets = resolved_offsets;
13155 	}
13156 
13157 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
13158 
13159 	lopts.uprobe_multi.path = path;
13160 	lopts.uprobe_multi.offsets = offsets;
13161 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
13162 	lopts.uprobe_multi.cookies = cookies;
13163 	lopts.uprobe_multi.cnt = cnt;
13164 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
13165 
13166 	if (pid == 0)
13167 		pid = getpid();
13168 	if (pid > 0)
13169 		lopts.uprobe_multi.pid = pid;
13170 
13171 	link = calloc(1, sizeof(*link));
13172 	if (!link) {
13173 		err = -ENOMEM;
13174 		goto error;
13175 	}
13176 	link->detach = &bpf_link__detach_fd;
13177 
13178 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13179 	if (link_fd < 0) {
13180 		err = -errno;
13181 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
13182 			prog->name, errstr(err));
13183 		goto error;
13184 	}
13185 	link->fd = link_fd;
13186 	free(resolved_offsets);
13187 	return link;
13188 
13189 error:
13190 	free(resolved_offsets);
13191 	free(link);
13192 	return libbpf_err_ptr(err);
13193 }
13194 
13195 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)13196 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
13197 				const char *binary_path, size_t func_offset,
13198 				const struct bpf_uprobe_opts *opts)
13199 {
13200 	const char *archive_path = NULL, *archive_sep = NULL;
13201 	char *legacy_probe = NULL;
13202 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13203 	enum probe_attach_mode attach_mode;
13204 	char full_path[PATH_MAX];
13205 	struct bpf_link *link;
13206 	size_t ref_ctr_off;
13207 	int pfd, err;
13208 	bool retprobe, legacy;
13209 	const char *func_name;
13210 
13211 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13212 		return libbpf_err_ptr(-EINVAL);
13213 
13214 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
13215 	retprobe = OPTS_GET(opts, retprobe, false);
13216 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
13217 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13218 
13219 	if (!binary_path)
13220 		return libbpf_err_ptr(-EINVAL);
13221 
13222 	/* Check if "binary_path" refers to an archive. */
13223 	archive_sep = strstr(binary_path, "!/");
13224 	if (archive_sep) {
13225 		full_path[0] = '\0';
13226 		libbpf_strlcpy(full_path, binary_path,
13227 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
13228 		archive_path = full_path;
13229 		binary_path = archive_sep + 2;
13230 	} else if (!strchr(binary_path, '/')) {
13231 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
13232 		if (err) {
13233 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13234 				prog->name, binary_path, errstr(err));
13235 			return libbpf_err_ptr(err);
13236 		}
13237 		binary_path = full_path;
13238 	}
13239 	func_name = OPTS_GET(opts, func_name, NULL);
13240 	if (func_name) {
13241 		long sym_off;
13242 
13243 		if (archive_path) {
13244 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
13245 								    func_name);
13246 			binary_path = archive_path;
13247 		} else {
13248 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
13249 		}
13250 		if (sym_off < 0)
13251 			return libbpf_err_ptr(sym_off);
13252 		func_offset += sym_off;
13253 	}
13254 
13255 	legacy = determine_uprobe_perf_type() < 0;
13256 	switch (attach_mode) {
13257 	case PROBE_ATTACH_MODE_LEGACY:
13258 		legacy = true;
13259 		pe_opts.force_ioctl_attach = true;
13260 		break;
13261 	case PROBE_ATTACH_MODE_PERF:
13262 		if (legacy)
13263 			return libbpf_err_ptr(-ENOTSUP);
13264 		pe_opts.force_ioctl_attach = true;
13265 		break;
13266 	case PROBE_ATTACH_MODE_LINK:
13267 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
13268 			return libbpf_err_ptr(-ENOTSUP);
13269 		break;
13270 	case PROBE_ATTACH_MODE_DEFAULT:
13271 		break;
13272 	default:
13273 		return libbpf_err_ptr(-EINVAL);
13274 	}
13275 
13276 	if (!legacy) {
13277 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
13278 					    func_offset, pid, ref_ctr_off);
13279 	} else {
13280 		char probe_name[MAX_EVENT_NAME_LEN];
13281 
13282 		if (ref_ctr_off)
13283 			return libbpf_err_ptr(-EINVAL);
13284 
13285 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
13286 					    strrchr(binary_path, '/') ? : binary_path,
13287 					    func_offset);
13288 
13289 		legacy_probe = strdup(probe_name);
13290 		if (!legacy_probe)
13291 			return libbpf_err_ptr(-ENOMEM);
13292 
13293 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
13294 						    binary_path, func_offset, pid);
13295 	}
13296 	if (pfd < 0) {
13297 		err = pfd;
13298 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
13299 			prog->name, retprobe ? "uretprobe" : "uprobe",
13300 			binary_path, func_offset,
13301 			errstr(err));
13302 		goto err_out;
13303 	}
13304 
13305 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13306 	err = libbpf_get_error(link);
13307 	if (err) {
13308 		close(pfd);
13309 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
13310 			prog->name, retprobe ? "uretprobe" : "uprobe",
13311 			binary_path, func_offset,
13312 			errstr(err));
13313 		goto err_clean_legacy;
13314 	}
13315 	if (legacy) {
13316 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
13317 
13318 		perf_link->legacy_probe_name = legacy_probe;
13319 		perf_link->legacy_is_kprobe = false;
13320 		perf_link->legacy_is_retprobe = retprobe;
13321 	}
13322 	return link;
13323 
13324 err_clean_legacy:
13325 	if (legacy)
13326 		remove_uprobe_event_legacy(legacy_probe, retprobe);
13327 err_out:
13328 	free(legacy_probe);
13329 	return libbpf_err_ptr(err);
13330 }
13331 
13332 /* Format of u[ret]probe section definition supporting auto-attach:
13333  * u[ret]probe/binary:function[+offset]
13334  *
13335  * binary can be an absolute/relative path or a filename; the latter is resolved to a
13336  * full binary path via bpf_program__attach_uprobe_opts.
13337  *
13338  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
13339  * specified (and auto-attach is not possible) or the above format is specified for
13340  * auto-attach.
13341  */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13342 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13343 {
13344 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
13345 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
13346 	int n, c, ret = -EINVAL;
13347 	long offset = 0;
13348 
13349 	*link = NULL;
13350 
13351 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13352 		   &probe_type, &binary_path, &func_name);
13353 	switch (n) {
13354 	case 1:
13355 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13356 		ret = 0;
13357 		break;
13358 	case 2:
13359 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
13360 			prog->name, prog->sec_name);
13361 		break;
13362 	case 3:
13363 		/* check if user specifies `+offset`, if yes, this should be
13364 		 * the last part of the string, make sure sscanf read to EOL
13365 		 */
13366 		func_off = strrchr(func_name, '+');
13367 		if (func_off) {
13368 			n = sscanf(func_off, "+%li%n", &offset, &c);
13369 			if (n == 1 && *(func_off + c) == '\0')
13370 				func_off[0] = '\0';
13371 			else
13372 				offset = 0;
13373 		}
13374 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
13375 				strcmp(probe_type, "uretprobe.s") == 0;
13376 		if (opts.retprobe && offset != 0) {
13377 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
13378 				prog->name);
13379 			break;
13380 		}
13381 		opts.func_name = func_name;
13382 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
13383 		ret = libbpf_get_error(*link);
13384 		break;
13385 	default:
13386 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13387 			prog->sec_name);
13388 		break;
13389 	}
13390 	free(probe_type);
13391 	free(binary_path);
13392 	free(func_name);
13393 
13394 	return ret;
13395 }
13396 
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)13397 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
13398 					    bool retprobe, pid_t pid,
13399 					    const char *binary_path,
13400 					    size_t func_offset)
13401 {
13402 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
13403 
13404 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
13405 }
13406 
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)13407 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
13408 					  pid_t pid, const char *binary_path,
13409 					  const char *usdt_provider, const char *usdt_name,
13410 					  const struct bpf_usdt_opts *opts)
13411 {
13412 	char resolved_path[512];
13413 	struct bpf_object *obj = prog->obj;
13414 	struct bpf_link *link;
13415 	__u64 usdt_cookie;
13416 	int err;
13417 
13418 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13419 		return libbpf_err_ptr(-EINVAL);
13420 
13421 	if (bpf_program__fd(prog) < 0) {
13422 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13423 			prog->name);
13424 		return libbpf_err_ptr(-EINVAL);
13425 	}
13426 
13427 	if (!binary_path)
13428 		return libbpf_err_ptr(-EINVAL);
13429 
13430 	if (!strchr(binary_path, '/')) {
13431 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
13432 		if (err) {
13433 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13434 				prog->name, binary_path, errstr(err));
13435 			return libbpf_err_ptr(err);
13436 		}
13437 		binary_path = resolved_path;
13438 	}
13439 
13440 	/* USDT manager is instantiated lazily on first USDT attach. It will
13441 	 * be destroyed together with BPF object in bpf_object__close().
13442 	 */
13443 	if (IS_ERR(obj->usdt_man))
13444 		return libbpf_ptr(obj->usdt_man);
13445 	if (!obj->usdt_man) {
13446 		obj->usdt_man = usdt_manager_new(obj);
13447 		if (IS_ERR(obj->usdt_man))
13448 			return libbpf_ptr(obj->usdt_man);
13449 	}
13450 
13451 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
13452 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
13453 					usdt_provider, usdt_name, usdt_cookie);
13454 	err = libbpf_get_error(link);
13455 	if (err)
13456 		return libbpf_err_ptr(err);
13457 	return link;
13458 }
13459 
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13460 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13461 {
13462 	char *path = NULL, *provider = NULL, *name = NULL;
13463 	const char *sec_name;
13464 	int n, err;
13465 
13466 	sec_name = bpf_program__section_name(prog);
13467 	if (strcmp(sec_name, "usdt") == 0) {
13468 		/* no auto-attach for just SEC("usdt") */
13469 		*link = NULL;
13470 		return 0;
13471 	}
13472 
13473 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
13474 	if (n != 3) {
13475 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
13476 			sec_name);
13477 		err = -EINVAL;
13478 	} else {
13479 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
13480 						 provider, name, NULL);
13481 		err = libbpf_get_error(*link);
13482 	}
13483 	free(path);
13484 	free(provider);
13485 	free(name);
13486 	return err;
13487 }
13488 
determine_tracepoint_id(const char * tp_category,const char * tp_name)13489 static int determine_tracepoint_id(const char *tp_category,
13490 				   const char *tp_name)
13491 {
13492 	char file[PATH_MAX];
13493 	int ret;
13494 
13495 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13496 		       tracefs_path(), tp_category, tp_name);
13497 	if (ret < 0)
13498 		return -errno;
13499 	if (ret >= sizeof(file)) {
13500 		pr_debug("tracepoint %s/%s path is too long\n",
13501 			 tp_category, tp_name);
13502 		return -E2BIG;
13503 	}
13504 	return parse_uint_from_file(file, "%d\n");
13505 }
13506 
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)13507 static int perf_event_open_tracepoint(const char *tp_category,
13508 				      const char *tp_name)
13509 {
13510 	const size_t attr_sz = sizeof(struct perf_event_attr);
13511 	struct perf_event_attr attr;
13512 	int tp_id, pfd, err;
13513 
13514 	tp_id = determine_tracepoint_id(tp_category, tp_name);
13515 	if (tp_id < 0) {
13516 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
13517 			tp_category, tp_name,
13518 			errstr(tp_id));
13519 		return tp_id;
13520 	}
13521 
13522 	memset(&attr, 0, attr_sz);
13523 	attr.type = PERF_TYPE_TRACEPOINT;
13524 	attr.size = attr_sz;
13525 	attr.config = tp_id;
13526 
13527 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
13528 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
13529 	if (pfd < 0) {
13530 		err = -errno;
13531 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
13532 			tp_category, tp_name,
13533 			errstr(err));
13534 		return err;
13535 	}
13536 	return pfd;
13537 }
13538 
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)13539 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
13540 						     const char *tp_category,
13541 						     const char *tp_name,
13542 						     const struct bpf_tracepoint_opts *opts)
13543 {
13544 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13545 	struct bpf_link *link;
13546 	int pfd, err;
13547 
13548 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
13549 		return libbpf_err_ptr(-EINVAL);
13550 
13551 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13552 
13553 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
13554 	if (pfd < 0) {
13555 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
13556 			prog->name, tp_category, tp_name,
13557 			errstr(pfd));
13558 		return libbpf_err_ptr(pfd);
13559 	}
13560 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13561 	err = libbpf_get_error(link);
13562 	if (err) {
13563 		close(pfd);
13564 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
13565 			prog->name, tp_category, tp_name,
13566 			errstr(err));
13567 		return libbpf_err_ptr(err);
13568 	}
13569 	return link;
13570 }
13571 
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)13572 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
13573 						const char *tp_category,
13574 						const char *tp_name)
13575 {
13576 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
13577 }
13578 
13579 /*
13580  * Match section name against a prefix array. Returns pointer past
13581  * "prefix/" on match, empty string for bare sections (exact prefix
13582  * match), or NULL if no prefix matches.
13583  */
sec_name_match_prefix(const char * sec_name,const char * const * prefixes,size_t n)13584 static const char *sec_name_match_prefix(const char *sec_name,
13585 					 const char *const *prefixes,
13586 					 size_t n)
13587 {
13588 	size_t i;
13589 
13590 	for (i = 0; i < n; i++) {
13591 		size_t pfx_len;
13592 
13593 		if (!str_has_pfx(sec_name, prefixes[i]))
13594 			continue;
13595 
13596 		pfx_len = strlen(prefixes[i]);
13597 		if (sec_name[pfx_len] == '\0')
13598 			return sec_name + pfx_len;
13599 
13600 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
13601 			continue;
13602 
13603 		return sec_name + pfx_len + 1;
13604 	}
13605 	return NULL;
13606 }
13607 
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13608 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13609 {
13610 	static const char *const prefixes[] = {
13611 		"tp.s",
13612 		"tp",
13613 		"tracepoint.s",
13614 		"tracepoint",
13615 	};
13616 	char *sec_name, *tp_cat, *tp_name;
13617 	const char *match;
13618 
13619 	*link = NULL;
13620 
13621 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13622 	if (!match) {
13623 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13624 		return -EINVAL;
13625 	}
13626 	if (!match[0]) /* bare section name no autoattach */
13627 		return 0;
13628 
13629 	sec_name = strdup(prog->sec_name);
13630 	if (!sec_name)
13631 		return -ENOMEM;
13632 
13633 	tp_cat = sec_name + (match - prog->sec_name);
13634 	tp_name = strchr(tp_cat, '/');
13635 	if (!tp_name) {
13636 		free(sec_name);
13637 		return -EINVAL;
13638 	}
13639 	*tp_name = '\0';
13640 	tp_name++;
13641 
13642 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
13643 	free(sec_name);
13644 	return libbpf_get_error(*link);
13645 }
13646 
13647 struct bpf_link *
bpf_program__attach_raw_tracepoint_opts(const struct bpf_program * prog,const char * tp_name,struct bpf_raw_tracepoint_opts * opts)13648 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
13649 					const char *tp_name,
13650 					struct bpf_raw_tracepoint_opts *opts)
13651 {
13652 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
13653 	struct bpf_link *link;
13654 	int prog_fd, pfd;
13655 
13656 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
13657 		return libbpf_err_ptr(-EINVAL);
13658 
13659 	prog_fd = bpf_program__fd(prog);
13660 	if (prog_fd < 0) {
13661 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13662 		return libbpf_err_ptr(-EINVAL);
13663 	}
13664 
13665 	link = calloc(1, sizeof(*link));
13666 	if (!link)
13667 		return libbpf_err_ptr(-ENOMEM);
13668 	link->detach = &bpf_link__detach_fd;
13669 
13670 	raw_opts.tp_name = tp_name;
13671 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13672 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13673 	if (pfd < 0) {
13674 		pfd = -errno;
13675 		free(link);
13676 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13677 			prog->name, tp_name, errstr(pfd));
13678 		return libbpf_err_ptr(pfd);
13679 	}
13680 	link->fd = pfd;
13681 	return link;
13682 }
13683 
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)13684 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13685 						    const char *tp_name)
13686 {
13687 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13688 }
13689 
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13690 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13691 {
13692 	static const char *const prefixes[] = {
13693 		"raw_tp",
13694 		"raw_tracepoint",
13695 		"raw_tp.w",
13696 		"raw_tracepoint.w",
13697 		"raw_tp.s",
13698 		"raw_tracepoint.s",
13699 	};
13700 	const char *match;
13701 
13702 	*link = NULL;
13703 
13704 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13705 	if (!match) {
13706 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13707 		return -EINVAL;
13708 	}
13709 	if (!match[0])
13710 		return 0;
13711 
13712 	*link = bpf_program__attach_raw_tracepoint(prog, match);
13713 	return libbpf_get_error(*link);
13714 }
13715 
13716 /* 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)13717 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13718 						   const struct bpf_trace_opts *opts)
13719 {
13720 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13721 	struct bpf_link *link;
13722 	int prog_fd, pfd;
13723 
13724 	if (!OPTS_VALID(opts, bpf_trace_opts))
13725 		return libbpf_err_ptr(-EINVAL);
13726 
13727 	prog_fd = bpf_program__fd(prog);
13728 	if (prog_fd < 0) {
13729 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13730 		return libbpf_err_ptr(-EINVAL);
13731 	}
13732 
13733 	link = calloc(1, sizeof(*link));
13734 	if (!link)
13735 		return libbpf_err_ptr(-ENOMEM);
13736 	link->detach = &bpf_link__detach_fd;
13737 
13738 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13739 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13740 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13741 	if (pfd < 0) {
13742 		pfd = -errno;
13743 		free(link);
13744 		pr_warn("prog '%s': failed to attach: %s\n",
13745 			prog->name, errstr(pfd));
13746 		return libbpf_err_ptr(pfd);
13747 	}
13748 	link->fd = pfd;
13749 	return link;
13750 }
13751 
bpf_program__attach_trace(const struct bpf_program * prog)13752 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13753 {
13754 	return bpf_program__attach_btf_id(prog, NULL);
13755 }
13756 
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)13757 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13758 						const struct bpf_trace_opts *opts)
13759 {
13760 	return bpf_program__attach_btf_id(prog, opts);
13761 }
13762 
bpf_program__attach_lsm(const struct bpf_program * prog)13763 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13764 {
13765 	return bpf_program__attach_btf_id(prog, NULL);
13766 }
13767 
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13768 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13769 {
13770 	*link = bpf_program__attach_trace(prog);
13771 	return libbpf_get_error(*link);
13772 }
13773 
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13774 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13775 {
13776 	*link = bpf_program__attach_lsm(prog);
13777 	return libbpf_get_error(*link);
13778 }
13779 
13780 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)13781 bpf_program_attach_fd(const struct bpf_program *prog,
13782 		      int target_fd, const char *target_name,
13783 		      const struct bpf_link_create_opts *opts)
13784 {
13785 	enum bpf_attach_type attach_type;
13786 	struct bpf_link *link;
13787 	int prog_fd, link_fd;
13788 
13789 	prog_fd = bpf_program__fd(prog);
13790 	if (prog_fd < 0) {
13791 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13792 		return libbpf_err_ptr(-EINVAL);
13793 	}
13794 
13795 	link = calloc(1, sizeof(*link));
13796 	if (!link)
13797 		return libbpf_err_ptr(-ENOMEM);
13798 	link->detach = &bpf_link__detach_fd;
13799 
13800 	attach_type = bpf_program__expected_attach_type(prog);
13801 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13802 	if (link_fd < 0) {
13803 		link_fd = -errno;
13804 		free(link);
13805 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13806 			prog->name, target_name,
13807 			errstr(link_fd));
13808 		return libbpf_err_ptr(link_fd);
13809 	}
13810 	link->fd = link_fd;
13811 	return link;
13812 }
13813 
13814 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)13815 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13816 {
13817 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13818 }
13819 
13820 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)13821 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13822 {
13823 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13824 }
13825 
13826 struct bpf_link *
bpf_program__attach_sockmap(const struct bpf_program * prog,int map_fd)13827 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13828 {
13829 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13830 }
13831 
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)13832 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13833 {
13834 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13835 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13836 }
13837 
13838 struct bpf_link *
bpf_program__attach_cgroup_opts(const struct bpf_program * prog,int cgroup_fd,const struct bpf_cgroup_opts * opts)13839 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13840 				const struct bpf_cgroup_opts *opts)
13841 {
13842 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13843 	__u32 relative_id;
13844 	int relative_fd;
13845 
13846 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13847 		return libbpf_err_ptr(-EINVAL);
13848 
13849 	relative_id = OPTS_GET(opts, relative_id, 0);
13850 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13851 
13852 	if (relative_fd && relative_id) {
13853 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13854 			prog->name);
13855 		return libbpf_err_ptr(-EINVAL);
13856 	}
13857 
13858 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13859 	link_create_opts.cgroup.relative_fd = relative_fd;
13860 	link_create_opts.cgroup.relative_id = relative_id;
13861 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13862 
13863 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13864 }
13865 
13866 struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)13867 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13868 			const struct bpf_tcx_opts *opts)
13869 {
13870 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13871 	__u32 relative_id;
13872 	int relative_fd;
13873 
13874 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13875 		return libbpf_err_ptr(-EINVAL);
13876 
13877 	relative_id = OPTS_GET(opts, relative_id, 0);
13878 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13879 
13880 	/* validate we don't have unexpected combinations of non-zero fields */
13881 	if (!ifindex) {
13882 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13883 			prog->name);
13884 		return libbpf_err_ptr(-EINVAL);
13885 	}
13886 	if (relative_fd && relative_id) {
13887 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13888 			prog->name);
13889 		return libbpf_err_ptr(-EINVAL);
13890 	}
13891 
13892 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13893 	link_create_opts.tcx.relative_fd = relative_fd;
13894 	link_create_opts.tcx.relative_id = relative_id;
13895 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13896 
13897 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13898 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13899 }
13900 
13901 struct bpf_link *
bpf_program__attach_netkit(const struct bpf_program * prog,int ifindex,const struct bpf_netkit_opts * opts)13902 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13903 			   const struct bpf_netkit_opts *opts)
13904 {
13905 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13906 	__u32 relative_id;
13907 	int relative_fd;
13908 
13909 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13910 		return libbpf_err_ptr(-EINVAL);
13911 
13912 	relative_id = OPTS_GET(opts, relative_id, 0);
13913 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13914 
13915 	/* validate we don't have unexpected combinations of non-zero fields */
13916 	if (!ifindex) {
13917 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13918 			prog->name);
13919 		return libbpf_err_ptr(-EINVAL);
13920 	}
13921 	if (relative_fd && relative_id) {
13922 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13923 			prog->name);
13924 		return libbpf_err_ptr(-EINVAL);
13925 	}
13926 
13927 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13928 	link_create_opts.netkit.relative_fd = relative_fd;
13929 	link_create_opts.netkit.relative_id = relative_id;
13930 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13931 
13932 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13933 }
13934 
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)13935 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13936 					      int target_fd,
13937 					      const char *attach_func_name)
13938 {
13939 	int btf_id;
13940 
13941 	if (!!target_fd != !!attach_func_name) {
13942 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13943 			prog->name);
13944 		return libbpf_err_ptr(-EINVAL);
13945 	}
13946 
13947 	if (prog->type != BPF_PROG_TYPE_EXT) {
13948 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13949 			prog->name);
13950 		return libbpf_err_ptr(-EINVAL);
13951 	}
13952 
13953 	if (target_fd) {
13954 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13955 
13956 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13957 		if (btf_id < 0)
13958 			return libbpf_err_ptr(btf_id);
13959 
13960 		target_opts.target_btf_id = btf_id;
13961 
13962 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13963 					     &target_opts);
13964 	} else {
13965 		/* no target, so use raw_tracepoint_open for compatibility
13966 		 * with old kernels
13967 		 */
13968 		return bpf_program__attach_trace(prog);
13969 	}
13970 }
13971 
13972 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)13973 bpf_program__attach_iter(const struct bpf_program *prog,
13974 			 const struct bpf_iter_attach_opts *opts)
13975 {
13976 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13977 	struct bpf_link *link;
13978 	int prog_fd, link_fd;
13979 	__u32 target_fd = 0;
13980 
13981 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13982 		return libbpf_err_ptr(-EINVAL);
13983 
13984 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13985 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13986 
13987 	prog_fd = bpf_program__fd(prog);
13988 	if (prog_fd < 0) {
13989 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13990 		return libbpf_err_ptr(-EINVAL);
13991 	}
13992 
13993 	link = calloc(1, sizeof(*link));
13994 	if (!link)
13995 		return libbpf_err_ptr(-ENOMEM);
13996 	link->detach = &bpf_link__detach_fd;
13997 
13998 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13999 				  &link_create_opts);
14000 	if (link_fd < 0) {
14001 		link_fd = -errno;
14002 		free(link);
14003 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
14004 			prog->name, errstr(link_fd));
14005 		return libbpf_err_ptr(link_fd);
14006 	}
14007 	link->fd = link_fd;
14008 	return link;
14009 }
14010 
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)14011 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14012 {
14013 	*link = bpf_program__attach_iter(prog, NULL);
14014 	return libbpf_get_error(*link);
14015 }
14016 
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)14017 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
14018 					       const struct bpf_netfilter_opts *opts)
14019 {
14020 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
14021 	struct bpf_link *link;
14022 	int prog_fd, link_fd;
14023 
14024 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
14025 		return libbpf_err_ptr(-EINVAL);
14026 
14027 	prog_fd = bpf_program__fd(prog);
14028 	if (prog_fd < 0) {
14029 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14030 		return libbpf_err_ptr(-EINVAL);
14031 	}
14032 
14033 	link = calloc(1, sizeof(*link));
14034 	if (!link)
14035 		return libbpf_err_ptr(-ENOMEM);
14036 
14037 	link->detach = &bpf_link__detach_fd;
14038 
14039 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
14040 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
14041 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
14042 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
14043 
14044 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
14045 	if (link_fd < 0) {
14046 		link_fd = -errno;
14047 		free(link);
14048 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
14049 			prog->name, errstr(link_fd));
14050 		return libbpf_err_ptr(link_fd);
14051 	}
14052 	link->fd = link_fd;
14053 
14054 	return link;
14055 }
14056 
bpf_program__attach(const struct bpf_program * prog)14057 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
14058 {
14059 	struct bpf_link *link = NULL;
14060 	int err;
14061 
14062 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14063 		return libbpf_err_ptr(-EOPNOTSUPP);
14064 
14065 	if (bpf_program__fd(prog) < 0) {
14066 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14067 			prog->name);
14068 		return libbpf_err_ptr(-EINVAL);
14069 	}
14070 
14071 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
14072 	if (err)
14073 		return libbpf_err_ptr(err);
14074 
14075 	/* When calling bpf_program__attach() explicitly, auto-attach support
14076 	 * is expected to work, so NULL returned link is considered an error.
14077 	 * This is different for skeleton's attach, see comment in
14078 	 * bpf_object__attach_skeleton().
14079 	 */
14080 	if (!link)
14081 		return libbpf_err_ptr(-EOPNOTSUPP);
14082 
14083 	return link;
14084 }
14085 
14086 struct bpf_link_struct_ops {
14087 	struct bpf_link link;
14088 	int map_fd;
14089 };
14090 
bpf_link__detach_struct_ops(struct bpf_link * link)14091 static int bpf_link__detach_struct_ops(struct bpf_link *link)
14092 {
14093 	struct bpf_link_struct_ops *st_link;
14094 	__u32 zero = 0;
14095 
14096 	st_link = container_of(link, struct bpf_link_struct_ops, link);
14097 
14098 	if (st_link->map_fd < 0)
14099 		/* w/o a real link */
14100 		return bpf_map_delete_elem(link->fd, &zero);
14101 
14102 	return close(link->fd);
14103 }
14104 
bpf_map__attach_struct_ops(const struct bpf_map * map)14105 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
14106 {
14107 	struct bpf_link_struct_ops *link;
14108 	__u32 zero = 0;
14109 	int err, fd;
14110 
14111 	if (!bpf_map__is_struct_ops(map)) {
14112 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14113 		return libbpf_err_ptr(-EINVAL);
14114 	}
14115 
14116 	if (map->fd < 0) {
14117 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14118 		return libbpf_err_ptr(-EINVAL);
14119 	}
14120 
14121 	link = calloc(1, sizeof(*link));
14122 	if (!link)
14123 		return libbpf_err_ptr(-EINVAL);
14124 
14125 	/* kern_vdata should be prepared during the loading phase. */
14126 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14127 	/* It can be EBUSY if the map has been used to create or
14128 	 * update a link before.  We don't allow updating the value of
14129 	 * a struct_ops once it is set.  That ensures that the value
14130 	 * never changed.  So, it is safe to skip EBUSY.
14131 	 */
14132 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
14133 		free(link);
14134 		return libbpf_err_ptr(err);
14135 	}
14136 
14137 	link->link.detach = bpf_link__detach_struct_ops;
14138 
14139 	if (!(map->def.map_flags & BPF_F_LINK)) {
14140 		/* w/o a real link */
14141 		link->link.fd = map->fd;
14142 		link->map_fd = -1;
14143 		return &link->link;
14144 	}
14145 
14146 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
14147 	if (fd < 0) {
14148 		free(link);
14149 		return libbpf_err_ptr(fd);
14150 	}
14151 
14152 	link->link.fd = fd;
14153 	link->map_fd = map->fd;
14154 
14155 	return &link->link;
14156 }
14157 
14158 /*
14159  * Swap the back struct_ops of a link with a new struct_ops map.
14160  */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)14161 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
14162 {
14163 	struct bpf_link_struct_ops *st_ops_link;
14164 	__u32 zero = 0;
14165 	int err;
14166 
14167 	if (!bpf_map__is_struct_ops(map))
14168 		return libbpf_err(-EINVAL);
14169 
14170 	if (map->fd < 0) {
14171 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
14172 		return libbpf_err(-EINVAL);
14173 	}
14174 
14175 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
14176 	/* Ensure the type of a link is correct */
14177 	if (st_ops_link->map_fd < 0)
14178 		return libbpf_err(-EINVAL);
14179 
14180 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14181 	/* It can be EBUSY if the map has been used to create or
14182 	 * update a link before.  We don't allow updating the value of
14183 	 * a struct_ops once it is set.  That ensures that the value
14184 	 * never changed.  So, it is safe to skip EBUSY.
14185 	 */
14186 	if (err && err != -EBUSY)
14187 		return err;
14188 
14189 	err = bpf_link_update(link->fd, map->fd, NULL);
14190 	if (err < 0)
14191 		return err;
14192 
14193 	st_ops_link->map_fd = map->fd;
14194 
14195 	return 0;
14196 }
14197 
14198 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
14199 							  void *private_data);
14200 
14201 static enum bpf_perf_event_ret
perf_event_read_simple(void * mmap_mem,size_t mmap_size,size_t page_size,void ** copy_mem,size_t * copy_size,bpf_perf_event_print_t fn,void * private_data)14202 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
14203 		       void **copy_mem, size_t *copy_size,
14204 		       bpf_perf_event_print_t fn, void *private_data)
14205 {
14206 	struct perf_event_mmap_page *header = mmap_mem;
14207 	__u64 data_head = ring_buffer_read_head(header);
14208 	__u64 data_tail = header->data_tail;
14209 	void *base = ((__u8 *)header) + page_size;
14210 	int ret = LIBBPF_PERF_EVENT_CONT;
14211 	struct perf_event_header *ehdr;
14212 	size_t ehdr_size;
14213 
14214 	while (data_head != data_tail) {
14215 		ehdr = base + (data_tail & (mmap_size - 1));
14216 		ehdr_size = ehdr->size;
14217 
14218 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
14219 			void *copy_start = ehdr;
14220 			size_t len_first = base + mmap_size - copy_start;
14221 			size_t len_second = ehdr_size - len_first;
14222 
14223 			if (*copy_size < ehdr_size) {
14224 				free(*copy_mem);
14225 				*copy_mem = malloc(ehdr_size);
14226 				if (!*copy_mem) {
14227 					*copy_size = 0;
14228 					ret = LIBBPF_PERF_EVENT_ERROR;
14229 					break;
14230 				}
14231 				*copy_size = ehdr_size;
14232 			}
14233 
14234 			memcpy(*copy_mem, copy_start, len_first);
14235 			memcpy(*copy_mem + len_first, base, len_second);
14236 			ehdr = *copy_mem;
14237 		}
14238 
14239 		ret = fn(ehdr, private_data);
14240 		data_tail += ehdr_size;
14241 		if (ret != LIBBPF_PERF_EVENT_CONT)
14242 			break;
14243 	}
14244 
14245 	ring_buffer_write_tail(header, data_tail);
14246 	return libbpf_err(ret);
14247 }
14248 
14249 struct perf_buffer;
14250 
14251 struct perf_buffer_params {
14252 	struct perf_event_attr *attr;
14253 	/* if event_cb is specified, it takes precedence */
14254 	perf_buffer_event_fn event_cb;
14255 	/* sample_cb and lost_cb are higher-level common-case callbacks */
14256 	perf_buffer_sample_fn sample_cb;
14257 	perf_buffer_lost_fn lost_cb;
14258 	void *ctx;
14259 	int cpu_cnt;
14260 	int *cpus;
14261 	int *map_keys;
14262 };
14263 
14264 struct perf_cpu_buf {
14265 	struct perf_buffer *pb;
14266 	void *base; /* mmap()'ed memory */
14267 	void *buf; /* for reconstructing segmented data */
14268 	size_t buf_size;
14269 	int fd;
14270 	int cpu;
14271 	int map_key;
14272 };
14273 
14274 struct perf_buffer {
14275 	perf_buffer_event_fn event_cb;
14276 	perf_buffer_sample_fn sample_cb;
14277 	perf_buffer_lost_fn lost_cb;
14278 	void *ctx; /* passed into callbacks */
14279 
14280 	size_t page_size;
14281 	size_t mmap_size;
14282 	struct perf_cpu_buf **cpu_bufs;
14283 	struct epoll_event *events;
14284 	int cpu_cnt; /* number of allocated CPU buffers */
14285 	int epoll_fd; /* perf event FD */
14286 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
14287 };
14288 
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)14289 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
14290 				      struct perf_cpu_buf *cpu_buf)
14291 {
14292 	if (!cpu_buf)
14293 		return;
14294 	if (cpu_buf->base &&
14295 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
14296 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
14297 	if (cpu_buf->fd >= 0) {
14298 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
14299 		close(cpu_buf->fd);
14300 	}
14301 	free(cpu_buf->buf);
14302 	free(cpu_buf);
14303 }
14304 
perf_buffer__free(struct perf_buffer * pb)14305 void perf_buffer__free(struct perf_buffer *pb)
14306 {
14307 	int i;
14308 
14309 	if (IS_ERR_OR_NULL(pb))
14310 		return;
14311 	if (pb->cpu_bufs) {
14312 		for (i = 0; i < pb->cpu_cnt; i++) {
14313 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14314 
14315 			if (!cpu_buf)
14316 				continue;
14317 
14318 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
14319 			perf_buffer__free_cpu_buf(pb, cpu_buf);
14320 		}
14321 		free(pb->cpu_bufs);
14322 	}
14323 	if (pb->epoll_fd >= 0)
14324 		close(pb->epoll_fd);
14325 	free(pb->events);
14326 	free(pb);
14327 }
14328 
14329 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)14330 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
14331 			  int cpu, int map_key)
14332 {
14333 	struct perf_cpu_buf *cpu_buf;
14334 	int err;
14335 
14336 	cpu_buf = calloc(1, sizeof(*cpu_buf));
14337 	if (!cpu_buf)
14338 		return ERR_PTR(-ENOMEM);
14339 
14340 	cpu_buf->pb = pb;
14341 	cpu_buf->cpu = cpu;
14342 	cpu_buf->map_key = map_key;
14343 
14344 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
14345 			      -1, PERF_FLAG_FD_CLOEXEC);
14346 	if (cpu_buf->fd < 0) {
14347 		err = -errno;
14348 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
14349 			cpu, errstr(err));
14350 		goto error;
14351 	}
14352 
14353 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
14354 			     PROT_READ | PROT_WRITE, MAP_SHARED,
14355 			     cpu_buf->fd, 0);
14356 	if (cpu_buf->base == MAP_FAILED) {
14357 		cpu_buf->base = NULL;
14358 		err = -errno;
14359 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
14360 			cpu, errstr(err));
14361 		goto error;
14362 	}
14363 
14364 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
14365 		err = -errno;
14366 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
14367 			cpu, errstr(err));
14368 		goto error;
14369 	}
14370 
14371 	return cpu_buf;
14372 
14373 error:
14374 	perf_buffer__free_cpu_buf(pb, cpu_buf);
14375 	return (struct perf_cpu_buf *)ERR_PTR(err);
14376 }
14377 
14378 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14379 					      struct perf_buffer_params *p);
14380 
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)14381 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
14382 				     perf_buffer_sample_fn sample_cb,
14383 				     perf_buffer_lost_fn lost_cb,
14384 				     void *ctx,
14385 				     const struct perf_buffer_opts *opts)
14386 {
14387 	const size_t attr_sz = sizeof(struct perf_event_attr);
14388 	struct perf_buffer_params p = {};
14389 	struct perf_event_attr attr;
14390 	__u32 sample_period;
14391 
14392 	if (!OPTS_VALID(opts, perf_buffer_opts))
14393 		return libbpf_err_ptr(-EINVAL);
14394 
14395 	sample_period = OPTS_GET(opts, sample_period, 1);
14396 	if (!sample_period)
14397 		sample_period = 1;
14398 
14399 	memset(&attr, 0, attr_sz);
14400 	attr.size = attr_sz;
14401 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
14402 	attr.type = PERF_TYPE_SOFTWARE;
14403 	attr.sample_type = PERF_SAMPLE_RAW;
14404 	attr.wakeup_events = sample_period;
14405 
14406 	p.attr = &attr;
14407 	p.sample_cb = sample_cb;
14408 	p.lost_cb = lost_cb;
14409 	p.ctx = ctx;
14410 
14411 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14412 }
14413 
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)14414 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
14415 					 struct perf_event_attr *attr,
14416 					 perf_buffer_event_fn event_cb, void *ctx,
14417 					 const struct perf_buffer_raw_opts *opts)
14418 {
14419 	struct perf_buffer_params p = {};
14420 
14421 	if (!attr)
14422 		return libbpf_err_ptr(-EINVAL);
14423 
14424 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
14425 		return libbpf_err_ptr(-EINVAL);
14426 
14427 	p.attr = attr;
14428 	p.event_cb = event_cb;
14429 	p.ctx = ctx;
14430 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
14431 	p.cpus = OPTS_GET(opts, cpus, NULL);
14432 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
14433 
14434 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14435 }
14436 
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)14437 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14438 					      struct perf_buffer_params *p)
14439 {
14440 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
14441 	struct bpf_map_info map;
14442 	struct perf_buffer *pb;
14443 	bool *online = NULL;
14444 	__u32 map_info_len;
14445 	int err, i, j, n;
14446 
14447 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
14448 		pr_warn("page count should be power of two, but is %zu\n",
14449 			page_cnt);
14450 		return ERR_PTR(-EINVAL);
14451 	}
14452 
14453 	/* best-effort sanity checks */
14454 	memset(&map, 0, sizeof(map));
14455 	map_info_len = sizeof(map);
14456 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
14457 	if (err) {
14458 		err = -errno;
14459 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
14460 		 * -EBADFD, -EFAULT, or -E2BIG on real error
14461 		 */
14462 		if (err != -EINVAL) {
14463 			pr_warn("failed to get map info for map FD %d: %s\n",
14464 				map_fd, errstr(err));
14465 			return ERR_PTR(err);
14466 		}
14467 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
14468 			 map_fd);
14469 	} else {
14470 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
14471 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
14472 				map.name);
14473 			return ERR_PTR(-EINVAL);
14474 		}
14475 	}
14476 
14477 	pb = calloc(1, sizeof(*pb));
14478 	if (!pb)
14479 		return ERR_PTR(-ENOMEM);
14480 
14481 	pb->event_cb = p->event_cb;
14482 	pb->sample_cb = p->sample_cb;
14483 	pb->lost_cb = p->lost_cb;
14484 	pb->ctx = p->ctx;
14485 
14486 	pb->page_size = getpagesize();
14487 	pb->mmap_size = pb->page_size * page_cnt;
14488 	pb->map_fd = map_fd;
14489 
14490 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
14491 	if (pb->epoll_fd < 0) {
14492 		err = -errno;
14493 		pr_warn("failed to create epoll instance: %s\n",
14494 			errstr(err));
14495 		goto error;
14496 	}
14497 
14498 	if (p->cpu_cnt > 0) {
14499 		pb->cpu_cnt = p->cpu_cnt;
14500 	} else {
14501 		pb->cpu_cnt = libbpf_num_possible_cpus();
14502 		if (pb->cpu_cnt < 0) {
14503 			err = pb->cpu_cnt;
14504 			goto error;
14505 		}
14506 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
14507 			pb->cpu_cnt = map.max_entries;
14508 	}
14509 
14510 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
14511 	if (!pb->events) {
14512 		err = -ENOMEM;
14513 		pr_warn("failed to allocate events: out of memory\n");
14514 		goto error;
14515 	}
14516 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
14517 	if (!pb->cpu_bufs) {
14518 		err = -ENOMEM;
14519 		pr_warn("failed to allocate buffers: out of memory\n");
14520 		goto error;
14521 	}
14522 
14523 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
14524 	if (err) {
14525 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
14526 		goto error;
14527 	}
14528 
14529 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
14530 		struct perf_cpu_buf *cpu_buf;
14531 		int cpu, map_key;
14532 
14533 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
14534 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
14535 
14536 		/* in case user didn't explicitly requested particular CPUs to
14537 		 * be attached to, skip offline/not present CPUs
14538 		 */
14539 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
14540 			continue;
14541 
14542 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
14543 		if (IS_ERR(cpu_buf)) {
14544 			err = PTR_ERR(cpu_buf);
14545 			goto error;
14546 		}
14547 
14548 		pb->cpu_bufs[j] = cpu_buf;
14549 
14550 		err = bpf_map_update_elem(pb->map_fd, &map_key,
14551 					  &cpu_buf->fd, 0);
14552 		if (err) {
14553 			err = -errno;
14554 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
14555 				cpu, map_key, cpu_buf->fd,
14556 				errstr(err));
14557 			goto error;
14558 		}
14559 
14560 		pb->events[j].events = EPOLLIN;
14561 		pb->events[j].data.ptr = cpu_buf;
14562 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
14563 			      &pb->events[j]) < 0) {
14564 			err = -errno;
14565 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
14566 				cpu, cpu_buf->fd,
14567 				errstr(err));
14568 			goto error;
14569 		}
14570 		j++;
14571 	}
14572 	pb->cpu_cnt = j;
14573 	free(online);
14574 
14575 	return pb;
14576 
14577 error:
14578 	free(online);
14579 	if (pb)
14580 		perf_buffer__free(pb);
14581 	return ERR_PTR(err);
14582 }
14583 
14584 struct perf_sample_raw {
14585 	struct perf_event_header header;
14586 	uint32_t size;
14587 	char data[];
14588 };
14589 
14590 struct perf_sample_lost {
14591 	struct perf_event_header header;
14592 	uint64_t id;
14593 	uint64_t lost;
14594 	uint64_t sample_id;
14595 };
14596 
14597 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)14598 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
14599 {
14600 	struct perf_cpu_buf *cpu_buf = ctx;
14601 	struct perf_buffer *pb = cpu_buf->pb;
14602 	void *data = e;
14603 
14604 	/* user wants full control over parsing perf event */
14605 	if (pb->event_cb)
14606 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
14607 
14608 	switch (e->type) {
14609 	case PERF_RECORD_SAMPLE: {
14610 		struct perf_sample_raw *s = data;
14611 
14612 		if (pb->sample_cb)
14613 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
14614 		break;
14615 	}
14616 	case PERF_RECORD_LOST: {
14617 		struct perf_sample_lost *s = data;
14618 
14619 		if (pb->lost_cb)
14620 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
14621 		break;
14622 	}
14623 	default:
14624 		pr_warn("unknown perf sample type %u\n", e->type);
14625 		return LIBBPF_PERF_EVENT_ERROR;
14626 	}
14627 	return LIBBPF_PERF_EVENT_CONT;
14628 }
14629 
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)14630 static int perf_buffer__process_records(struct perf_buffer *pb,
14631 					struct perf_cpu_buf *cpu_buf)
14632 {
14633 	enum bpf_perf_event_ret ret;
14634 
14635 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
14636 				     pb->page_size, &cpu_buf->buf,
14637 				     &cpu_buf->buf_size,
14638 				     perf_buffer__process_record, cpu_buf);
14639 	if (ret != LIBBPF_PERF_EVENT_CONT)
14640 		return ret;
14641 	return 0;
14642 }
14643 
perf_buffer__epoll_fd(const struct perf_buffer * pb)14644 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14645 {
14646 	return pb->epoll_fd;
14647 }
14648 
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)14649 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14650 {
14651 	int i, cnt, err;
14652 
14653 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14654 	if (cnt < 0)
14655 		return -errno;
14656 
14657 	for (i = 0; i < cnt; i++) {
14658 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14659 
14660 		err = perf_buffer__process_records(pb, cpu_buf);
14661 		if (err) {
14662 			pr_warn("error while processing records: %s\n", errstr(err));
14663 			return libbpf_err(err);
14664 		}
14665 	}
14666 	return cnt;
14667 }
14668 
14669 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14670  * manager.
14671  */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)14672 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14673 {
14674 	return pb->cpu_cnt;
14675 }
14676 
14677 /*
14678  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14679  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14680  * select()/poll()/epoll() Linux syscalls.
14681  */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)14682 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14683 {
14684 	struct perf_cpu_buf *cpu_buf;
14685 
14686 	if (buf_idx >= pb->cpu_cnt)
14687 		return libbpf_err(-EINVAL);
14688 
14689 	cpu_buf = pb->cpu_bufs[buf_idx];
14690 	if (!cpu_buf)
14691 		return libbpf_err(-ENOENT);
14692 
14693 	return cpu_buf->fd;
14694 }
14695 
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)14696 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14697 {
14698 	struct perf_cpu_buf *cpu_buf;
14699 
14700 	if (buf_idx >= pb->cpu_cnt)
14701 		return libbpf_err(-EINVAL);
14702 
14703 	cpu_buf = pb->cpu_bufs[buf_idx];
14704 	if (!cpu_buf)
14705 		return libbpf_err(-ENOENT);
14706 
14707 	*buf = cpu_buf->base;
14708 	*buf_size = pb->mmap_size;
14709 	return 0;
14710 }
14711 
14712 /*
14713  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14714  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14715  * consume, do nothing and return success.
14716  * Returns:
14717  *   - 0 on success;
14718  *   - <0 on failure.
14719  */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)14720 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14721 {
14722 	struct perf_cpu_buf *cpu_buf;
14723 
14724 	if (buf_idx >= pb->cpu_cnt)
14725 		return libbpf_err(-EINVAL);
14726 
14727 	cpu_buf = pb->cpu_bufs[buf_idx];
14728 	if (!cpu_buf)
14729 		return libbpf_err(-ENOENT);
14730 
14731 	return perf_buffer__process_records(pb, cpu_buf);
14732 }
14733 
perf_buffer__consume(struct perf_buffer * pb)14734 int perf_buffer__consume(struct perf_buffer *pb)
14735 {
14736 	int i, err;
14737 
14738 	for (i = 0; i < pb->cpu_cnt; i++) {
14739 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14740 
14741 		if (!cpu_buf)
14742 			continue;
14743 
14744 		err = perf_buffer__process_records(pb, cpu_buf);
14745 		if (err) {
14746 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14747 				i, errstr(err));
14748 			return libbpf_err(err);
14749 		}
14750 	}
14751 	return 0;
14752 }
14753 
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)14754 int bpf_program__set_attach_target(struct bpf_program *prog,
14755 				   int attach_prog_fd,
14756 				   const char *attach_func_name)
14757 {
14758 	int btf_obj_fd = 0, btf_id = 0, err;
14759 
14760 	if (!prog || attach_prog_fd < 0)
14761 		return libbpf_err(-EINVAL);
14762 
14763 	if (prog->obj->state >= OBJ_LOADED)
14764 		return libbpf_err(-EINVAL);
14765 
14766 	if (attach_prog_fd && !attach_func_name) {
14767 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14768 		 * the normal object/program load phase.
14769 		 */
14770 		prog->attach_prog_fd = attach_prog_fd;
14771 		return 0;
14772 	}
14773 
14774 	if (attach_prog_fd) {
14775 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14776 						 attach_prog_fd, prog->obj->token_fd);
14777 		if (btf_id < 0)
14778 			return libbpf_err(btf_id);
14779 	} else {
14780 		if (!attach_func_name)
14781 			return libbpf_err(-EINVAL);
14782 
14783 		/* load btf_vmlinux, if not yet */
14784 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14785 		if (err)
14786 			return libbpf_err(err);
14787 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14788 					 prog->expected_attach_type,
14789 					 &btf_obj_fd, &btf_id);
14790 		if (err)
14791 			return libbpf_err(err);
14792 	}
14793 
14794 	prog->attach_btf_id = btf_id;
14795 	prog->attach_btf_obj_fd = btf_obj_fd;
14796 	prog->attach_prog_fd = attach_prog_fd;
14797 	return 0;
14798 }
14799 
bpf_program__assoc_struct_ops(struct bpf_program * prog,struct bpf_map * map,struct bpf_prog_assoc_struct_ops_opts * opts)14800 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14801 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14802 {
14803 	int prog_fd, map_fd;
14804 
14805 	prog_fd = bpf_program__fd(prog);
14806 	if (prog_fd < 0) {
14807 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14808 			prog->name);
14809 		return libbpf_err(-EINVAL);
14810 	}
14811 
14812 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14813 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14814 		return libbpf_err(-EINVAL);
14815 	}
14816 
14817 	map_fd = bpf_map__fd(map);
14818 	if (map_fd < 0) {
14819 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14820 		return libbpf_err(-EINVAL);
14821 	}
14822 
14823 	if (!bpf_map__is_struct_ops(map)) {
14824 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14825 		return libbpf_err(-EINVAL);
14826 	}
14827 
14828 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14829 }
14830 
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)14831 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14832 {
14833 	int err = 0, n, len, start, end = -1;
14834 	bool *tmp;
14835 
14836 	*mask = NULL;
14837 	*mask_sz = 0;
14838 
14839 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14840 	while (*s) {
14841 		if (*s == ',' || *s == '\n') {
14842 			s++;
14843 			continue;
14844 		}
14845 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14846 		if (n <= 0 || n > 2) {
14847 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14848 			err = -EINVAL;
14849 			goto cleanup;
14850 		} else if (n == 1) {
14851 			end = start;
14852 		}
14853 		if (start < 0 || start > end) {
14854 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14855 				start, end, s);
14856 			err = -EINVAL;
14857 			goto cleanup;
14858 		}
14859 		tmp = realloc(*mask, end + 1);
14860 		if (!tmp) {
14861 			err = -ENOMEM;
14862 			goto cleanup;
14863 		}
14864 		*mask = tmp;
14865 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14866 		memset(tmp + start, 1, end - start + 1);
14867 		*mask_sz = end + 1;
14868 		s += len;
14869 	}
14870 	if (!*mask_sz) {
14871 		pr_warn("Empty CPU range\n");
14872 		return -EINVAL;
14873 	}
14874 	return 0;
14875 cleanup:
14876 	free(*mask);
14877 	*mask = NULL;
14878 	return err;
14879 }
14880 
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)14881 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14882 {
14883 	int fd, err = 0, len;
14884 	char buf[128];
14885 
14886 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14887 	if (fd < 0) {
14888 		err = -errno;
14889 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14890 		return err;
14891 	}
14892 	len = read(fd, buf, sizeof(buf));
14893 	close(fd);
14894 	if (len <= 0) {
14895 		err = len ? -errno : -EINVAL;
14896 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14897 		return err;
14898 	}
14899 	if (len >= sizeof(buf)) {
14900 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14901 		return -E2BIG;
14902 	}
14903 	buf[len] = '\0';
14904 
14905 	return parse_cpu_mask_str(buf, mask, mask_sz);
14906 }
14907 
libbpf_num_possible_cpus(void)14908 int libbpf_num_possible_cpus(void)
14909 {
14910 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14911 	static int cpus;
14912 	int err, n, i, tmp_cpus;
14913 	bool *mask;
14914 
14915 	tmp_cpus = READ_ONCE(cpus);
14916 	if (tmp_cpus > 0)
14917 		return tmp_cpus;
14918 
14919 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14920 	if (err)
14921 		return libbpf_err(err);
14922 
14923 	tmp_cpus = 0;
14924 	for (i = 0; i < n; i++) {
14925 		if (mask[i])
14926 			tmp_cpus++;
14927 	}
14928 	free(mask);
14929 
14930 	WRITE_ONCE(cpus, tmp_cpus);
14931 	return tmp_cpus;
14932 }
14933 
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt,size_t map_skel_sz)14934 static int populate_skeleton_maps(const struct bpf_object *obj,
14935 				  struct bpf_map_skeleton *maps,
14936 				  size_t map_cnt, size_t map_skel_sz)
14937 {
14938 	int i;
14939 
14940 	for (i = 0; i < map_cnt; i++) {
14941 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14942 		struct bpf_map **map = map_skel->map;
14943 		const char *name = map_skel->name;
14944 		void **mmaped = map_skel->mmaped;
14945 
14946 		*map = bpf_object__find_map_by_name(obj, name);
14947 		if (!*map) {
14948 			pr_warn("failed to find skeleton map '%s'\n", name);
14949 			return -ESRCH;
14950 		}
14951 
14952 		/* externs shouldn't be pre-setup from user code */
14953 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14954 			*mmaped = (*map)->mmaped;
14955 	}
14956 	return 0;
14957 }
14958 
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt,size_t prog_skel_sz)14959 static int populate_skeleton_progs(const struct bpf_object *obj,
14960 				   struct bpf_prog_skeleton *progs,
14961 				   size_t prog_cnt, size_t prog_skel_sz)
14962 {
14963 	int i;
14964 
14965 	for (i = 0; i < prog_cnt; i++) {
14966 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14967 		struct bpf_program **prog = prog_skel->prog;
14968 		const char *name = prog_skel->name;
14969 
14970 		*prog = bpf_object__find_program_by_name(obj, name);
14971 		if (!*prog) {
14972 			pr_warn("failed to find skeleton program '%s'\n", name);
14973 			return -ESRCH;
14974 		}
14975 	}
14976 	return 0;
14977 }
14978 
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)14979 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14980 			      const struct bpf_object_open_opts *opts)
14981 {
14982 	struct bpf_object *obj;
14983 	int err;
14984 
14985 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14986 	if (IS_ERR(obj)) {
14987 		err = PTR_ERR(obj);
14988 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14989 			s->name, errstr(err));
14990 		return libbpf_err(err);
14991 	}
14992 
14993 	*s->obj = obj;
14994 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14995 	if (err) {
14996 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14997 		return libbpf_err(err);
14998 	}
14999 
15000 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15001 	if (err) {
15002 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
15003 		return libbpf_err(err);
15004 	}
15005 
15006 	return 0;
15007 }
15008 
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)15009 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
15010 {
15011 	int err, len, var_idx, i;
15012 	const char *var_name;
15013 	const struct bpf_map *map;
15014 	struct btf *btf;
15015 	__u32 map_type_id;
15016 	const struct btf_type *map_type, *var_type;
15017 	const struct bpf_var_skeleton *var_skel;
15018 	struct btf_var_secinfo *var;
15019 
15020 	if (!s->obj)
15021 		return libbpf_err(-EINVAL);
15022 
15023 	btf = bpf_object__btf(s->obj);
15024 	if (!btf) {
15025 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
15026 			bpf_object__name(s->obj));
15027 		return libbpf_err(-errno);
15028 	}
15029 
15030 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
15031 	if (err) {
15032 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
15033 		return libbpf_err(err);
15034 	}
15035 
15036 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15037 	if (err) {
15038 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
15039 		return libbpf_err(err);
15040 	}
15041 
15042 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
15043 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
15044 		map = *var_skel->map;
15045 		map_type_id = bpf_map__btf_value_type_id(map);
15046 		map_type = btf__type_by_id(btf, map_type_id);
15047 
15048 		if (!btf_is_datasec(map_type)) {
15049 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
15050 				bpf_map__name(map),
15051 				__btf_kind_str(btf_kind(map_type)));
15052 			return libbpf_err(-EINVAL);
15053 		}
15054 
15055 		len = btf_vlen(map_type);
15056 		var = btf_var_secinfos(map_type);
15057 		for (i = 0; i < len; i++, var++) {
15058 			var_type = btf__type_by_id(btf, var->type);
15059 			var_name = btf__name_by_offset(btf, var_type->name_off);
15060 			if (strcmp(var_name, var_skel->name) == 0) {
15061 				*var_skel->addr = map->mmaped + var->offset;
15062 				break;
15063 			}
15064 		}
15065 	}
15066 	return 0;
15067 }
15068 
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)15069 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
15070 {
15071 	if (!s)
15072 		return;
15073 	free(s->maps);
15074 	free(s->progs);
15075 	free(s->vars);
15076 	free(s);
15077 }
15078 
bpf_object__load_skeleton(struct bpf_object_skeleton * s)15079 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
15080 {
15081 	int i, err;
15082 
15083 	err = bpf_object__load(*s->obj);
15084 	if (err) {
15085 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
15086 		return libbpf_err(err);
15087 	}
15088 
15089 	for (i = 0; i < s->map_cnt; i++) {
15090 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15091 		struct bpf_map *map = *map_skel->map;
15092 
15093 		if (!map_skel->mmaped)
15094 			continue;
15095 
15096 		if (map->def.type == BPF_MAP_TYPE_ARENA)
15097 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
15098 		else
15099 			*map_skel->mmaped = map->mmaped;
15100 	}
15101 
15102 	return 0;
15103 }
15104 
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)15105 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
15106 {
15107 	int i, err;
15108 
15109 	for (i = 0; i < s->prog_cnt; i++) {
15110 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15111 		struct bpf_program *prog = *prog_skel->prog;
15112 		struct bpf_link **link = prog_skel->link;
15113 
15114 		if (!prog->autoload || !prog->autoattach)
15115 			continue;
15116 
15117 		/* auto-attaching not supported for this program */
15118 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
15119 			continue;
15120 
15121 		/* if user already set the link manually, don't attempt auto-attach */
15122 		if (*link)
15123 			continue;
15124 
15125 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
15126 		if (err) {
15127 			pr_warn("prog '%s': failed to auto-attach: %s\n",
15128 				bpf_program__name(prog), errstr(err));
15129 			return libbpf_err(err);
15130 		}
15131 
15132 		/* It's possible that for some SEC() definitions auto-attach
15133 		 * is supported in some cases (e.g., if definition completely
15134 		 * specifies target information), but is not in other cases.
15135 		 * SEC("uprobe") is one such case. If user specified target
15136 		 * binary and function name, such BPF program can be
15137 		 * auto-attached. But if not, it shouldn't trigger skeleton's
15138 		 * attach to fail. It should just be skipped.
15139 		 * attach_fn signals such case with returning 0 (no error) and
15140 		 * setting link to NULL.
15141 		 */
15142 	}
15143 
15144 
15145 	for (i = 0; i < s->map_cnt; i++) {
15146 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15147 		struct bpf_map *map = *map_skel->map;
15148 		struct bpf_link **link;
15149 
15150 		if (!map->autocreate || !map->autoattach)
15151 			continue;
15152 
15153 		/* only struct_ops maps can be attached */
15154 		if (!bpf_map__is_struct_ops(map))
15155 			continue;
15156 
15157 		/* skeleton is created with earlier version of bpftool, notify user */
15158 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
15159 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
15160 				bpf_map__name(map));
15161 			continue;
15162 		}
15163 
15164 		link = map_skel->link;
15165 		if (!link) {
15166 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
15167 				bpf_map__name(map));
15168 			continue;
15169 		}
15170 
15171 		if (*link)
15172 			continue;
15173 
15174 		*link = bpf_map__attach_struct_ops(map);
15175 		if (!*link) {
15176 			err = -errno;
15177 			pr_warn("map '%s': failed to auto-attach: %s\n",
15178 				bpf_map__name(map), errstr(err));
15179 			return libbpf_err(err);
15180 		}
15181 	}
15182 
15183 	return 0;
15184 }
15185 
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)15186 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
15187 {
15188 	int i;
15189 
15190 	for (i = 0; i < s->prog_cnt; i++) {
15191 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15192 		struct bpf_link **link = prog_skel->link;
15193 
15194 		bpf_link__destroy(*link);
15195 		*link = NULL;
15196 	}
15197 
15198 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
15199 		return;
15200 
15201 	for (i = 0; i < s->map_cnt; i++) {
15202 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15203 		struct bpf_link **link = map_skel->link;
15204 
15205 		if (link) {
15206 			bpf_link__destroy(*link);
15207 			*link = NULL;
15208 		}
15209 	}
15210 }
15211 
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)15212 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
15213 {
15214 	if (!s)
15215 		return;
15216 
15217 	bpf_object__detach_skeleton(s);
15218 	if (s->obj)
15219 		bpf_object__close(*s->obj);
15220 	free(s->maps);
15221 	free(s->progs);
15222 	free(s);
15223 }
15224