xref: /linux/tools/lib/bpf/libbpf.c (revision a6923c06a3b2e2c534ae28c53a7531e76cc95cfa)
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 "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56 #include "bpf_gen_internal.h"
57 #include "zip.h"
58 
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC		0xcafe4a11
61 #endif
62 
63 #define MAX_EVENT_NAME_LEN	64
64 
65 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
66 
67 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
68 
69 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
70  * compilation if user enables corresponding warning. Disable it explicitly.
71  */
72 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
73 
74 #define __printf(a, b)	__attribute__((format(printf, a, b)))
75 
76 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
77 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
78 static int map_set_def_max_entries(struct bpf_map *map);
79 
80 static const char * const attach_type_name[] = {
81 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
82 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
83 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
84 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
85 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
86 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
87 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
88 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
89 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
90 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
91 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
92 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
93 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
94 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
95 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
96 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
97 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
98 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
99 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
100 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
101 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
102 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
103 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
104 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
105 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
106 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
107 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
108 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
109 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
110 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
111 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
112 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
113 	[BPF_LIRC_MODE2]		= "lirc_mode2",
114 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
115 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
116 	[BPF_TRACE_FENTRY]		= "trace_fentry",
117 	[BPF_TRACE_FEXIT]		= "trace_fexit",
118 	[BPF_MODIFY_RETURN]		= "modify_return",
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 };
140 
141 static const char * const link_type_name[] = {
142 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
143 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
144 	[BPF_LINK_TYPE_TRACING]			= "tracing",
145 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
146 	[BPF_LINK_TYPE_ITER]			= "iter",
147 	[BPF_LINK_TYPE_NETNS]			= "netns",
148 	[BPF_LINK_TYPE_XDP]			= "xdp",
149 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
150 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
151 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
152 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
153 	[BPF_LINK_TYPE_TCX]			= "tcx",
154 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
155 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
156 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
157 };
158 
159 static const char * const map_type_name[] = {
160 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
161 	[BPF_MAP_TYPE_HASH]			= "hash",
162 	[BPF_MAP_TYPE_ARRAY]			= "array",
163 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
164 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
165 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
166 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
167 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
168 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
169 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
170 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
171 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
172 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
173 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
174 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
175 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
176 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
177 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
178 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
179 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
180 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
181 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
182 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
183 	[BPF_MAP_TYPE_QUEUE]			= "queue",
184 	[BPF_MAP_TYPE_STACK]			= "stack",
185 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
186 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
187 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
188 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
189 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
190 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
191 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
192 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
193 	[BPF_MAP_TYPE_ARENA]			= "arena",
194 };
195 
196 static const char * const prog_type_name[] = {
197 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
198 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
199 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
200 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
201 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
202 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
203 	[BPF_PROG_TYPE_XDP]			= "xdp",
204 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
205 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
206 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
207 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
208 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
209 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
210 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
211 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
212 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
213 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
214 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
215 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
216 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
217 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
218 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
219 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
220 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
221 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
222 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
223 	[BPF_PROG_TYPE_TRACING]			= "tracing",
224 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
225 	[BPF_PROG_TYPE_EXT]			= "ext",
226 	[BPF_PROG_TYPE_LSM]			= "lsm",
227 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
228 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
229 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
230 };
231 
__base_pr(enum libbpf_print_level level,const char * format,va_list args)232 static int __base_pr(enum libbpf_print_level level, const char *format,
233 		     va_list args)
234 {
235 	const char *env_var = "LIBBPF_LOG_LEVEL";
236 	static enum libbpf_print_level min_level = LIBBPF_INFO;
237 	static bool initialized;
238 
239 	if (!initialized) {
240 		char *verbosity;
241 
242 		initialized = true;
243 		verbosity = getenv(env_var);
244 		if (verbosity) {
245 			if (strcasecmp(verbosity, "warn") == 0)
246 				min_level = LIBBPF_WARN;
247 			else if (strcasecmp(verbosity, "debug") == 0)
248 				min_level = LIBBPF_DEBUG;
249 			else if (strcasecmp(verbosity, "info") == 0)
250 				min_level = LIBBPF_INFO;
251 			else
252 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
253 					env_var, verbosity);
254 		}
255 	}
256 
257 	/* if too verbose, skip logging  */
258 	if (level > min_level)
259 		return 0;
260 
261 	return vfprintf(stderr, format, args);
262 }
263 
264 static libbpf_print_fn_t __libbpf_pr = __base_pr;
265 
libbpf_set_print(libbpf_print_fn_t fn)266 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
267 {
268 	libbpf_print_fn_t old_print_fn;
269 
270 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
271 
272 	return old_print_fn;
273 }
274 
275 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)276 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
277 {
278 	va_list args;
279 	int old_errno;
280 	libbpf_print_fn_t print_fn;
281 
282 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
283 	if (!print_fn)
284 		return;
285 
286 	old_errno = errno;
287 
288 	va_start(args, format);
289 	print_fn(level, format, args);
290 	va_end(args);
291 
292 	errno = old_errno;
293 }
294 
pr_perm_msg(int err)295 static void pr_perm_msg(int err)
296 {
297 	struct rlimit limit;
298 	char buf[100];
299 
300 	if (err != -EPERM || geteuid() != 0)
301 		return;
302 
303 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
304 	if (err)
305 		return;
306 
307 	if (limit.rlim_cur == RLIM_INFINITY)
308 		return;
309 
310 	if (limit.rlim_cur < 1024)
311 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
312 	else if (limit.rlim_cur < 1024*1024)
313 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
314 	else
315 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
316 
317 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
318 		buf);
319 }
320 
321 #define STRERR_BUFSIZE  128
322 
323 /* Copied from tools/perf/util/util.h */
324 #ifndef zfree
325 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
326 #endif
327 
328 #ifndef zclose
329 # define zclose(fd) ({			\
330 	int ___err = 0;			\
331 	if ((fd) >= 0)			\
332 		___err = close((fd));	\
333 	fd = -1;			\
334 	___err; })
335 #endif
336 
ptr_to_u64(const void * ptr)337 static inline __u64 ptr_to_u64(const void *ptr)
338 {
339 	return (__u64) (unsigned long) ptr;
340 }
341 
libbpf_set_strict_mode(enum libbpf_strict_mode mode)342 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
343 {
344 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
345 	return 0;
346 }
347 
libbpf_major_version(void)348 __u32 libbpf_major_version(void)
349 {
350 	return LIBBPF_MAJOR_VERSION;
351 }
352 
libbpf_minor_version(void)353 __u32 libbpf_minor_version(void)
354 {
355 	return LIBBPF_MINOR_VERSION;
356 }
357 
libbpf_version_string(void)358 const char *libbpf_version_string(void)
359 {
360 #define __S(X) #X
361 #define _S(X) __S(X)
362 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
363 #undef _S
364 #undef __S
365 }
366 
367 enum reloc_type {
368 	RELO_LD64,
369 	RELO_CALL,
370 	RELO_DATA,
371 	RELO_EXTERN_LD64,
372 	RELO_EXTERN_CALL,
373 	RELO_SUBPROG_ADDR,
374 	RELO_CORE,
375 };
376 
377 struct reloc_desc {
378 	enum reloc_type type;
379 	int insn_idx;
380 	union {
381 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
382 		struct {
383 			int map_idx;
384 			int sym_off;
385 			int ext_idx;
386 		};
387 	};
388 };
389 
390 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
391 enum sec_def_flags {
392 	SEC_NONE = 0,
393 	/* expected_attach_type is optional, if kernel doesn't support that */
394 	SEC_EXP_ATTACH_OPT = 1,
395 	/* legacy, only used by libbpf_get_type_names() and
396 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
397 	 * This used to be associated with cgroup (and few other) BPF programs
398 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
399 	 * meaningless nowadays, though.
400 	 */
401 	SEC_ATTACHABLE = 2,
402 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
403 	/* attachment target is specified through BTF ID in either kernel or
404 	 * other BPF program's BTF object
405 	 */
406 	SEC_ATTACH_BTF = 4,
407 	/* BPF program type allows sleeping/blocking in kernel */
408 	SEC_SLEEPABLE = 8,
409 	/* BPF program support non-linear XDP buffer */
410 	SEC_XDP_FRAGS = 16,
411 	/* Setup proper attach type for usdt probes. */
412 	SEC_USDT = 32,
413 };
414 
415 struct bpf_sec_def {
416 	char *sec;
417 	enum bpf_prog_type prog_type;
418 	enum bpf_attach_type expected_attach_type;
419 	long cookie;
420 	int handler_id;
421 
422 	libbpf_prog_setup_fn_t prog_setup_fn;
423 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
424 	libbpf_prog_attach_fn_t prog_attach_fn;
425 };
426 
427 /*
428  * bpf_prog should be a better name but it has been used in
429  * linux/filter.h.
430  */
431 struct bpf_program {
432 	char *name;
433 	char *sec_name;
434 	size_t sec_idx;
435 	const struct bpf_sec_def *sec_def;
436 	/* this program's instruction offset (in number of instructions)
437 	 * within its containing ELF section
438 	 */
439 	size_t sec_insn_off;
440 	/* number of original instructions in ELF section belonging to this
441 	 * program, not taking into account subprogram instructions possible
442 	 * appended later during relocation
443 	 */
444 	size_t sec_insn_cnt;
445 	/* Offset (in number of instructions) of the start of instruction
446 	 * belonging to this BPF program  within its containing main BPF
447 	 * program. For the entry-point (main) BPF program, this is always
448 	 * zero. For a sub-program, this gets reset before each of main BPF
449 	 * programs are processed and relocated and is used to determined
450 	 * whether sub-program was already appended to the main program, and
451 	 * if yes, at which instruction offset.
452 	 */
453 	size_t sub_insn_off;
454 
455 	/* instructions that belong to BPF program; insns[0] is located at
456 	 * sec_insn_off instruction within its ELF section in ELF file, so
457 	 * when mapping ELF file instruction index to the local instruction,
458 	 * one needs to subtract sec_insn_off; and vice versa.
459 	 */
460 	struct bpf_insn *insns;
461 	/* actual number of instruction in this BPF program's image; for
462 	 * entry-point BPF programs this includes the size of main program
463 	 * itself plus all the used sub-programs, appended at the end
464 	 */
465 	size_t insns_cnt;
466 
467 	struct reloc_desc *reloc_desc;
468 	int nr_reloc;
469 
470 	/* BPF verifier log settings */
471 	char *log_buf;
472 	size_t log_size;
473 	__u32 log_level;
474 
475 	struct bpf_object *obj;
476 
477 	int fd;
478 	bool autoload;
479 	bool autoattach;
480 	bool sym_global;
481 	bool mark_btf_static;
482 	enum bpf_prog_type type;
483 	enum bpf_attach_type expected_attach_type;
484 	int exception_cb_idx;
485 
486 	int prog_ifindex;
487 	__u32 attach_btf_obj_fd;
488 	__u32 attach_btf_id;
489 	__u32 attach_prog_fd;
490 
491 	void *func_info;
492 	__u32 func_info_rec_size;
493 	__u32 func_info_cnt;
494 
495 	void *line_info;
496 	__u32 line_info_rec_size;
497 	__u32 line_info_cnt;
498 	__u32 prog_flags;
499 };
500 
501 struct bpf_struct_ops {
502 	struct bpf_program **progs;
503 	__u32 *kern_func_off;
504 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
505 	void *data;
506 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
507 	 *      btf_vmlinux's format.
508 	 * struct bpf_struct_ops_tcp_congestion_ops {
509 	 *	[... some other kernel fields ...]
510 	 *	struct tcp_congestion_ops data;
511 	 * }
512 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
513 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
514 	 * from "data".
515 	 */
516 	void *kern_vdata;
517 	__u32 type_id;
518 };
519 
520 #define DATA_SEC ".data"
521 #define BSS_SEC ".bss"
522 #define RODATA_SEC ".rodata"
523 #define KCONFIG_SEC ".kconfig"
524 #define KSYMS_SEC ".ksyms"
525 #define STRUCT_OPS_SEC ".struct_ops"
526 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
527 #define ARENA_SEC ".addr_space.1"
528 
529 enum libbpf_map_type {
530 	LIBBPF_MAP_UNSPEC,
531 	LIBBPF_MAP_DATA,
532 	LIBBPF_MAP_BSS,
533 	LIBBPF_MAP_RODATA,
534 	LIBBPF_MAP_KCONFIG,
535 };
536 
537 struct bpf_map_def {
538 	unsigned int type;
539 	unsigned int key_size;
540 	unsigned int value_size;
541 	unsigned int max_entries;
542 	unsigned int map_flags;
543 };
544 
545 struct bpf_map {
546 	struct bpf_object *obj;
547 	char *name;
548 	/* real_name is defined for special internal maps (.rodata*,
549 	 * .data*, .bss, .kconfig) and preserves their original ELF section
550 	 * name. This is important to be able to find corresponding BTF
551 	 * DATASEC information.
552 	 */
553 	char *real_name;
554 	int fd;
555 	int sec_idx;
556 	size_t sec_offset;
557 	int map_ifindex;
558 	int inner_map_fd;
559 	struct bpf_map_def def;
560 	__u32 numa_node;
561 	__u32 btf_var_idx;
562 	int mod_btf_fd;
563 	__u32 btf_key_type_id;
564 	__u32 btf_value_type_id;
565 	__u32 btf_vmlinux_value_type_id;
566 	enum libbpf_map_type libbpf_type;
567 	void *mmaped;
568 	struct bpf_struct_ops *st_ops;
569 	struct bpf_map *inner_map;
570 	void **init_slots;
571 	int init_slots_sz;
572 	char *pin_path;
573 	bool pinned;
574 	bool reused;
575 	bool autocreate;
576 	bool autoattach;
577 	__u64 map_extra;
578 };
579 
580 enum extern_type {
581 	EXT_UNKNOWN,
582 	EXT_KCFG,
583 	EXT_KSYM,
584 };
585 
586 enum kcfg_type {
587 	KCFG_UNKNOWN,
588 	KCFG_CHAR,
589 	KCFG_BOOL,
590 	KCFG_INT,
591 	KCFG_TRISTATE,
592 	KCFG_CHAR_ARR,
593 };
594 
595 struct extern_desc {
596 	enum extern_type type;
597 	int sym_idx;
598 	int btf_id;
599 	int sec_btf_id;
600 	char *name;
601 	char *essent_name;
602 	bool is_set;
603 	bool is_weak;
604 	union {
605 		struct {
606 			enum kcfg_type type;
607 			int sz;
608 			int align;
609 			int data_off;
610 			bool is_signed;
611 		} kcfg;
612 		struct {
613 			unsigned long long addr;
614 
615 			/* target btf_id of the corresponding kernel var. */
616 			int kernel_btf_obj_fd;
617 			int kernel_btf_id;
618 
619 			/* local btf_id of the ksym extern's type. */
620 			__u32 type_id;
621 			/* BTF fd index to be patched in for insn->off, this is
622 			 * 0 for vmlinux BTF, index in obj->fd_array for module
623 			 * BTF
624 			 */
625 			__s16 btf_fd_idx;
626 		} ksym;
627 	};
628 };
629 
630 struct module_btf {
631 	struct btf *btf;
632 	char *name;
633 	__u32 id;
634 	int fd;
635 	int fd_array_idx;
636 };
637 
638 enum sec_type {
639 	SEC_UNUSED = 0,
640 	SEC_RELO,
641 	SEC_BSS,
642 	SEC_DATA,
643 	SEC_RODATA,
644 	SEC_ST_OPS,
645 };
646 
647 struct elf_sec_desc {
648 	enum sec_type sec_type;
649 	Elf64_Shdr *shdr;
650 	Elf_Data *data;
651 };
652 
653 struct elf_state {
654 	int fd;
655 	const void *obj_buf;
656 	size_t obj_buf_sz;
657 	Elf *elf;
658 	Elf64_Ehdr *ehdr;
659 	Elf_Data *symbols;
660 	Elf_Data *arena_data;
661 	size_t shstrndx; /* section index for section name strings */
662 	size_t strtabidx;
663 	struct elf_sec_desc *secs;
664 	size_t sec_cnt;
665 	int btf_maps_shndx;
666 	__u32 btf_maps_sec_btf_id;
667 	int text_shndx;
668 	int symbols_shndx;
669 	bool has_st_ops;
670 	int arena_data_shndx;
671 };
672 
673 struct usdt_manager;
674 
675 enum bpf_object_state {
676 	OBJ_OPEN,
677 	OBJ_PREPARED,
678 	OBJ_LOADED,
679 };
680 
681 struct bpf_object {
682 	char name[BPF_OBJ_NAME_LEN];
683 	char license[64];
684 	__u32 kern_version;
685 
686 	enum bpf_object_state state;
687 	struct bpf_program *programs;
688 	size_t nr_programs;
689 	struct bpf_map *maps;
690 	size_t nr_maps;
691 	size_t maps_cap;
692 
693 	char *kconfig;
694 	struct extern_desc *externs;
695 	int nr_extern;
696 	int kconfig_map_idx;
697 
698 	bool has_subcalls;
699 	bool has_rodata;
700 
701 	struct bpf_gen *gen_loader;
702 
703 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
704 	struct elf_state efile;
705 
706 	unsigned char byteorder;
707 
708 	struct btf *btf;
709 	struct btf_ext *btf_ext;
710 
711 	/* Parse and load BTF vmlinux if any of the programs in the object need
712 	 * it at load time.
713 	 */
714 	struct btf *btf_vmlinux;
715 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
716 	 * override for vmlinux BTF.
717 	 */
718 	char *btf_custom_path;
719 	/* vmlinux BTF override for CO-RE relocations */
720 	struct btf *btf_vmlinux_override;
721 	/* Lazily initialized kernel module BTFs */
722 	struct module_btf *btf_modules;
723 	bool btf_modules_loaded;
724 	size_t btf_module_cnt;
725 	size_t btf_module_cap;
726 
727 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
728 	char *log_buf;
729 	size_t log_size;
730 	__u32 log_level;
731 
732 	int *fd_array;
733 	size_t fd_array_cap;
734 	size_t fd_array_cnt;
735 
736 	struct usdt_manager *usdt_man;
737 
738 	int arena_map_idx;
739 	void *arena_data;
740 	size_t arena_data_sz;
741 
742 	struct kern_feature_cache *feat_cache;
743 	char *token_path;
744 	int token_fd;
745 
746 	char path[];
747 };
748 
749 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
750 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
751 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
752 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
753 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
754 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
755 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
756 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
757 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
758 
bpf_program__unload(struct bpf_program * prog)759 void bpf_program__unload(struct bpf_program *prog)
760 {
761 	if (!prog)
762 		return;
763 
764 	zclose(prog->fd);
765 
766 	zfree(&prog->func_info);
767 	zfree(&prog->line_info);
768 }
769 
bpf_program__exit(struct bpf_program * prog)770 static void bpf_program__exit(struct bpf_program *prog)
771 {
772 	if (!prog)
773 		return;
774 
775 	bpf_program__unload(prog);
776 	zfree(&prog->name);
777 	zfree(&prog->sec_name);
778 	zfree(&prog->insns);
779 	zfree(&prog->reloc_desc);
780 
781 	prog->nr_reloc = 0;
782 	prog->insns_cnt = 0;
783 	prog->sec_idx = -1;
784 }
785 
insn_is_subprog_call(const struct bpf_insn * insn)786 static bool insn_is_subprog_call(const struct bpf_insn *insn)
787 {
788 	return BPF_CLASS(insn->code) == BPF_JMP &&
789 	       BPF_OP(insn->code) == BPF_CALL &&
790 	       BPF_SRC(insn->code) == BPF_K &&
791 	       insn->src_reg == BPF_PSEUDO_CALL &&
792 	       insn->dst_reg == 0 &&
793 	       insn->off == 0;
794 }
795 
is_call_insn(const struct bpf_insn * insn)796 static bool is_call_insn(const struct bpf_insn *insn)
797 {
798 	return insn->code == (BPF_JMP | BPF_CALL);
799 }
800 
insn_is_pseudo_func(struct bpf_insn * insn)801 static bool insn_is_pseudo_func(struct bpf_insn *insn)
802 {
803 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
804 }
805 
806 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)807 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
808 		      const char *name, size_t sec_idx, const char *sec_name,
809 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
810 {
811 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
812 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
813 			sec_name, name, sec_off, insn_data_sz);
814 		return -EINVAL;
815 	}
816 
817 	memset(prog, 0, sizeof(*prog));
818 	prog->obj = obj;
819 
820 	prog->sec_idx = sec_idx;
821 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
822 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
823 	/* insns_cnt can later be increased by appending used subprograms */
824 	prog->insns_cnt = prog->sec_insn_cnt;
825 
826 	prog->type = BPF_PROG_TYPE_UNSPEC;
827 	prog->fd = -1;
828 	prog->exception_cb_idx = -1;
829 
830 	/* libbpf's convention for SEC("?abc...") is that it's just like
831 	 * SEC("abc...") but the corresponding bpf_program starts out with
832 	 * autoload set to false.
833 	 */
834 	if (sec_name[0] == '?') {
835 		prog->autoload = false;
836 		/* from now on forget there was ? in section name */
837 		sec_name++;
838 	} else {
839 		prog->autoload = true;
840 	}
841 
842 	prog->autoattach = true;
843 
844 	/* inherit object's log_level */
845 	prog->log_level = obj->log_level;
846 
847 	prog->sec_name = strdup(sec_name);
848 	if (!prog->sec_name)
849 		goto errout;
850 
851 	prog->name = strdup(name);
852 	if (!prog->name)
853 		goto errout;
854 
855 	prog->insns = malloc(insn_data_sz);
856 	if (!prog->insns)
857 		goto errout;
858 	memcpy(prog->insns, insn_data, insn_data_sz);
859 
860 	return 0;
861 errout:
862 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
863 	bpf_program__exit(prog);
864 	return -ENOMEM;
865 }
866 
867 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)868 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
869 			 const char *sec_name, int sec_idx)
870 {
871 	Elf_Data *symbols = obj->efile.symbols;
872 	struct bpf_program *prog, *progs;
873 	void *data = sec_data->d_buf;
874 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
875 	int nr_progs, err, i;
876 	const char *name;
877 	Elf64_Sym *sym;
878 
879 	progs = obj->programs;
880 	nr_progs = obj->nr_programs;
881 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
882 
883 	for (i = 0; i < nr_syms; i++) {
884 		sym = elf_sym_by_idx(obj, i);
885 
886 		if (sym->st_shndx != sec_idx)
887 			continue;
888 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
889 			continue;
890 
891 		prog_sz = sym->st_size;
892 		sec_off = sym->st_value;
893 
894 		name = elf_sym_str(obj, sym->st_name);
895 		if (!name) {
896 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
897 				sec_name, sec_off);
898 			return -LIBBPF_ERRNO__FORMAT;
899 		}
900 
901 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
902 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
903 				sec_name, sec_off);
904 			return -LIBBPF_ERRNO__FORMAT;
905 		}
906 
907 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
908 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
909 			return -ENOTSUP;
910 		}
911 
912 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
913 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
914 
915 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
916 		if (!progs) {
917 			/*
918 			 * In this case the original obj->programs
919 			 * is still valid, so don't need special treat for
920 			 * bpf_close_object().
921 			 */
922 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
923 				sec_name, name);
924 			return -ENOMEM;
925 		}
926 		obj->programs = progs;
927 
928 		prog = &progs[nr_progs];
929 
930 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
931 					    sec_off, data + sec_off, prog_sz);
932 		if (err)
933 			return err;
934 
935 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
936 			prog->sym_global = true;
937 
938 		/* if function is a global/weak symbol, but has restricted
939 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
940 		 * as static to enable more permissive BPF verification mode
941 		 * with more outside context available to BPF verifier
942 		 */
943 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
944 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
945 			prog->mark_btf_static = true;
946 
947 		nr_progs++;
948 		obj->nr_programs = nr_progs;
949 	}
950 
951 	return 0;
952 }
953 
bpf_object_bswap_progs(struct bpf_object * obj)954 static void bpf_object_bswap_progs(struct bpf_object *obj)
955 {
956 	struct bpf_program *prog = obj->programs;
957 	struct bpf_insn *insn;
958 	int p, i;
959 
960 	for (p = 0; p < obj->nr_programs; p++, prog++) {
961 		insn = prog->insns;
962 		for (i = 0; i < prog->insns_cnt; i++, insn++)
963 			bpf_insn_bswap(insn);
964 	}
965 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
966 }
967 
968 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)969 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
970 {
971 	struct btf_member *m;
972 	int i;
973 
974 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
975 		if (btf_member_bit_offset(t, i) == bit_offset)
976 			return m;
977 	}
978 
979 	return NULL;
980 }
981 
982 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)983 find_member_by_name(const struct btf *btf, const struct btf_type *t,
984 		    const char *name)
985 {
986 	struct btf_member *m;
987 	int i;
988 
989 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
990 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
991 			return m;
992 	}
993 
994 	return NULL;
995 }
996 
997 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
998 			    __u16 kind, struct btf **res_btf,
999 			    struct module_btf **res_mod_btf);
1000 
1001 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1002 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1003 				   const char *name, __u32 kind);
1004 
1005 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)1006 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1007 			   struct module_btf **mod_btf,
1008 			   const struct btf_type **type, __u32 *type_id,
1009 			   const struct btf_type **vtype, __u32 *vtype_id,
1010 			   const struct btf_member **data_member)
1011 {
1012 	const struct btf_type *kern_type, *kern_vtype;
1013 	const struct btf_member *kern_data_member;
1014 	struct btf *btf = NULL;
1015 	__s32 kern_vtype_id, kern_type_id;
1016 	char tname[256];
1017 	__u32 i;
1018 
1019 	snprintf(tname, sizeof(tname), "%.*s",
1020 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1021 
1022 	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
1023 					&btf, mod_btf);
1024 	if (kern_type_id < 0) {
1025 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1026 			tname);
1027 		return kern_type_id;
1028 	}
1029 	kern_type = btf__type_by_id(btf, kern_type_id);
1030 
1031 	/* Find the corresponding "map_value" type that will be used
1032 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1033 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1034 	 * btf_vmlinux.
1035 	 */
1036 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1037 						tname, BTF_KIND_STRUCT);
1038 	if (kern_vtype_id < 0) {
1039 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1040 			STRUCT_OPS_VALUE_PREFIX, tname);
1041 		return kern_vtype_id;
1042 	}
1043 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1044 
1045 	/* Find "struct tcp_congestion_ops" from
1046 	 * struct bpf_struct_ops_tcp_congestion_ops {
1047 	 *	[ ... ]
1048 	 *	struct tcp_congestion_ops data;
1049 	 * }
1050 	 */
1051 	kern_data_member = btf_members(kern_vtype);
1052 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1053 		if (kern_data_member->type == kern_type_id)
1054 			break;
1055 	}
1056 	if (i == btf_vlen(kern_vtype)) {
1057 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1058 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1059 		return -EINVAL;
1060 	}
1061 
1062 	*type = kern_type;
1063 	*type_id = kern_type_id;
1064 	*vtype = kern_vtype;
1065 	*vtype_id = kern_vtype_id;
1066 	*data_member = kern_data_member;
1067 
1068 	return 0;
1069 }
1070 
bpf_map__is_struct_ops(const struct bpf_map * map)1071 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1072 {
1073 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1074 }
1075 
is_valid_st_ops_program(struct bpf_object * obj,const struct bpf_program * prog)1076 static bool is_valid_st_ops_program(struct bpf_object *obj,
1077 				    const struct bpf_program *prog)
1078 {
1079 	int i;
1080 
1081 	for (i = 0; i < obj->nr_programs; i++) {
1082 		if (&obj->programs[i] == prog)
1083 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1084 	}
1085 
1086 	return false;
1087 }
1088 
1089 /* For each struct_ops program P, referenced from some struct_ops map M,
1090  * enable P.autoload if there are Ms for which M.autocreate is true,
1091  * disable P.autoload if for all Ms M.autocreate is false.
1092  * Don't change P.autoload for programs that are not referenced from any maps.
1093  */
bpf_object_adjust_struct_ops_autoload(struct bpf_object * obj)1094 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1095 {
1096 	struct bpf_program *prog, *slot_prog;
1097 	struct bpf_map *map;
1098 	int i, j, k, vlen;
1099 
1100 	for (i = 0; i < obj->nr_programs; ++i) {
1101 		int should_load = false;
1102 		int use_cnt = 0;
1103 
1104 		prog = &obj->programs[i];
1105 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1106 			continue;
1107 
1108 		for (j = 0; j < obj->nr_maps; ++j) {
1109 			const struct btf_type *type;
1110 
1111 			map = &obj->maps[j];
1112 			if (!bpf_map__is_struct_ops(map))
1113 				continue;
1114 
1115 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1116 			vlen = btf_vlen(type);
1117 			for (k = 0; k < vlen; ++k) {
1118 				slot_prog = map->st_ops->progs[k];
1119 				if (prog != slot_prog)
1120 					continue;
1121 
1122 				use_cnt++;
1123 				if (map->autocreate)
1124 					should_load = true;
1125 			}
1126 		}
1127 		if (use_cnt)
1128 			prog->autoload = should_load;
1129 	}
1130 
1131 	return 0;
1132 }
1133 
1134 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map)1135 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1136 {
1137 	const struct btf_member *member, *kern_member, *kern_data_member;
1138 	const struct btf_type *type, *kern_type, *kern_vtype;
1139 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1140 	struct bpf_object *obj = map->obj;
1141 	const struct btf *btf = obj->btf;
1142 	struct bpf_struct_ops *st_ops;
1143 	const struct btf *kern_btf;
1144 	struct module_btf *mod_btf = NULL;
1145 	void *data, *kern_data;
1146 	const char *tname;
1147 	int err;
1148 
1149 	st_ops = map->st_ops;
1150 	type = btf__type_by_id(btf, st_ops->type_id);
1151 	tname = btf__name_by_offset(btf, type->name_off);
1152 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1153 					 &kern_type, &kern_type_id,
1154 					 &kern_vtype, &kern_vtype_id,
1155 					 &kern_data_member);
1156 	if (err)
1157 		return err;
1158 
1159 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1160 
1161 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1162 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1163 
1164 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1165 	map->def.value_size = kern_vtype->size;
1166 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1167 
1168 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1169 	if (!st_ops->kern_vdata)
1170 		return -ENOMEM;
1171 
1172 	data = st_ops->data;
1173 	kern_data_off = kern_data_member->offset / 8;
1174 	kern_data = st_ops->kern_vdata + kern_data_off;
1175 
1176 	member = btf_members(type);
1177 	for (i = 0; i < btf_vlen(type); i++, member++) {
1178 		const struct btf_type *mtype, *kern_mtype;
1179 		__u32 mtype_id, kern_mtype_id;
1180 		void *mdata, *kern_mdata;
1181 		struct bpf_program *prog;
1182 		__s64 msize, kern_msize;
1183 		__u32 moff, kern_moff;
1184 		__u32 kern_member_idx;
1185 		const char *mname;
1186 
1187 		mname = btf__name_by_offset(btf, member->name_off);
1188 		moff = member->offset / 8;
1189 		mdata = data + moff;
1190 		msize = btf__resolve_size(btf, member->type);
1191 		if (msize < 0) {
1192 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1193 				map->name, mname);
1194 			return msize;
1195 		}
1196 
1197 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1198 		if (!kern_member) {
1199 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1200 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1201 					map->name, mname);
1202 				return -ENOTSUP;
1203 			}
1204 
1205 			if (st_ops->progs[i]) {
1206 				/* If we had declaratively set struct_ops callback, we need to
1207 				 * force its autoload to false, because it doesn't have
1208 				 * a chance of succeeding from POV of the current struct_ops map.
1209 				 * If this program is still referenced somewhere else, though,
1210 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1211 				 * autoload accordingly.
1212 				 */
1213 				st_ops->progs[i]->autoload = false;
1214 				st_ops->progs[i] = NULL;
1215 			}
1216 
1217 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1218 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1219 				map->name, mname);
1220 			continue;
1221 		}
1222 
1223 		kern_member_idx = kern_member - btf_members(kern_type);
1224 		if (btf_member_bitfield_size(type, i) ||
1225 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1226 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1227 				map->name, mname);
1228 			return -ENOTSUP;
1229 		}
1230 
1231 		kern_moff = kern_member->offset / 8;
1232 		kern_mdata = kern_data + kern_moff;
1233 
1234 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1235 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1236 						    &kern_mtype_id);
1237 		if (BTF_INFO_KIND(mtype->info) !=
1238 		    BTF_INFO_KIND(kern_mtype->info)) {
1239 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1240 				map->name, mname, BTF_INFO_KIND(mtype->info),
1241 				BTF_INFO_KIND(kern_mtype->info));
1242 			return -ENOTSUP;
1243 		}
1244 
1245 		if (btf_is_ptr(mtype)) {
1246 			prog = *(void **)mdata;
1247 			/* just like for !kern_member case above, reset declaratively
1248 			 * set (at compile time) program's autload to false,
1249 			 * if user replaced it with another program or NULL
1250 			 */
1251 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1252 				st_ops->progs[i]->autoload = false;
1253 
1254 			/* Update the value from the shadow type */
1255 			st_ops->progs[i] = prog;
1256 			if (!prog)
1257 				continue;
1258 
1259 			if (!is_valid_st_ops_program(obj, prog)) {
1260 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1261 					map->name, mname);
1262 				return -ENOTSUP;
1263 			}
1264 
1265 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1266 							    kern_mtype->type,
1267 							    &kern_mtype_id);
1268 
1269 			/* mtype->type must be a func_proto which was
1270 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1271 			 * so only check kern_mtype for func_proto here.
1272 			 */
1273 			if (!btf_is_func_proto(kern_mtype)) {
1274 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1275 					map->name, mname);
1276 				return -ENOTSUP;
1277 			}
1278 
1279 			if (mod_btf)
1280 				prog->attach_btf_obj_fd = mod_btf->fd;
1281 
1282 			/* if we haven't yet processed this BPF program, record proper
1283 			 * attach_btf_id and member_idx
1284 			 */
1285 			if (!prog->attach_btf_id) {
1286 				prog->attach_btf_id = kern_type_id;
1287 				prog->expected_attach_type = kern_member_idx;
1288 			}
1289 
1290 			/* struct_ops BPF prog can be re-used between multiple
1291 			 * .struct_ops & .struct_ops.link as long as it's the
1292 			 * same struct_ops struct definition and the same
1293 			 * function pointer field
1294 			 */
1295 			if (prog->attach_btf_id != kern_type_id) {
1296 				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",
1297 					map->name, mname, prog->name, prog->sec_name, prog->type,
1298 					prog->attach_btf_id, kern_type_id);
1299 				return -EINVAL;
1300 			}
1301 			if (prog->expected_attach_type != kern_member_idx) {
1302 				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",
1303 					map->name, mname, prog->name, prog->sec_name, prog->type,
1304 					prog->expected_attach_type, kern_member_idx);
1305 				return -EINVAL;
1306 			}
1307 
1308 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1309 
1310 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1311 				 map->name, mname, prog->name, moff,
1312 				 kern_moff);
1313 
1314 			continue;
1315 		}
1316 
1317 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1318 		if (kern_msize < 0 || msize != kern_msize) {
1319 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1320 				map->name, mname, (ssize_t)msize,
1321 				(ssize_t)kern_msize);
1322 			return -ENOTSUP;
1323 		}
1324 
1325 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1326 			 map->name, mname, (unsigned int)msize,
1327 			 moff, kern_moff);
1328 		memcpy(kern_mdata, mdata, msize);
1329 	}
1330 
1331 	return 0;
1332 }
1333 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1334 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1335 {
1336 	struct bpf_map *map;
1337 	size_t i;
1338 	int err;
1339 
1340 	for (i = 0; i < obj->nr_maps; i++) {
1341 		map = &obj->maps[i];
1342 
1343 		if (!bpf_map__is_struct_ops(map))
1344 			continue;
1345 
1346 		if (!map->autocreate)
1347 			continue;
1348 
1349 		err = bpf_map__init_kern_struct_ops(map);
1350 		if (err)
1351 			return err;
1352 	}
1353 
1354 	return 0;
1355 }
1356 
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data)1357 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1358 				int shndx, Elf_Data *data)
1359 {
1360 	const struct btf_type *type, *datasec;
1361 	const struct btf_var_secinfo *vsi;
1362 	struct bpf_struct_ops *st_ops;
1363 	const char *tname, *var_name;
1364 	__s32 type_id, datasec_id;
1365 	const struct btf *btf;
1366 	struct bpf_map *map;
1367 	__u32 i;
1368 
1369 	if (shndx == -1)
1370 		return 0;
1371 
1372 	btf = obj->btf;
1373 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1374 					    BTF_KIND_DATASEC);
1375 	if (datasec_id < 0) {
1376 		pr_warn("struct_ops init: DATASEC %s not found\n",
1377 			sec_name);
1378 		return -EINVAL;
1379 	}
1380 
1381 	datasec = btf__type_by_id(btf, datasec_id);
1382 	vsi = btf_var_secinfos(datasec);
1383 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1384 		type = btf__type_by_id(obj->btf, vsi->type);
1385 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1386 
1387 		type_id = btf__resolve_type(obj->btf, vsi->type);
1388 		if (type_id < 0) {
1389 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1390 				vsi->type, sec_name);
1391 			return -EINVAL;
1392 		}
1393 
1394 		type = btf__type_by_id(obj->btf, type_id);
1395 		tname = btf__name_by_offset(obj->btf, type->name_off);
1396 		if (!tname[0]) {
1397 			pr_warn("struct_ops init: anonymous type is not supported\n");
1398 			return -ENOTSUP;
1399 		}
1400 		if (!btf_is_struct(type)) {
1401 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1402 			return -EINVAL;
1403 		}
1404 
1405 		map = bpf_object__add_map(obj);
1406 		if (IS_ERR(map))
1407 			return PTR_ERR(map);
1408 
1409 		map->sec_idx = shndx;
1410 		map->sec_offset = vsi->offset;
1411 		map->name = strdup(var_name);
1412 		if (!map->name)
1413 			return -ENOMEM;
1414 		map->btf_value_type_id = type_id;
1415 
1416 		/* Follow same convention as for programs autoload:
1417 		 * SEC("?.struct_ops") means map is not created by default.
1418 		 */
1419 		if (sec_name[0] == '?') {
1420 			map->autocreate = false;
1421 			/* from now on forget there was ? in section name */
1422 			sec_name++;
1423 		}
1424 
1425 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1426 		map->def.key_size = sizeof(int);
1427 		map->def.value_size = type->size;
1428 		map->def.max_entries = 1;
1429 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1430 		map->autoattach = true;
1431 
1432 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1433 		if (!map->st_ops)
1434 			return -ENOMEM;
1435 		st_ops = map->st_ops;
1436 		st_ops->data = malloc(type->size);
1437 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1438 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1439 					       sizeof(*st_ops->kern_func_off));
1440 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1441 			return -ENOMEM;
1442 
1443 		if (vsi->offset + type->size > data->d_size) {
1444 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1445 				var_name, sec_name);
1446 			return -EINVAL;
1447 		}
1448 
1449 		memcpy(st_ops->data,
1450 		       data->d_buf + vsi->offset,
1451 		       type->size);
1452 		st_ops->type_id = type_id;
1453 
1454 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1455 			 tname, type_id, var_name, vsi->offset);
1456 	}
1457 
1458 	return 0;
1459 }
1460 
bpf_object_init_struct_ops(struct bpf_object * obj)1461 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1462 {
1463 	const char *sec_name;
1464 	int sec_idx, err;
1465 
1466 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1467 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1468 
1469 		if (desc->sec_type != SEC_ST_OPS)
1470 			continue;
1471 
1472 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1473 		if (!sec_name)
1474 			return -LIBBPF_ERRNO__FORMAT;
1475 
1476 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1477 		if (err)
1478 			return err;
1479 	}
1480 
1481 	return 0;
1482 }
1483 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1484 static struct bpf_object *bpf_object__new(const char *path,
1485 					  const void *obj_buf,
1486 					  size_t obj_buf_sz,
1487 					  const char *obj_name)
1488 {
1489 	struct bpf_object *obj;
1490 	char *end;
1491 
1492 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1493 	if (!obj) {
1494 		pr_warn("alloc memory failed for %s\n", path);
1495 		return ERR_PTR(-ENOMEM);
1496 	}
1497 
1498 	strcpy(obj->path, path);
1499 	if (obj_name) {
1500 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1501 	} else {
1502 		/* Using basename() GNU version which doesn't modify arg. */
1503 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1504 		end = strchr(obj->name, '.');
1505 		if (end)
1506 			*end = 0;
1507 	}
1508 
1509 	obj->efile.fd = -1;
1510 	/*
1511 	 * Caller of this function should also call
1512 	 * bpf_object__elf_finish() after data collection to return
1513 	 * obj_buf to user. If not, we should duplicate the buffer to
1514 	 * avoid user freeing them before elf finish.
1515 	 */
1516 	obj->efile.obj_buf = obj_buf;
1517 	obj->efile.obj_buf_sz = obj_buf_sz;
1518 	obj->efile.btf_maps_shndx = -1;
1519 	obj->kconfig_map_idx = -1;
1520 	obj->arena_map_idx = -1;
1521 
1522 	obj->kern_version = get_kernel_version();
1523 	obj->state  = OBJ_OPEN;
1524 
1525 	return obj;
1526 }
1527 
bpf_object__elf_finish(struct bpf_object * obj)1528 static void bpf_object__elf_finish(struct bpf_object *obj)
1529 {
1530 	if (!obj->efile.elf)
1531 		return;
1532 
1533 	elf_end(obj->efile.elf);
1534 	obj->efile.elf = NULL;
1535 	obj->efile.ehdr = NULL;
1536 	obj->efile.symbols = NULL;
1537 	obj->efile.arena_data = NULL;
1538 
1539 	zfree(&obj->efile.secs);
1540 	obj->efile.sec_cnt = 0;
1541 	zclose(obj->efile.fd);
1542 	obj->efile.obj_buf = NULL;
1543 	obj->efile.obj_buf_sz = 0;
1544 }
1545 
bpf_object__elf_init(struct bpf_object * obj)1546 static int bpf_object__elf_init(struct bpf_object *obj)
1547 {
1548 	Elf64_Ehdr *ehdr;
1549 	int err = 0;
1550 	Elf *elf;
1551 
1552 	if (obj->efile.elf) {
1553 		pr_warn("elf: init internal error\n");
1554 		return -LIBBPF_ERRNO__LIBELF;
1555 	}
1556 
1557 	if (obj->efile.obj_buf_sz > 0) {
1558 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1559 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1560 	} else {
1561 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1562 		if (obj->efile.fd < 0) {
1563 			err = -errno;
1564 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1565 			return err;
1566 		}
1567 
1568 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1569 	}
1570 
1571 	if (!elf) {
1572 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1573 		err = -LIBBPF_ERRNO__LIBELF;
1574 		goto errout;
1575 	}
1576 
1577 	obj->efile.elf = elf;
1578 
1579 	if (elf_kind(elf) != ELF_K_ELF) {
1580 		err = -LIBBPF_ERRNO__FORMAT;
1581 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1582 		goto errout;
1583 	}
1584 
1585 	if (gelf_getclass(elf) != ELFCLASS64) {
1586 		err = -LIBBPF_ERRNO__FORMAT;
1587 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1588 		goto errout;
1589 	}
1590 
1591 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1592 	if (!obj->efile.ehdr) {
1593 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1594 		err = -LIBBPF_ERRNO__FORMAT;
1595 		goto errout;
1596 	}
1597 
1598 	/* Validate ELF object endianness... */
1599 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1600 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1601 		err = -LIBBPF_ERRNO__ENDIAN;
1602 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1603 		goto errout;
1604 	}
1605 	/* and save after bpf_object_open() frees ELF data */
1606 	obj->byteorder = ehdr->e_ident[EI_DATA];
1607 
1608 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1609 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1610 			obj->path, elf_errmsg(-1));
1611 		err = -LIBBPF_ERRNO__FORMAT;
1612 		goto errout;
1613 	}
1614 
1615 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1616 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1617 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1618 			obj->path, elf_errmsg(-1));
1619 		err = -LIBBPF_ERRNO__FORMAT;
1620 		goto errout;
1621 	}
1622 
1623 	/* Old LLVM set e_machine to EM_NONE */
1624 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1625 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1626 		err = -LIBBPF_ERRNO__FORMAT;
1627 		goto errout;
1628 	}
1629 
1630 	return 0;
1631 errout:
1632 	bpf_object__elf_finish(obj);
1633 	return err;
1634 }
1635 
is_native_endianness(struct bpf_object * obj)1636 static bool is_native_endianness(struct bpf_object *obj)
1637 {
1638 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1639 	return obj->byteorder == ELFDATA2LSB;
1640 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1641 	return obj->byteorder == ELFDATA2MSB;
1642 #else
1643 # error "Unrecognized __BYTE_ORDER__"
1644 #endif
1645 }
1646 
1647 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1648 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1649 {
1650 	if (!data) {
1651 		pr_warn("invalid license section in %s\n", obj->path);
1652 		return -LIBBPF_ERRNO__FORMAT;
1653 	}
1654 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1655 	 * go over allowed ELF data section buffer
1656 	 */
1657 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1658 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1659 	return 0;
1660 }
1661 
1662 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1663 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1664 {
1665 	__u32 kver;
1666 
1667 	if (!data || size != sizeof(kver)) {
1668 		pr_warn("invalid kver section in %s\n", obj->path);
1669 		return -LIBBPF_ERRNO__FORMAT;
1670 	}
1671 	memcpy(&kver, data, sizeof(kver));
1672 	obj->kern_version = kver;
1673 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1674 	return 0;
1675 }
1676 
bpf_map_type__is_map_in_map(enum bpf_map_type type)1677 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1678 {
1679 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1680 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1681 		return true;
1682 	return false;
1683 }
1684 
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1685 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1686 {
1687 	Elf_Data *data;
1688 	Elf_Scn *scn;
1689 
1690 	if (!name)
1691 		return -EINVAL;
1692 
1693 	scn = elf_sec_by_name(obj, name);
1694 	data = elf_sec_data(obj, scn);
1695 	if (data) {
1696 		*size = data->d_size;
1697 		return 0; /* found it */
1698 	}
1699 
1700 	return -ENOENT;
1701 }
1702 
find_elf_var_sym(const struct bpf_object * obj,const char * name)1703 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1704 {
1705 	Elf_Data *symbols = obj->efile.symbols;
1706 	const char *sname;
1707 	size_t si;
1708 
1709 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1710 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1711 
1712 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1713 			continue;
1714 
1715 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1716 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1717 			continue;
1718 
1719 		sname = elf_sym_str(obj, sym->st_name);
1720 		if (!sname) {
1721 			pr_warn("failed to get sym name string for var %s\n", name);
1722 			return ERR_PTR(-EIO);
1723 		}
1724 		if (strcmp(name, sname) == 0)
1725 			return sym;
1726 	}
1727 
1728 	return ERR_PTR(-ENOENT);
1729 }
1730 
1731 #ifndef MFD_CLOEXEC
1732 #define MFD_CLOEXEC 0x0001U
1733 #endif
1734 #ifndef MFD_NOEXEC_SEAL
1735 #define MFD_NOEXEC_SEAL 0x0008U
1736 #endif
1737 
create_placeholder_fd(void)1738 static int create_placeholder_fd(void)
1739 {
1740 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1741 	const char *name = "libbpf-placeholder-fd";
1742 	int fd;
1743 
1744 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1745 	if (fd >= 0)
1746 		return fd;
1747 	else if (errno != EINVAL)
1748 		return -errno;
1749 
1750 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1751 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1752 	if (fd < 0)
1753 		return -errno;
1754 	return fd;
1755 }
1756 
bpf_object__add_map(struct bpf_object * obj)1757 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1758 {
1759 	struct bpf_map *map;
1760 	int err;
1761 
1762 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1763 				sizeof(*obj->maps), obj->nr_maps + 1);
1764 	if (err)
1765 		return ERR_PTR(err);
1766 
1767 	map = &obj->maps[obj->nr_maps++];
1768 	map->obj = obj;
1769 	/* Preallocate map FD without actually creating BPF map just yet.
1770 	 * These map FD "placeholders" will be reused later without changing
1771 	 * FD value when map is actually created in the kernel.
1772 	 *
1773 	 * This is useful to be able to perform BPF program relocations
1774 	 * without having to create BPF maps before that step. This allows us
1775 	 * to finalize and load BTF very late in BPF object's loading phase,
1776 	 * right before BPF maps have to be created and BPF programs have to
1777 	 * be loaded. By having these map FD placeholders we can perform all
1778 	 * the sanitizations, relocations, and any other adjustments before we
1779 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1780 	 */
1781 	map->fd = create_placeholder_fd();
1782 	if (map->fd < 0)
1783 		return ERR_PTR(map->fd);
1784 	map->inner_map_fd = -1;
1785 	map->autocreate = true;
1786 
1787 	return map;
1788 }
1789 
array_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1790 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1791 {
1792 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1793 	size_t map_sz;
1794 
1795 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1796 	map_sz = roundup(map_sz, page_sz);
1797 	return map_sz;
1798 }
1799 
bpf_map_mmap_sz(const struct bpf_map * map)1800 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1801 {
1802 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1803 
1804 	switch (map->def.type) {
1805 	case BPF_MAP_TYPE_ARRAY:
1806 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1807 	case BPF_MAP_TYPE_ARENA:
1808 		return page_sz * map->def.max_entries;
1809 	default:
1810 		return 0; /* not supported */
1811 	}
1812 }
1813 
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1814 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1815 {
1816 	void *mmaped;
1817 
1818 	if (!map->mmaped)
1819 		return -EINVAL;
1820 
1821 	if (old_sz == new_sz)
1822 		return 0;
1823 
1824 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1825 	if (mmaped == MAP_FAILED)
1826 		return -errno;
1827 
1828 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1829 	munmap(map->mmaped, old_sz);
1830 	map->mmaped = mmaped;
1831 	return 0;
1832 }
1833 
internal_map_name(struct bpf_object * obj,const char * real_name)1834 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1835 {
1836 	char map_name[BPF_OBJ_NAME_LEN], *p;
1837 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1838 
1839 	/* This is one of the more confusing parts of libbpf for various
1840 	 * reasons, some of which are historical. The original idea for naming
1841 	 * internal names was to include as much of BPF object name prefix as
1842 	 * possible, so that it can be distinguished from similar internal
1843 	 * maps of a different BPF object.
1844 	 * As an example, let's say we have bpf_object named 'my_object_name'
1845 	 * and internal map corresponding to '.rodata' ELF section. The final
1846 	 * map name advertised to user and to the kernel will be
1847 	 * 'my_objec.rodata', taking first 8 characters of object name and
1848 	 * entire 7 characters of '.rodata'.
1849 	 * Somewhat confusingly, if internal map ELF section name is shorter
1850 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1851 	 * for the suffix, even though we only have 4 actual characters, and
1852 	 * resulting map will be called 'my_objec.bss', not even using all 15
1853 	 * characters allowed by the kernel. Oh well, at least the truncated
1854 	 * object name is somewhat consistent in this case. But if the map
1855 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1856 	 * (8 chars) and thus will be left with only first 7 characters of the
1857 	 * object name ('my_obje'). Happy guessing, user, that the final map
1858 	 * name will be "my_obje.kconfig".
1859 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1860 	 * and .data.* data sections, it's possible that ELF section name is
1861 	 * longer than allowed 15 chars, so we now need to be careful to take
1862 	 * only up to 15 first characters of ELF name, taking no BPF object
1863 	 * name characters at all. So '.rodata.abracadabra' will result in
1864 	 * '.rodata.abracad' kernel and user-visible name.
1865 	 * We need to keep this convoluted logic intact for .data, .bss and
1866 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1867 	 * maps we use their ELF names as is, not prepending bpf_object name
1868 	 * in front. We still need to truncate them to 15 characters for the
1869 	 * kernel. Full name can be recovered for such maps by using DATASEC
1870 	 * BTF type associated with such map's value type, though.
1871 	 */
1872 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1873 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1874 
1875 	/* if there are two or more dots in map name, it's a custom dot map */
1876 	if (strchr(real_name + 1, '.') != NULL)
1877 		pfx_len = 0;
1878 	else
1879 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1880 
1881 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1882 		 sfx_len, real_name);
1883 
1884 	/* sanities map name to characters allowed by kernel */
1885 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1886 		if (!isalnum(*p) && *p != '_' && *p != '.')
1887 			*p = '_';
1888 
1889 	return strdup(map_name);
1890 }
1891 
1892 static int
1893 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1894 
1895 /* Internal BPF map is mmap()'able only if at least one of corresponding
1896  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1897  * variable and it's not marked as __hidden (which turns it into, effectively,
1898  * a STATIC variable).
1899  */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1900 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1901 {
1902 	const struct btf_type *t, *vt;
1903 	struct btf_var_secinfo *vsi;
1904 	int i, n;
1905 
1906 	if (!map->btf_value_type_id)
1907 		return false;
1908 
1909 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1910 	if (!btf_is_datasec(t))
1911 		return false;
1912 
1913 	vsi = btf_var_secinfos(t);
1914 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1915 		vt = btf__type_by_id(obj->btf, vsi->type);
1916 		if (!btf_is_var(vt))
1917 			continue;
1918 
1919 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1920 			return true;
1921 	}
1922 
1923 	return false;
1924 }
1925 
1926 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)1927 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1928 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1929 {
1930 	struct bpf_map_def *def;
1931 	struct bpf_map *map;
1932 	size_t mmap_sz;
1933 	int err;
1934 
1935 	map = bpf_object__add_map(obj);
1936 	if (IS_ERR(map))
1937 		return PTR_ERR(map);
1938 
1939 	map->libbpf_type = type;
1940 	map->sec_idx = sec_idx;
1941 	map->sec_offset = 0;
1942 	map->real_name = strdup(real_name);
1943 	map->name = internal_map_name(obj, real_name);
1944 	if (!map->real_name || !map->name) {
1945 		zfree(&map->real_name);
1946 		zfree(&map->name);
1947 		return -ENOMEM;
1948 	}
1949 
1950 	def = &map->def;
1951 	def->type = BPF_MAP_TYPE_ARRAY;
1952 	def->key_size = sizeof(int);
1953 	def->value_size = data_sz;
1954 	def->max_entries = 1;
1955 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1956 		? BPF_F_RDONLY_PROG : 0;
1957 
1958 	/* failures are fine because of maps like .rodata.str1.1 */
1959 	(void) map_fill_btf_type_info(obj, map);
1960 
1961 	if (map_is_mmapable(obj, map))
1962 		def->map_flags |= BPF_F_MMAPABLE;
1963 
1964 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1965 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1966 
1967 	mmap_sz = bpf_map_mmap_sz(map);
1968 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1969 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1970 	if (map->mmaped == MAP_FAILED) {
1971 		err = -errno;
1972 		map->mmaped = NULL;
1973 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
1974 		zfree(&map->real_name);
1975 		zfree(&map->name);
1976 		return err;
1977 	}
1978 
1979 	if (data)
1980 		memcpy(map->mmaped, data, data_sz);
1981 
1982 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1983 	return 0;
1984 }
1985 
bpf_object__init_global_data_maps(struct bpf_object * obj)1986 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1987 {
1988 	struct elf_sec_desc *sec_desc;
1989 	const char *sec_name;
1990 	int err = 0, sec_idx;
1991 
1992 	/*
1993 	 * Populate obj->maps with libbpf internal maps.
1994 	 */
1995 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1996 		sec_desc = &obj->efile.secs[sec_idx];
1997 
1998 		/* Skip recognized sections with size 0. */
1999 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2000 			continue;
2001 
2002 		switch (sec_desc->sec_type) {
2003 		case SEC_DATA:
2004 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2005 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2006 							    sec_name, sec_idx,
2007 							    sec_desc->data->d_buf,
2008 							    sec_desc->data->d_size);
2009 			break;
2010 		case SEC_RODATA:
2011 			obj->has_rodata = true;
2012 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2013 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2014 							    sec_name, sec_idx,
2015 							    sec_desc->data->d_buf,
2016 							    sec_desc->data->d_size);
2017 			break;
2018 		case SEC_BSS:
2019 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2020 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2021 							    sec_name, sec_idx,
2022 							    NULL,
2023 							    sec_desc->data->d_size);
2024 			break;
2025 		default:
2026 			/* skip */
2027 			break;
2028 		}
2029 		if (err)
2030 			return err;
2031 	}
2032 	return 0;
2033 }
2034 
2035 
find_extern_by_name(const struct bpf_object * obj,const void * name)2036 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2037 					       const void *name)
2038 {
2039 	int i;
2040 
2041 	for (i = 0; i < obj->nr_extern; i++) {
2042 		if (strcmp(obj->externs[i].name, name) == 0)
2043 			return &obj->externs[i];
2044 	}
2045 	return NULL;
2046 }
2047 
find_extern_by_name_with_len(const struct bpf_object * obj,const void * name,int len)2048 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2049 							const void *name, int len)
2050 {
2051 	const char *ext_name;
2052 	int i;
2053 
2054 	for (i = 0; i < obj->nr_extern; i++) {
2055 		ext_name = obj->externs[i].name;
2056 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2057 			return &obj->externs[i];
2058 	}
2059 	return NULL;
2060 }
2061 
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)2062 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2063 			      char value)
2064 {
2065 	switch (ext->kcfg.type) {
2066 	case KCFG_BOOL:
2067 		if (value == 'm') {
2068 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2069 				ext->name, value);
2070 			return -EINVAL;
2071 		}
2072 		*(bool *)ext_val = value == 'y' ? true : false;
2073 		break;
2074 	case KCFG_TRISTATE:
2075 		if (value == 'y')
2076 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2077 		else if (value == 'm')
2078 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2079 		else /* value == 'n' */
2080 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2081 		break;
2082 	case KCFG_CHAR:
2083 		*(char *)ext_val = value;
2084 		break;
2085 	case KCFG_UNKNOWN:
2086 	case KCFG_INT:
2087 	case KCFG_CHAR_ARR:
2088 	default:
2089 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2090 			ext->name, value);
2091 		return -EINVAL;
2092 	}
2093 	ext->is_set = true;
2094 	return 0;
2095 }
2096 
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)2097 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2098 			      const char *value)
2099 {
2100 	size_t len;
2101 
2102 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2103 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2104 			ext->name, value);
2105 		return -EINVAL;
2106 	}
2107 
2108 	len = strlen(value);
2109 	if (len < 2 || value[len - 1] != '"') {
2110 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2111 			ext->name, value);
2112 		return -EINVAL;
2113 	}
2114 
2115 	/* strip quotes */
2116 	len -= 2;
2117 	if (len >= ext->kcfg.sz) {
2118 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2119 			ext->name, value, len, ext->kcfg.sz - 1);
2120 		len = ext->kcfg.sz - 1;
2121 	}
2122 	memcpy(ext_val, value + 1, len);
2123 	ext_val[len] = '\0';
2124 	ext->is_set = true;
2125 	return 0;
2126 }
2127 
parse_u64(const char * value,__u64 * res)2128 static int parse_u64(const char *value, __u64 *res)
2129 {
2130 	char *value_end;
2131 	int err;
2132 
2133 	errno = 0;
2134 	*res = strtoull(value, &value_end, 0);
2135 	if (errno) {
2136 		err = -errno;
2137 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2138 		return err;
2139 	}
2140 	if (*value_end) {
2141 		pr_warn("failed to parse '%s' as integer completely\n", value);
2142 		return -EINVAL;
2143 	}
2144 	return 0;
2145 }
2146 
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)2147 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2148 {
2149 	int bit_sz = ext->kcfg.sz * 8;
2150 
2151 	if (ext->kcfg.sz == 8)
2152 		return true;
2153 
2154 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2155 	 * bytes size without any loss of information. If the target integer
2156 	 * is signed, we rely on the following limits of integer type of
2157 	 * Y bits and subsequent transformation:
2158 	 *
2159 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2160 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2161 	 *            0 <= X + 2^(Y-1) <  2^Y
2162 	 *
2163 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2164 	 *  zero.
2165 	 */
2166 	if (ext->kcfg.is_signed)
2167 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2168 	else
2169 		return (v >> bit_sz) == 0;
2170 }
2171 
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)2172 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2173 			      __u64 value)
2174 {
2175 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2176 	    ext->kcfg.type != KCFG_BOOL) {
2177 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2178 			ext->name, (unsigned long long)value);
2179 		return -EINVAL;
2180 	}
2181 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2182 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2183 			ext->name, (unsigned long long)value);
2184 		return -EINVAL;
2185 
2186 	}
2187 	if (!is_kcfg_value_in_range(ext, value)) {
2188 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2189 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2190 		return -ERANGE;
2191 	}
2192 	switch (ext->kcfg.sz) {
2193 	case 1:
2194 		*(__u8 *)ext_val = value;
2195 		break;
2196 	case 2:
2197 		*(__u16 *)ext_val = value;
2198 		break;
2199 	case 4:
2200 		*(__u32 *)ext_val = value;
2201 		break;
2202 	case 8:
2203 		*(__u64 *)ext_val = value;
2204 		break;
2205 	default:
2206 		return -EINVAL;
2207 	}
2208 	ext->is_set = true;
2209 	return 0;
2210 }
2211 
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)2212 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2213 					    char *buf, void *data)
2214 {
2215 	struct extern_desc *ext;
2216 	char *sep, *value;
2217 	int len, err = 0;
2218 	void *ext_val;
2219 	__u64 num;
2220 
2221 	if (!str_has_pfx(buf, "CONFIG_"))
2222 		return 0;
2223 
2224 	sep = strchr(buf, '=');
2225 	if (!sep) {
2226 		pr_warn("failed to parse '%s': no separator\n", buf);
2227 		return -EINVAL;
2228 	}
2229 
2230 	/* Trim ending '\n' */
2231 	len = strlen(buf);
2232 	if (buf[len - 1] == '\n')
2233 		buf[len - 1] = '\0';
2234 	/* Split on '=' and ensure that a value is present. */
2235 	*sep = '\0';
2236 	if (!sep[1]) {
2237 		*sep = '=';
2238 		pr_warn("failed to parse '%s': no value\n", buf);
2239 		return -EINVAL;
2240 	}
2241 
2242 	ext = find_extern_by_name(obj, buf);
2243 	if (!ext || ext->is_set)
2244 		return 0;
2245 
2246 	ext_val = data + ext->kcfg.data_off;
2247 	value = sep + 1;
2248 
2249 	switch (*value) {
2250 	case 'y': case 'n': case 'm':
2251 		err = set_kcfg_value_tri(ext, ext_val, *value);
2252 		break;
2253 	case '"':
2254 		err = set_kcfg_value_str(ext, ext_val, value);
2255 		break;
2256 	default:
2257 		/* assume integer */
2258 		err = parse_u64(value, &num);
2259 		if (err) {
2260 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2261 			return err;
2262 		}
2263 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2264 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2265 			return -EINVAL;
2266 		}
2267 		err = set_kcfg_value_num(ext, ext_val, num);
2268 		break;
2269 	}
2270 	if (err)
2271 		return err;
2272 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2273 	return 0;
2274 }
2275 
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)2276 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2277 {
2278 	char buf[PATH_MAX];
2279 	struct utsname uts;
2280 	int len, err = 0;
2281 	gzFile file;
2282 
2283 	uname(&uts);
2284 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2285 	if (len < 0)
2286 		return -EINVAL;
2287 	else if (len >= PATH_MAX)
2288 		return -ENAMETOOLONG;
2289 
2290 	/* gzopen also accepts uncompressed files. */
2291 	file = gzopen(buf, "re");
2292 	if (!file)
2293 		file = gzopen("/proc/config.gz", "re");
2294 
2295 	if (!file) {
2296 		pr_warn("failed to open system Kconfig\n");
2297 		return -ENOENT;
2298 	}
2299 
2300 	while (gzgets(file, buf, sizeof(buf))) {
2301 		err = bpf_object__process_kconfig_line(obj, buf, data);
2302 		if (err) {
2303 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2304 				buf, errstr(err));
2305 			goto out;
2306 		}
2307 	}
2308 
2309 out:
2310 	gzclose(file);
2311 	return err;
2312 }
2313 
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2314 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2315 					const char *config, void *data)
2316 {
2317 	char buf[PATH_MAX];
2318 	int err = 0;
2319 	FILE *file;
2320 
2321 	file = fmemopen((void *)config, strlen(config), "r");
2322 	if (!file) {
2323 		err = -errno;
2324 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2325 		return err;
2326 	}
2327 
2328 	while (fgets(buf, sizeof(buf), file)) {
2329 		err = bpf_object__process_kconfig_line(obj, buf, data);
2330 		if (err) {
2331 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2332 				buf, errstr(err));
2333 			break;
2334 		}
2335 	}
2336 
2337 	fclose(file);
2338 	return err;
2339 }
2340 
bpf_object__init_kconfig_map(struct bpf_object * obj)2341 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2342 {
2343 	struct extern_desc *last_ext = NULL, *ext;
2344 	size_t map_sz;
2345 	int i, err;
2346 
2347 	for (i = 0; i < obj->nr_extern; i++) {
2348 		ext = &obj->externs[i];
2349 		if (ext->type == EXT_KCFG)
2350 			last_ext = ext;
2351 	}
2352 
2353 	if (!last_ext)
2354 		return 0;
2355 
2356 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2357 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2358 					    ".kconfig", obj->efile.symbols_shndx,
2359 					    NULL, map_sz);
2360 	if (err)
2361 		return err;
2362 
2363 	obj->kconfig_map_idx = obj->nr_maps - 1;
2364 
2365 	return 0;
2366 }
2367 
2368 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2369 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2370 {
2371 	const struct btf_type *t = btf__type_by_id(btf, id);
2372 
2373 	if (res_id)
2374 		*res_id = id;
2375 
2376 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2377 		if (res_id)
2378 			*res_id = t->type;
2379 		t = btf__type_by_id(btf, t->type);
2380 	}
2381 
2382 	return t;
2383 }
2384 
2385 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2386 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2387 {
2388 	const struct btf_type *t;
2389 
2390 	t = skip_mods_and_typedefs(btf, id, NULL);
2391 	if (!btf_is_ptr(t))
2392 		return NULL;
2393 
2394 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2395 
2396 	return btf_is_func_proto(t) ? t : NULL;
2397 }
2398 
__btf_kind_str(__u16 kind)2399 static const char *__btf_kind_str(__u16 kind)
2400 {
2401 	switch (kind) {
2402 	case BTF_KIND_UNKN: return "void";
2403 	case BTF_KIND_INT: return "int";
2404 	case BTF_KIND_PTR: return "ptr";
2405 	case BTF_KIND_ARRAY: return "array";
2406 	case BTF_KIND_STRUCT: return "struct";
2407 	case BTF_KIND_UNION: return "union";
2408 	case BTF_KIND_ENUM: return "enum";
2409 	case BTF_KIND_FWD: return "fwd";
2410 	case BTF_KIND_TYPEDEF: return "typedef";
2411 	case BTF_KIND_VOLATILE: return "volatile";
2412 	case BTF_KIND_CONST: return "const";
2413 	case BTF_KIND_RESTRICT: return "restrict";
2414 	case BTF_KIND_FUNC: return "func";
2415 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2416 	case BTF_KIND_VAR: return "var";
2417 	case BTF_KIND_DATASEC: return "datasec";
2418 	case BTF_KIND_FLOAT: return "float";
2419 	case BTF_KIND_DECL_TAG: return "decl_tag";
2420 	case BTF_KIND_TYPE_TAG: return "type_tag";
2421 	case BTF_KIND_ENUM64: return "enum64";
2422 	default: return "unknown";
2423 	}
2424 }
2425 
btf_kind_str(const struct btf_type * t)2426 const char *btf_kind_str(const struct btf_type *t)
2427 {
2428 	return __btf_kind_str(btf_kind(t));
2429 }
2430 
2431 /*
2432  * Fetch integer attribute of BTF map definition. Such attributes are
2433  * represented using a pointer to an array, in which dimensionality of array
2434  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2435  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2436  * type definition, while using only sizeof(void *) space in ELF data section.
2437  */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2438 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2439 			      const struct btf_member *m, __u32 *res)
2440 {
2441 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2442 	const char *name = btf__name_by_offset(btf, m->name_off);
2443 	const struct btf_array *arr_info;
2444 	const struct btf_type *arr_t;
2445 
2446 	if (!btf_is_ptr(t)) {
2447 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2448 			map_name, name, btf_kind_str(t));
2449 		return false;
2450 	}
2451 
2452 	arr_t = btf__type_by_id(btf, t->type);
2453 	if (!arr_t) {
2454 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2455 			map_name, name, t->type);
2456 		return false;
2457 	}
2458 	if (!btf_is_array(arr_t)) {
2459 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2460 			map_name, name, btf_kind_str(arr_t));
2461 		return false;
2462 	}
2463 	arr_info = btf_array(arr_t);
2464 	*res = arr_info->nelems;
2465 	return true;
2466 }
2467 
get_map_field_long(const char * map_name,const struct btf * btf,const struct btf_member * m,__u64 * res)2468 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2469 			       const struct btf_member *m, __u64 *res)
2470 {
2471 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2472 	const char *name = btf__name_by_offset(btf, m->name_off);
2473 
2474 	if (btf_is_ptr(t)) {
2475 		__u32 res32;
2476 		bool ret;
2477 
2478 		ret = get_map_field_int(map_name, btf, m, &res32);
2479 		if (ret)
2480 			*res = (__u64)res32;
2481 		return ret;
2482 	}
2483 
2484 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2485 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2486 			map_name, name, btf_kind_str(t));
2487 		return false;
2488 	}
2489 
2490 	if (btf_vlen(t) != 1) {
2491 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2492 			map_name, name);
2493 		return false;
2494 	}
2495 
2496 	if (btf_is_enum(t)) {
2497 		const struct btf_enum *e = btf_enum(t);
2498 
2499 		*res = e->val;
2500 	} else {
2501 		const struct btf_enum64 *e = btf_enum64(t);
2502 
2503 		*res = btf_enum64_value(e);
2504 	}
2505 	return true;
2506 }
2507 
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2508 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2509 {
2510 	int len;
2511 
2512 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2513 	if (len < 0)
2514 		return -EINVAL;
2515 	if (len >= buf_sz)
2516 		return -ENAMETOOLONG;
2517 
2518 	return 0;
2519 }
2520 
build_map_pin_path(struct bpf_map * map,const char * path)2521 static int build_map_pin_path(struct bpf_map *map, const char *path)
2522 {
2523 	char buf[PATH_MAX];
2524 	int err;
2525 
2526 	if (!path)
2527 		path = BPF_FS_DEFAULT_PATH;
2528 
2529 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2530 	if (err)
2531 		return err;
2532 
2533 	return bpf_map__set_pin_path(map, buf);
2534 }
2535 
2536 /* should match definition in bpf_helpers.h */
2537 enum libbpf_pin_type {
2538 	LIBBPF_PIN_NONE,
2539 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2540 	LIBBPF_PIN_BY_NAME,
2541 };
2542 
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)2543 int parse_btf_map_def(const char *map_name, struct btf *btf,
2544 		      const struct btf_type *def_t, bool strict,
2545 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2546 {
2547 	const struct btf_type *t;
2548 	const struct btf_member *m;
2549 	bool is_inner = inner_def == NULL;
2550 	int vlen, i;
2551 
2552 	vlen = btf_vlen(def_t);
2553 	m = btf_members(def_t);
2554 	for (i = 0; i < vlen; i++, m++) {
2555 		const char *name = btf__name_by_offset(btf, m->name_off);
2556 
2557 		if (!name) {
2558 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2559 			return -EINVAL;
2560 		}
2561 		if (strcmp(name, "type") == 0) {
2562 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2563 				return -EINVAL;
2564 			map_def->parts |= MAP_DEF_MAP_TYPE;
2565 		} else if (strcmp(name, "max_entries") == 0) {
2566 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2567 				return -EINVAL;
2568 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2569 		} else if (strcmp(name, "map_flags") == 0) {
2570 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2571 				return -EINVAL;
2572 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2573 		} else if (strcmp(name, "numa_node") == 0) {
2574 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2575 				return -EINVAL;
2576 			map_def->parts |= MAP_DEF_NUMA_NODE;
2577 		} else if (strcmp(name, "key_size") == 0) {
2578 			__u32 sz;
2579 
2580 			if (!get_map_field_int(map_name, btf, m, &sz))
2581 				return -EINVAL;
2582 			if (map_def->key_size && map_def->key_size != sz) {
2583 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2584 					map_name, map_def->key_size, sz);
2585 				return -EINVAL;
2586 			}
2587 			map_def->key_size = sz;
2588 			map_def->parts |= MAP_DEF_KEY_SIZE;
2589 		} else if (strcmp(name, "key") == 0) {
2590 			__s64 sz;
2591 
2592 			t = btf__type_by_id(btf, m->type);
2593 			if (!t) {
2594 				pr_warn("map '%s': key type [%d] not found.\n",
2595 					map_name, m->type);
2596 				return -EINVAL;
2597 			}
2598 			if (!btf_is_ptr(t)) {
2599 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2600 					map_name, btf_kind_str(t));
2601 				return -EINVAL;
2602 			}
2603 			sz = btf__resolve_size(btf, t->type);
2604 			if (sz < 0) {
2605 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2606 					map_name, t->type, (ssize_t)sz);
2607 				return sz;
2608 			}
2609 			if (map_def->key_size && map_def->key_size != sz) {
2610 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2611 					map_name, map_def->key_size, (ssize_t)sz);
2612 				return -EINVAL;
2613 			}
2614 			map_def->key_size = sz;
2615 			map_def->key_type_id = t->type;
2616 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2617 		} else if (strcmp(name, "value_size") == 0) {
2618 			__u32 sz;
2619 
2620 			if (!get_map_field_int(map_name, btf, m, &sz))
2621 				return -EINVAL;
2622 			if (map_def->value_size && map_def->value_size != sz) {
2623 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2624 					map_name, map_def->value_size, sz);
2625 				return -EINVAL;
2626 			}
2627 			map_def->value_size = sz;
2628 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2629 		} else if (strcmp(name, "value") == 0) {
2630 			__s64 sz;
2631 
2632 			t = btf__type_by_id(btf, m->type);
2633 			if (!t) {
2634 				pr_warn("map '%s': value type [%d] not found.\n",
2635 					map_name, m->type);
2636 				return -EINVAL;
2637 			}
2638 			if (!btf_is_ptr(t)) {
2639 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2640 					map_name, btf_kind_str(t));
2641 				return -EINVAL;
2642 			}
2643 			sz = btf__resolve_size(btf, t->type);
2644 			if (sz < 0) {
2645 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2646 					map_name, t->type, (ssize_t)sz);
2647 				return sz;
2648 			}
2649 			if (map_def->value_size && map_def->value_size != sz) {
2650 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2651 					map_name, map_def->value_size, (ssize_t)sz);
2652 				return -EINVAL;
2653 			}
2654 			map_def->value_size = sz;
2655 			map_def->value_type_id = t->type;
2656 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2657 		}
2658 		else if (strcmp(name, "values") == 0) {
2659 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2660 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2661 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2662 			char inner_map_name[128];
2663 			int err;
2664 
2665 			if (is_inner) {
2666 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2667 					map_name);
2668 				return -ENOTSUP;
2669 			}
2670 			if (i != vlen - 1) {
2671 				pr_warn("map '%s': '%s' member should be last.\n",
2672 					map_name, name);
2673 				return -EINVAL;
2674 			}
2675 			if (!is_map_in_map && !is_prog_array) {
2676 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2677 					map_name);
2678 				return -ENOTSUP;
2679 			}
2680 			if (map_def->value_size && map_def->value_size != 4) {
2681 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2682 					map_name, map_def->value_size);
2683 				return -EINVAL;
2684 			}
2685 			map_def->value_size = 4;
2686 			t = btf__type_by_id(btf, m->type);
2687 			if (!t) {
2688 				pr_warn("map '%s': %s type [%d] not found.\n",
2689 					map_name, desc, m->type);
2690 				return -EINVAL;
2691 			}
2692 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2693 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2694 					map_name, desc);
2695 				return -EINVAL;
2696 			}
2697 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2698 			if (!btf_is_ptr(t)) {
2699 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2700 					map_name, desc, btf_kind_str(t));
2701 				return -EINVAL;
2702 			}
2703 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2704 			if (is_prog_array) {
2705 				if (!btf_is_func_proto(t)) {
2706 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2707 						map_name, btf_kind_str(t));
2708 					return -EINVAL;
2709 				}
2710 				continue;
2711 			}
2712 			if (!btf_is_struct(t)) {
2713 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2714 					map_name, btf_kind_str(t));
2715 				return -EINVAL;
2716 			}
2717 
2718 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2719 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2720 			if (err)
2721 				return err;
2722 
2723 			map_def->parts |= MAP_DEF_INNER_MAP;
2724 		} else if (strcmp(name, "pinning") == 0) {
2725 			__u32 val;
2726 
2727 			if (is_inner) {
2728 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2729 				return -EINVAL;
2730 			}
2731 			if (!get_map_field_int(map_name, btf, m, &val))
2732 				return -EINVAL;
2733 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2734 				pr_warn("map '%s': invalid pinning value %u.\n",
2735 					map_name, val);
2736 				return -EINVAL;
2737 			}
2738 			map_def->pinning = val;
2739 			map_def->parts |= MAP_DEF_PINNING;
2740 		} else if (strcmp(name, "map_extra") == 0) {
2741 			__u64 map_extra;
2742 
2743 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2744 				return -EINVAL;
2745 			map_def->map_extra = map_extra;
2746 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2747 		} else {
2748 			if (strict) {
2749 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2750 				return -ENOTSUP;
2751 			}
2752 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2753 		}
2754 	}
2755 
2756 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2757 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2758 		return -EINVAL;
2759 	}
2760 
2761 	return 0;
2762 }
2763 
adjust_ringbuf_sz(size_t sz)2764 static size_t adjust_ringbuf_sz(size_t sz)
2765 {
2766 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2767 	__u32 mul;
2768 
2769 	/* if user forgot to set any size, make sure they see error */
2770 	if (sz == 0)
2771 		return 0;
2772 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2773 	 * a power-of-2 multiple of kernel's page size. If user diligently
2774 	 * satisified these conditions, pass the size through.
2775 	 */
2776 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2777 		return sz;
2778 
2779 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2780 	 * user-set size to satisfy both user size request and kernel
2781 	 * requirements and substitute correct max_entries for map creation.
2782 	 */
2783 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2784 		if (mul * page_sz > sz)
2785 			return mul * page_sz;
2786 	}
2787 
2788 	/* if it's impossible to satisfy the conditions (i.e., user size is
2789 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2790 	 * page_size) then just return original size and let kernel reject it
2791 	 */
2792 	return sz;
2793 }
2794 
map_is_ringbuf(const struct bpf_map * map)2795 static bool map_is_ringbuf(const struct bpf_map *map)
2796 {
2797 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2798 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2799 }
2800 
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2801 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2802 {
2803 	map->def.type = def->map_type;
2804 	map->def.key_size = def->key_size;
2805 	map->def.value_size = def->value_size;
2806 	map->def.max_entries = def->max_entries;
2807 	map->def.map_flags = def->map_flags;
2808 	map->map_extra = def->map_extra;
2809 
2810 	map->numa_node = def->numa_node;
2811 	map->btf_key_type_id = def->key_type_id;
2812 	map->btf_value_type_id = def->value_type_id;
2813 
2814 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2815 	if (map_is_ringbuf(map))
2816 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2817 
2818 	if (def->parts & MAP_DEF_MAP_TYPE)
2819 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2820 
2821 	if (def->parts & MAP_DEF_KEY_TYPE)
2822 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2823 			 map->name, def->key_type_id, def->key_size);
2824 	else if (def->parts & MAP_DEF_KEY_SIZE)
2825 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2826 
2827 	if (def->parts & MAP_DEF_VALUE_TYPE)
2828 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2829 			 map->name, def->value_type_id, def->value_size);
2830 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2831 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2832 
2833 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2834 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2835 	if (def->parts & MAP_DEF_MAP_FLAGS)
2836 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2837 	if (def->parts & MAP_DEF_MAP_EXTRA)
2838 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2839 			 (unsigned long long)def->map_extra);
2840 	if (def->parts & MAP_DEF_PINNING)
2841 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2842 	if (def->parts & MAP_DEF_NUMA_NODE)
2843 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2844 
2845 	if (def->parts & MAP_DEF_INNER_MAP)
2846 		pr_debug("map '%s': found inner map definition.\n", map->name);
2847 }
2848 
btf_var_linkage_str(__u32 linkage)2849 static const char *btf_var_linkage_str(__u32 linkage)
2850 {
2851 	switch (linkage) {
2852 	case BTF_VAR_STATIC: return "static";
2853 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2854 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2855 	default: return "unknown";
2856 	}
2857 }
2858 
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)2859 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2860 					 const struct btf_type *sec,
2861 					 int var_idx, int sec_idx,
2862 					 const Elf_Data *data, bool strict,
2863 					 const char *pin_root_path)
2864 {
2865 	struct btf_map_def map_def = {}, inner_def = {};
2866 	const struct btf_type *var, *def;
2867 	const struct btf_var_secinfo *vi;
2868 	const struct btf_var *var_extra;
2869 	const char *map_name;
2870 	struct bpf_map *map;
2871 	int err;
2872 
2873 	vi = btf_var_secinfos(sec) + var_idx;
2874 	var = btf__type_by_id(obj->btf, vi->type);
2875 	var_extra = btf_var(var);
2876 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2877 
2878 	if (map_name == NULL || map_name[0] == '\0') {
2879 		pr_warn("map #%d: empty name.\n", var_idx);
2880 		return -EINVAL;
2881 	}
2882 	if ((__u64)vi->offset + vi->size > data->d_size) {
2883 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2884 		return -EINVAL;
2885 	}
2886 	if (!btf_is_var(var)) {
2887 		pr_warn("map '%s': unexpected var kind %s.\n",
2888 			map_name, btf_kind_str(var));
2889 		return -EINVAL;
2890 	}
2891 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2892 		pr_warn("map '%s': unsupported map linkage %s.\n",
2893 			map_name, btf_var_linkage_str(var_extra->linkage));
2894 		return -EOPNOTSUPP;
2895 	}
2896 
2897 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2898 	if (!btf_is_struct(def)) {
2899 		pr_warn("map '%s': unexpected def kind %s.\n",
2900 			map_name, btf_kind_str(var));
2901 		return -EINVAL;
2902 	}
2903 	if (def->size > vi->size) {
2904 		pr_warn("map '%s': invalid def size.\n", map_name);
2905 		return -EINVAL;
2906 	}
2907 
2908 	map = bpf_object__add_map(obj);
2909 	if (IS_ERR(map))
2910 		return PTR_ERR(map);
2911 	map->name = strdup(map_name);
2912 	if (!map->name) {
2913 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2914 		return -ENOMEM;
2915 	}
2916 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2917 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2918 	map->sec_idx = sec_idx;
2919 	map->sec_offset = vi->offset;
2920 	map->btf_var_idx = var_idx;
2921 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2922 		 map_name, map->sec_idx, map->sec_offset);
2923 
2924 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2925 	if (err)
2926 		return err;
2927 
2928 	fill_map_from_def(map, &map_def);
2929 
2930 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2931 		err = build_map_pin_path(map, pin_root_path);
2932 		if (err) {
2933 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2934 			return err;
2935 		}
2936 	}
2937 
2938 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2939 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2940 		if (!map->inner_map)
2941 			return -ENOMEM;
2942 		map->inner_map->fd = create_placeholder_fd();
2943 		if (map->inner_map->fd < 0)
2944 			return map->inner_map->fd;
2945 		map->inner_map->sec_idx = sec_idx;
2946 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2947 		if (!map->inner_map->name)
2948 			return -ENOMEM;
2949 		sprintf(map->inner_map->name, "%s.inner", map_name);
2950 
2951 		fill_map_from_def(map->inner_map, &inner_def);
2952 	}
2953 
2954 	err = map_fill_btf_type_info(obj, map);
2955 	if (err)
2956 		return err;
2957 
2958 	return 0;
2959 }
2960 
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)2961 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2962 			       const char *sec_name, int sec_idx,
2963 			       void *data, size_t data_sz)
2964 {
2965 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2966 	size_t mmap_sz;
2967 
2968 	mmap_sz = bpf_map_mmap_sz(map);
2969 	if (roundup(data_sz, page_sz) > mmap_sz) {
2970 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2971 			sec_name, mmap_sz, data_sz);
2972 		return -E2BIG;
2973 	}
2974 
2975 	obj->arena_data = malloc(data_sz);
2976 	if (!obj->arena_data)
2977 		return -ENOMEM;
2978 	memcpy(obj->arena_data, data, data_sz);
2979 	obj->arena_data_sz = data_sz;
2980 
2981 	/* make bpf_map__init_value() work for ARENA maps */
2982 	map->mmaped = obj->arena_data;
2983 
2984 	return 0;
2985 }
2986 
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2987 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2988 					  const char *pin_root_path)
2989 {
2990 	const struct btf_type *sec = NULL;
2991 	int nr_types, i, vlen, err;
2992 	const struct btf_type *t;
2993 	const char *name;
2994 	Elf_Data *data;
2995 	Elf_Scn *scn;
2996 
2997 	if (obj->efile.btf_maps_shndx < 0)
2998 		return 0;
2999 
3000 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3001 	data = elf_sec_data(obj, scn);
3002 	if (!scn || !data) {
3003 		pr_warn("elf: failed to get %s map definitions for %s\n",
3004 			MAPS_ELF_SEC, obj->path);
3005 		return -EINVAL;
3006 	}
3007 
3008 	nr_types = btf__type_cnt(obj->btf);
3009 	for (i = 1; i < nr_types; i++) {
3010 		t = btf__type_by_id(obj->btf, i);
3011 		if (!btf_is_datasec(t))
3012 			continue;
3013 		name = btf__name_by_offset(obj->btf, t->name_off);
3014 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3015 			sec = t;
3016 			obj->efile.btf_maps_sec_btf_id = i;
3017 			break;
3018 		}
3019 	}
3020 
3021 	if (!sec) {
3022 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3023 		return -ENOENT;
3024 	}
3025 
3026 	vlen = btf_vlen(sec);
3027 	for (i = 0; i < vlen; i++) {
3028 		err = bpf_object__init_user_btf_map(obj, sec, i,
3029 						    obj->efile.btf_maps_shndx,
3030 						    data, strict,
3031 						    pin_root_path);
3032 		if (err)
3033 			return err;
3034 	}
3035 
3036 	for (i = 0; i < obj->nr_maps; i++) {
3037 		struct bpf_map *map = &obj->maps[i];
3038 
3039 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3040 			continue;
3041 
3042 		if (obj->arena_map_idx >= 0) {
3043 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3044 				map->name, obj->maps[obj->arena_map_idx].name);
3045 			return -EINVAL;
3046 		}
3047 		obj->arena_map_idx = i;
3048 
3049 		if (obj->efile.arena_data) {
3050 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3051 						  obj->efile.arena_data->d_buf,
3052 						  obj->efile.arena_data->d_size);
3053 			if (err)
3054 				return err;
3055 		}
3056 	}
3057 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3058 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3059 			ARENA_SEC);
3060 		return -ENOENT;
3061 	}
3062 
3063 	return 0;
3064 }
3065 
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)3066 static int bpf_object__init_maps(struct bpf_object *obj,
3067 				 const struct bpf_object_open_opts *opts)
3068 {
3069 	const char *pin_root_path;
3070 	bool strict;
3071 	int err = 0;
3072 
3073 	strict = !OPTS_GET(opts, relaxed_maps, false);
3074 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3075 
3076 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3077 	err = err ?: bpf_object__init_global_data_maps(obj);
3078 	err = err ?: bpf_object__init_kconfig_map(obj);
3079 	err = err ?: bpf_object_init_struct_ops(obj);
3080 
3081 	return err;
3082 }
3083 
section_have_execinstr(struct bpf_object * obj,int idx)3084 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3085 {
3086 	Elf64_Shdr *sh;
3087 
3088 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3089 	if (!sh)
3090 		return false;
3091 
3092 	return sh->sh_flags & SHF_EXECINSTR;
3093 }
3094 
starts_with_qmark(const char * s)3095 static bool starts_with_qmark(const char *s)
3096 {
3097 	return s && s[0] == '?';
3098 }
3099 
btf_needs_sanitization(struct bpf_object * obj)3100 static bool btf_needs_sanitization(struct bpf_object *obj)
3101 {
3102 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3103 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3104 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3105 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3106 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3107 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3108 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3109 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3110 
3111 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3112 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3113 }
3114 
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)3115 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3116 {
3117 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3118 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3119 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3120 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3121 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3122 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3123 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3124 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3125 	int enum64_placeholder_id = 0;
3126 	struct btf_type *t;
3127 	int i, j, vlen;
3128 
3129 	for (i = 1; i < btf__type_cnt(btf); i++) {
3130 		t = (struct btf_type *)btf__type_by_id(btf, i);
3131 
3132 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3133 			/* replace VAR/DECL_TAG with INT */
3134 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3135 			/*
3136 			 * using size = 1 is the safest choice, 4 will be too
3137 			 * big and cause kernel BTF validation failure if
3138 			 * original variable took less than 4 bytes
3139 			 */
3140 			t->size = 1;
3141 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3142 		} else if (!has_datasec && btf_is_datasec(t)) {
3143 			/* replace DATASEC with STRUCT */
3144 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3145 			struct btf_member *m = btf_members(t);
3146 			struct btf_type *vt;
3147 			char *name;
3148 
3149 			name = (char *)btf__name_by_offset(btf, t->name_off);
3150 			while (*name) {
3151 				if (*name == '.' || *name == '?')
3152 					*name = '_';
3153 				name++;
3154 			}
3155 
3156 			vlen = btf_vlen(t);
3157 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3158 			for (j = 0; j < vlen; j++, v++, m++) {
3159 				/* order of field assignments is important */
3160 				m->offset = v->offset * 8;
3161 				m->type = v->type;
3162 				/* preserve variable name as member name */
3163 				vt = (void *)btf__type_by_id(btf, v->type);
3164 				m->name_off = vt->name_off;
3165 			}
3166 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3167 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3168 			/* replace '?' prefix with '_' for DATASEC names */
3169 			char *name;
3170 
3171 			name = (char *)btf__name_by_offset(btf, t->name_off);
3172 			if (name[0] == '?')
3173 				name[0] = '_';
3174 		} else if (!has_func && btf_is_func_proto(t)) {
3175 			/* replace FUNC_PROTO with ENUM */
3176 			vlen = btf_vlen(t);
3177 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3178 			t->size = sizeof(__u32); /* kernel enforced */
3179 		} else if (!has_func && btf_is_func(t)) {
3180 			/* replace FUNC with TYPEDEF */
3181 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3182 		} else if (!has_func_global && btf_is_func(t)) {
3183 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3184 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3185 		} else if (!has_float && btf_is_float(t)) {
3186 			/* replace FLOAT with an equally-sized empty STRUCT;
3187 			 * since C compilers do not accept e.g. "float" as a
3188 			 * valid struct name, make it anonymous
3189 			 */
3190 			t->name_off = 0;
3191 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3192 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3193 			/* replace TYPE_TAG with a CONST */
3194 			t->name_off = 0;
3195 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3196 		} else if (!has_enum64 && btf_is_enum(t)) {
3197 			/* clear the kflag */
3198 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3199 		} else if (!has_enum64 && btf_is_enum64(t)) {
3200 			/* replace ENUM64 with a union */
3201 			struct btf_member *m;
3202 
3203 			if (enum64_placeholder_id == 0) {
3204 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3205 				if (enum64_placeholder_id < 0)
3206 					return enum64_placeholder_id;
3207 
3208 				t = (struct btf_type *)btf__type_by_id(btf, i);
3209 			}
3210 
3211 			m = btf_members(t);
3212 			vlen = btf_vlen(t);
3213 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3214 			for (j = 0; j < vlen; j++, m++) {
3215 				m->type = enum64_placeholder_id;
3216 				m->offset = 0;
3217 			}
3218 		}
3219 	}
3220 
3221 	return 0;
3222 }
3223 
libbpf_needs_btf(const struct bpf_object * obj)3224 static bool libbpf_needs_btf(const struct bpf_object *obj)
3225 {
3226 	return obj->efile.btf_maps_shndx >= 0 ||
3227 	       obj->efile.has_st_ops ||
3228 	       obj->nr_extern > 0;
3229 }
3230 
kernel_needs_btf(const struct bpf_object * obj)3231 static bool kernel_needs_btf(const struct bpf_object *obj)
3232 {
3233 	return obj->efile.has_st_ops;
3234 }
3235 
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)3236 static int bpf_object__init_btf(struct bpf_object *obj,
3237 				Elf_Data *btf_data,
3238 				Elf_Data *btf_ext_data)
3239 {
3240 	int err = -ENOENT;
3241 
3242 	if (btf_data) {
3243 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3244 		err = libbpf_get_error(obj->btf);
3245 		if (err) {
3246 			obj->btf = NULL;
3247 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3248 			goto out;
3249 		}
3250 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3251 		btf__set_pointer_size(obj->btf, 8);
3252 	}
3253 	if (btf_ext_data) {
3254 		struct btf_ext_info *ext_segs[3];
3255 		int seg_num, sec_num;
3256 
3257 		if (!obj->btf) {
3258 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3259 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3260 			goto out;
3261 		}
3262 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3263 		err = libbpf_get_error(obj->btf_ext);
3264 		if (err) {
3265 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3266 				BTF_EXT_ELF_SEC, errstr(err));
3267 			obj->btf_ext = NULL;
3268 			goto out;
3269 		}
3270 
3271 		/* setup .BTF.ext to ELF section mapping */
3272 		ext_segs[0] = &obj->btf_ext->func_info;
3273 		ext_segs[1] = &obj->btf_ext->line_info;
3274 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3275 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3276 			struct btf_ext_info *seg = ext_segs[seg_num];
3277 			const struct btf_ext_info_sec *sec;
3278 			const char *sec_name;
3279 			Elf_Scn *scn;
3280 
3281 			if (seg->sec_cnt == 0)
3282 				continue;
3283 
3284 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3285 			if (!seg->sec_idxs) {
3286 				err = -ENOMEM;
3287 				goto out;
3288 			}
3289 
3290 			sec_num = 0;
3291 			for_each_btf_ext_sec(seg, sec) {
3292 				/* preventively increment index to avoid doing
3293 				 * this before every continue below
3294 				 */
3295 				sec_num++;
3296 
3297 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3298 				if (str_is_empty(sec_name))
3299 					continue;
3300 				scn = elf_sec_by_name(obj, sec_name);
3301 				if (!scn)
3302 					continue;
3303 
3304 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3305 			}
3306 		}
3307 	}
3308 out:
3309 	if (err && libbpf_needs_btf(obj)) {
3310 		pr_warn("BTF is required, but is missing or corrupted.\n");
3311 		return err;
3312 	}
3313 	return 0;
3314 }
3315 
compare_vsi_off(const void * _a,const void * _b)3316 static int compare_vsi_off(const void *_a, const void *_b)
3317 {
3318 	const struct btf_var_secinfo *a = _a;
3319 	const struct btf_var_secinfo *b = _b;
3320 
3321 	return a->offset - b->offset;
3322 }
3323 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)3324 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3325 			     struct btf_type *t)
3326 {
3327 	__u32 size = 0, i, vars = btf_vlen(t);
3328 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3329 	struct btf_var_secinfo *vsi;
3330 	bool fixup_offsets = false;
3331 	int err;
3332 
3333 	if (!sec_name) {
3334 		pr_debug("No name found in string section for DATASEC kind.\n");
3335 		return -ENOENT;
3336 	}
3337 
3338 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3339 	 * variable offsets set at the previous step. Further, not every
3340 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3341 	 * all fixups altogether for such sections and go straight to sorting
3342 	 * VARs within their DATASEC.
3343 	 */
3344 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3345 		goto sort_vars;
3346 
3347 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3348 	 * fix this up. But BPF static linker already fixes this up and fills
3349 	 * all the sizes and offsets during static linking. So this step has
3350 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3351 	 * non-extern DATASEC, so the variable fixup loop below handles both
3352 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3353 	 * symbol matching just once.
3354 	 */
3355 	if (t->size == 0) {
3356 		err = find_elf_sec_sz(obj, sec_name, &size);
3357 		if (err || !size) {
3358 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3359 				 sec_name, size, errstr(err));
3360 			return -ENOENT;
3361 		}
3362 
3363 		t->size = size;
3364 		fixup_offsets = true;
3365 	}
3366 
3367 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3368 		const struct btf_type *t_var;
3369 		struct btf_var *var;
3370 		const char *var_name;
3371 		Elf64_Sym *sym;
3372 
3373 		t_var = btf__type_by_id(btf, vsi->type);
3374 		if (!t_var || !btf_is_var(t_var)) {
3375 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3376 			return -EINVAL;
3377 		}
3378 
3379 		var = btf_var(t_var);
3380 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3381 			continue;
3382 
3383 		var_name = btf__name_by_offset(btf, t_var->name_off);
3384 		if (!var_name) {
3385 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3386 				 sec_name, i);
3387 			return -ENOENT;
3388 		}
3389 
3390 		sym = find_elf_var_sym(obj, var_name);
3391 		if (IS_ERR(sym)) {
3392 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3393 				 sec_name, var_name);
3394 			return -ENOENT;
3395 		}
3396 
3397 		if (fixup_offsets)
3398 			vsi->offset = sym->st_value;
3399 
3400 		/* if variable is a global/weak symbol, but has restricted
3401 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3402 		 * as static. This follows similar logic for functions (BPF
3403 		 * subprogs) and influences libbpf's further decisions about
3404 		 * whether to make global data BPF array maps as
3405 		 * BPF_F_MMAPABLE.
3406 		 */
3407 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3408 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3409 			var->linkage = BTF_VAR_STATIC;
3410 	}
3411 
3412 sort_vars:
3413 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3414 	return 0;
3415 }
3416 
bpf_object_fixup_btf(struct bpf_object * obj)3417 static int bpf_object_fixup_btf(struct bpf_object *obj)
3418 {
3419 	int i, n, err = 0;
3420 
3421 	if (!obj->btf)
3422 		return 0;
3423 
3424 	n = btf__type_cnt(obj->btf);
3425 	for (i = 1; i < n; i++) {
3426 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3427 
3428 		/* Loader needs to fix up some of the things compiler
3429 		 * couldn't get its hands on while emitting BTF. This
3430 		 * is section size and global variable offset. We use
3431 		 * the info from the ELF itself for this purpose.
3432 		 */
3433 		if (btf_is_datasec(t)) {
3434 			err = btf_fixup_datasec(obj, obj->btf, t);
3435 			if (err)
3436 				return err;
3437 		}
3438 	}
3439 
3440 	return 0;
3441 }
3442 
prog_needs_vmlinux_btf(struct bpf_program * prog)3443 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3444 {
3445 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3446 	    prog->type == BPF_PROG_TYPE_LSM)
3447 		return true;
3448 
3449 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3450 	 * also need vmlinux BTF
3451 	 */
3452 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3453 		return true;
3454 
3455 	return false;
3456 }
3457 
map_needs_vmlinux_btf(struct bpf_map * map)3458 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3459 {
3460 	return bpf_map__is_struct_ops(map);
3461 }
3462 
obj_needs_vmlinux_btf(const struct bpf_object * obj)3463 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3464 {
3465 	struct bpf_program *prog;
3466 	struct bpf_map *map;
3467 	int i;
3468 
3469 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3470 	 * is not specified
3471 	 */
3472 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3473 		return true;
3474 
3475 	/* Support for typed ksyms needs kernel BTF */
3476 	for (i = 0; i < obj->nr_extern; i++) {
3477 		const struct extern_desc *ext;
3478 
3479 		ext = &obj->externs[i];
3480 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3481 			return true;
3482 	}
3483 
3484 	bpf_object__for_each_program(prog, obj) {
3485 		if (!prog->autoload)
3486 			continue;
3487 		if (prog_needs_vmlinux_btf(prog))
3488 			return true;
3489 	}
3490 
3491 	bpf_object__for_each_map(map, obj) {
3492 		if (map_needs_vmlinux_btf(map))
3493 			return true;
3494 	}
3495 
3496 	return false;
3497 }
3498 
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3499 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3500 {
3501 	int err;
3502 
3503 	/* btf_vmlinux could be loaded earlier */
3504 	if (obj->btf_vmlinux || obj->gen_loader)
3505 		return 0;
3506 
3507 	if (!force && !obj_needs_vmlinux_btf(obj))
3508 		return 0;
3509 
3510 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3511 	err = libbpf_get_error(obj->btf_vmlinux);
3512 	if (err) {
3513 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3514 		obj->btf_vmlinux = NULL;
3515 		return err;
3516 	}
3517 	return 0;
3518 }
3519 
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3520 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3521 {
3522 	struct btf *kern_btf = obj->btf;
3523 	bool btf_mandatory, sanitize;
3524 	int i, err = 0;
3525 
3526 	if (!obj->btf)
3527 		return 0;
3528 
3529 	if (!kernel_supports(obj, FEAT_BTF)) {
3530 		if (kernel_needs_btf(obj)) {
3531 			err = -EOPNOTSUPP;
3532 			goto report;
3533 		}
3534 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3535 		return 0;
3536 	}
3537 
3538 	/* Even though some subprogs are global/weak, user might prefer more
3539 	 * permissive BPF verification process that BPF verifier performs for
3540 	 * static functions, taking into account more context from the caller
3541 	 * functions. In such case, they need to mark such subprogs with
3542 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3543 	 * corresponding FUNC BTF type to be marked as static and trigger more
3544 	 * involved BPF verification process.
3545 	 */
3546 	for (i = 0; i < obj->nr_programs; i++) {
3547 		struct bpf_program *prog = &obj->programs[i];
3548 		struct btf_type *t;
3549 		const char *name;
3550 		int j, n;
3551 
3552 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3553 			continue;
3554 
3555 		n = btf__type_cnt(obj->btf);
3556 		for (j = 1; j < n; j++) {
3557 			t = btf_type_by_id(obj->btf, j);
3558 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3559 				continue;
3560 
3561 			name = btf__str_by_offset(obj->btf, t->name_off);
3562 			if (strcmp(name, prog->name) != 0)
3563 				continue;
3564 
3565 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3566 			break;
3567 		}
3568 	}
3569 
3570 	sanitize = btf_needs_sanitization(obj);
3571 	if (sanitize) {
3572 		const void *raw_data;
3573 		__u32 sz;
3574 
3575 		/* clone BTF to sanitize a copy and leave the original intact */
3576 		raw_data = btf__raw_data(obj->btf, &sz);
3577 		kern_btf = btf__new(raw_data, sz);
3578 		err = libbpf_get_error(kern_btf);
3579 		if (err)
3580 			return err;
3581 
3582 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3583 		btf__set_pointer_size(obj->btf, 8);
3584 		err = bpf_object__sanitize_btf(obj, kern_btf);
3585 		if (err)
3586 			return err;
3587 	}
3588 
3589 	if (obj->gen_loader) {
3590 		__u32 raw_size = 0;
3591 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3592 
3593 		if (!raw_data)
3594 			return -ENOMEM;
3595 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3596 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3597 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3598 		 */
3599 		btf__set_fd(kern_btf, 0);
3600 	} else {
3601 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3602 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3603 					   obj->log_level ? 1 : 0, obj->token_fd);
3604 	}
3605 	if (sanitize) {
3606 		if (!err) {
3607 			/* move fd to libbpf's BTF */
3608 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3609 			btf__set_fd(kern_btf, -1);
3610 		}
3611 		btf__free(kern_btf);
3612 	}
3613 report:
3614 	if (err) {
3615 		btf_mandatory = kernel_needs_btf(obj);
3616 		if (btf_mandatory) {
3617 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3618 				errstr(err));
3619 		} else {
3620 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3621 				errstr(err));
3622 			err = 0;
3623 		}
3624 	}
3625 	return err;
3626 }
3627 
elf_sym_str(const struct bpf_object * obj,size_t off)3628 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3629 {
3630 	const char *name;
3631 
3632 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3633 	if (!name) {
3634 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3635 			off, obj->path, elf_errmsg(-1));
3636 		return NULL;
3637 	}
3638 
3639 	return name;
3640 }
3641 
elf_sec_str(const struct bpf_object * obj,size_t off)3642 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3643 {
3644 	const char *name;
3645 
3646 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3647 	if (!name) {
3648 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3649 			off, obj->path, elf_errmsg(-1));
3650 		return NULL;
3651 	}
3652 
3653 	return name;
3654 }
3655 
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3656 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3657 {
3658 	Elf_Scn *scn;
3659 
3660 	scn = elf_getscn(obj->efile.elf, idx);
3661 	if (!scn) {
3662 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3663 			idx, obj->path, elf_errmsg(-1));
3664 		return NULL;
3665 	}
3666 	return scn;
3667 }
3668 
elf_sec_by_name(const struct bpf_object * obj,const char * name)3669 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3670 {
3671 	Elf_Scn *scn = NULL;
3672 	Elf *elf = obj->efile.elf;
3673 	const char *sec_name;
3674 
3675 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3676 		sec_name = elf_sec_name(obj, scn);
3677 		if (!sec_name)
3678 			return NULL;
3679 
3680 		if (strcmp(sec_name, name) != 0)
3681 			continue;
3682 
3683 		return scn;
3684 	}
3685 	return NULL;
3686 }
3687 
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3688 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3689 {
3690 	Elf64_Shdr *shdr;
3691 
3692 	if (!scn)
3693 		return NULL;
3694 
3695 	shdr = elf64_getshdr(scn);
3696 	if (!shdr) {
3697 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3698 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3699 		return NULL;
3700 	}
3701 
3702 	return shdr;
3703 }
3704 
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3705 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3706 {
3707 	const char *name;
3708 	Elf64_Shdr *sh;
3709 
3710 	if (!scn)
3711 		return NULL;
3712 
3713 	sh = elf_sec_hdr(obj, scn);
3714 	if (!sh)
3715 		return NULL;
3716 
3717 	name = elf_sec_str(obj, sh->sh_name);
3718 	if (!name) {
3719 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3720 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3721 		return NULL;
3722 	}
3723 
3724 	return name;
3725 }
3726 
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3727 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3728 {
3729 	Elf_Data *data;
3730 
3731 	if (!scn)
3732 		return NULL;
3733 
3734 	data = elf_getdata(scn, 0);
3735 	if (!data) {
3736 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3737 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3738 			obj->path, elf_errmsg(-1));
3739 		return NULL;
3740 	}
3741 
3742 	return data;
3743 }
3744 
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3745 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3746 {
3747 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3748 		return NULL;
3749 
3750 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3751 }
3752 
elf_rel_by_idx(Elf_Data * data,size_t idx)3753 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3754 {
3755 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3756 		return NULL;
3757 
3758 	return (Elf64_Rel *)data->d_buf + idx;
3759 }
3760 
is_sec_name_dwarf(const char * name)3761 static bool is_sec_name_dwarf(const char *name)
3762 {
3763 	/* approximation, but the actual list is too long */
3764 	return str_has_pfx(name, ".debug_");
3765 }
3766 
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3767 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3768 {
3769 	/* no special handling of .strtab */
3770 	if (hdr->sh_type == SHT_STRTAB)
3771 		return true;
3772 
3773 	/* ignore .llvm_addrsig section as well */
3774 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3775 		return true;
3776 
3777 	/* no subprograms will lead to an empty .text section, ignore it */
3778 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3779 	    strcmp(name, ".text") == 0)
3780 		return true;
3781 
3782 	/* DWARF sections */
3783 	if (is_sec_name_dwarf(name))
3784 		return true;
3785 
3786 	if (str_has_pfx(name, ".rel")) {
3787 		name += sizeof(".rel") - 1;
3788 		/* DWARF section relocations */
3789 		if (is_sec_name_dwarf(name))
3790 			return true;
3791 
3792 		/* .BTF and .BTF.ext don't need relocations */
3793 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3794 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3795 			return true;
3796 	}
3797 
3798 	return false;
3799 }
3800 
cmp_progs(const void * _a,const void * _b)3801 static int cmp_progs(const void *_a, const void *_b)
3802 {
3803 	const struct bpf_program *a = _a;
3804 	const struct bpf_program *b = _b;
3805 
3806 	if (a->sec_idx != b->sec_idx)
3807 		return a->sec_idx < b->sec_idx ? -1 : 1;
3808 
3809 	/* sec_insn_off can't be the same within the section */
3810 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3811 }
3812 
bpf_object__elf_collect(struct bpf_object * obj)3813 static int bpf_object__elf_collect(struct bpf_object *obj)
3814 {
3815 	struct elf_sec_desc *sec_desc;
3816 	Elf *elf = obj->efile.elf;
3817 	Elf_Data *btf_ext_data = NULL;
3818 	Elf_Data *btf_data = NULL;
3819 	int idx = 0, err = 0;
3820 	const char *name;
3821 	Elf_Data *data;
3822 	Elf_Scn *scn;
3823 	Elf64_Shdr *sh;
3824 
3825 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3826 	 * section. Since section count retrieved by elf_getshdrnum() does
3827 	 * include sec #0, it is already the necessary size of an array to keep
3828 	 * all the sections.
3829 	 */
3830 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3831 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3832 			obj->path, elf_errmsg(-1));
3833 		return -LIBBPF_ERRNO__FORMAT;
3834 	}
3835 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3836 	if (!obj->efile.secs)
3837 		return -ENOMEM;
3838 
3839 	/* a bunch of ELF parsing functionality depends on processing symbols,
3840 	 * so do the first pass and find the symbol table
3841 	 */
3842 	scn = NULL;
3843 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3844 		sh = elf_sec_hdr(obj, scn);
3845 		if (!sh)
3846 			return -LIBBPF_ERRNO__FORMAT;
3847 
3848 		if (sh->sh_type == SHT_SYMTAB) {
3849 			if (obj->efile.symbols) {
3850 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3851 				return -LIBBPF_ERRNO__FORMAT;
3852 			}
3853 
3854 			data = elf_sec_data(obj, scn);
3855 			if (!data)
3856 				return -LIBBPF_ERRNO__FORMAT;
3857 
3858 			idx = elf_ndxscn(scn);
3859 
3860 			obj->efile.symbols = data;
3861 			obj->efile.symbols_shndx = idx;
3862 			obj->efile.strtabidx = sh->sh_link;
3863 		}
3864 	}
3865 
3866 	if (!obj->efile.symbols) {
3867 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3868 			obj->path);
3869 		return -ENOENT;
3870 	}
3871 
3872 	scn = NULL;
3873 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3874 		idx = elf_ndxscn(scn);
3875 		sec_desc = &obj->efile.secs[idx];
3876 
3877 		sh = elf_sec_hdr(obj, scn);
3878 		if (!sh)
3879 			return -LIBBPF_ERRNO__FORMAT;
3880 
3881 		name = elf_sec_str(obj, sh->sh_name);
3882 		if (!name)
3883 			return -LIBBPF_ERRNO__FORMAT;
3884 
3885 		if (ignore_elf_section(sh, name))
3886 			continue;
3887 
3888 		data = elf_sec_data(obj, scn);
3889 		if (!data)
3890 			return -LIBBPF_ERRNO__FORMAT;
3891 
3892 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3893 			 idx, name, (unsigned long)data->d_size,
3894 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3895 			 (int)sh->sh_type);
3896 
3897 		if (strcmp(name, "license") == 0) {
3898 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3899 			if (err)
3900 				return err;
3901 		} else if (strcmp(name, "version") == 0) {
3902 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3903 			if (err)
3904 				return err;
3905 		} else if (strcmp(name, "maps") == 0) {
3906 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3907 			return -ENOTSUP;
3908 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3909 			obj->efile.btf_maps_shndx = idx;
3910 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3911 			if (sh->sh_type != SHT_PROGBITS)
3912 				return -LIBBPF_ERRNO__FORMAT;
3913 			btf_data = data;
3914 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3915 			if (sh->sh_type != SHT_PROGBITS)
3916 				return -LIBBPF_ERRNO__FORMAT;
3917 			btf_ext_data = data;
3918 		} else if (sh->sh_type == SHT_SYMTAB) {
3919 			/* already processed during the first pass above */
3920 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3921 			if (sh->sh_flags & SHF_EXECINSTR) {
3922 				if (strcmp(name, ".text") == 0)
3923 					obj->efile.text_shndx = idx;
3924 				err = bpf_object__add_programs(obj, data, name, idx);
3925 				if (err)
3926 					return err;
3927 			} else if (strcmp(name, DATA_SEC) == 0 ||
3928 				   str_has_pfx(name, DATA_SEC ".")) {
3929 				sec_desc->sec_type = SEC_DATA;
3930 				sec_desc->shdr = sh;
3931 				sec_desc->data = data;
3932 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3933 				   str_has_pfx(name, RODATA_SEC ".")) {
3934 				sec_desc->sec_type = SEC_RODATA;
3935 				sec_desc->shdr = sh;
3936 				sec_desc->data = data;
3937 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3938 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3939 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3940 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3941 				sec_desc->sec_type = SEC_ST_OPS;
3942 				sec_desc->shdr = sh;
3943 				sec_desc->data = data;
3944 				obj->efile.has_st_ops = true;
3945 			} else if (strcmp(name, ARENA_SEC) == 0) {
3946 				obj->efile.arena_data = data;
3947 				obj->efile.arena_data_shndx = idx;
3948 			} else {
3949 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3950 					idx, name);
3951 			}
3952 		} else if (sh->sh_type == SHT_REL) {
3953 			int targ_sec_idx = sh->sh_info; /* points to other section */
3954 
3955 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3956 			    targ_sec_idx >= obj->efile.sec_cnt)
3957 				return -LIBBPF_ERRNO__FORMAT;
3958 
3959 			/* Only do relo for section with exec instructions */
3960 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3961 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3962 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3963 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3964 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3965 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3966 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3967 					idx, name, targ_sec_idx,
3968 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3969 				continue;
3970 			}
3971 
3972 			sec_desc->sec_type = SEC_RELO;
3973 			sec_desc->shdr = sh;
3974 			sec_desc->data = data;
3975 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3976 							 str_has_pfx(name, BSS_SEC "."))) {
3977 			sec_desc->sec_type = SEC_BSS;
3978 			sec_desc->shdr = sh;
3979 			sec_desc->data = data;
3980 		} else {
3981 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3982 				(size_t)sh->sh_size);
3983 		}
3984 	}
3985 
3986 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3987 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3988 		return -LIBBPF_ERRNO__FORMAT;
3989 	}
3990 
3991 	/* change BPF program insns to native endianness for introspection */
3992 	if (!is_native_endianness(obj))
3993 		bpf_object_bswap_progs(obj);
3994 
3995 	/* sort BPF programs by section name and in-section instruction offset
3996 	 * for faster search
3997 	 */
3998 	if (obj->nr_programs)
3999 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4000 
4001 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4002 }
4003 
sym_is_extern(const Elf64_Sym * sym)4004 static bool sym_is_extern(const Elf64_Sym *sym)
4005 {
4006 	int bind = ELF64_ST_BIND(sym->st_info);
4007 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4008 	return sym->st_shndx == SHN_UNDEF &&
4009 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4010 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4011 }
4012 
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)4013 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4014 {
4015 	int bind = ELF64_ST_BIND(sym->st_info);
4016 	int type = ELF64_ST_TYPE(sym->st_info);
4017 
4018 	/* in .text section */
4019 	if (sym->st_shndx != text_shndx)
4020 		return false;
4021 
4022 	/* local function */
4023 	if (bind == STB_LOCAL && type == STT_SECTION)
4024 		return true;
4025 
4026 	/* global function */
4027 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4028 }
4029 
find_extern_btf_id(const struct btf * btf,const char * ext_name)4030 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4031 {
4032 	const struct btf_type *t;
4033 	const char *tname;
4034 	int i, n;
4035 
4036 	if (!btf)
4037 		return -ESRCH;
4038 
4039 	n = btf__type_cnt(btf);
4040 	for (i = 1; i < n; i++) {
4041 		t = btf__type_by_id(btf, i);
4042 
4043 		if (!btf_is_var(t) && !btf_is_func(t))
4044 			continue;
4045 
4046 		tname = btf__name_by_offset(btf, t->name_off);
4047 		if (strcmp(tname, ext_name))
4048 			continue;
4049 
4050 		if (btf_is_var(t) &&
4051 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4052 			return -EINVAL;
4053 
4054 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4055 			return -EINVAL;
4056 
4057 		return i;
4058 	}
4059 
4060 	return -ENOENT;
4061 }
4062 
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)4063 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4064 	const struct btf_var_secinfo *vs;
4065 	const struct btf_type *t;
4066 	int i, j, n;
4067 
4068 	if (!btf)
4069 		return -ESRCH;
4070 
4071 	n = btf__type_cnt(btf);
4072 	for (i = 1; i < n; i++) {
4073 		t = btf__type_by_id(btf, i);
4074 
4075 		if (!btf_is_datasec(t))
4076 			continue;
4077 
4078 		vs = btf_var_secinfos(t);
4079 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4080 			if (vs->type == ext_btf_id)
4081 				return i;
4082 		}
4083 	}
4084 
4085 	return -ENOENT;
4086 }
4087 
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)4088 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4089 				     bool *is_signed)
4090 {
4091 	const struct btf_type *t;
4092 	const char *name;
4093 
4094 	t = skip_mods_and_typedefs(btf, id, NULL);
4095 	name = btf__name_by_offset(btf, t->name_off);
4096 
4097 	if (is_signed)
4098 		*is_signed = false;
4099 	switch (btf_kind(t)) {
4100 	case BTF_KIND_INT: {
4101 		int enc = btf_int_encoding(t);
4102 
4103 		if (enc & BTF_INT_BOOL)
4104 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4105 		if (is_signed)
4106 			*is_signed = enc & BTF_INT_SIGNED;
4107 		if (t->size == 1)
4108 			return KCFG_CHAR;
4109 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4110 			return KCFG_UNKNOWN;
4111 		return KCFG_INT;
4112 	}
4113 	case BTF_KIND_ENUM:
4114 		if (t->size != 4)
4115 			return KCFG_UNKNOWN;
4116 		if (strcmp(name, "libbpf_tristate"))
4117 			return KCFG_UNKNOWN;
4118 		return KCFG_TRISTATE;
4119 	case BTF_KIND_ENUM64:
4120 		if (strcmp(name, "libbpf_tristate"))
4121 			return KCFG_UNKNOWN;
4122 		return KCFG_TRISTATE;
4123 	case BTF_KIND_ARRAY:
4124 		if (btf_array(t)->nelems == 0)
4125 			return KCFG_UNKNOWN;
4126 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4127 			return KCFG_UNKNOWN;
4128 		return KCFG_CHAR_ARR;
4129 	default:
4130 		return KCFG_UNKNOWN;
4131 	}
4132 }
4133 
cmp_externs(const void * _a,const void * _b)4134 static int cmp_externs(const void *_a, const void *_b)
4135 {
4136 	const struct extern_desc *a = _a;
4137 	const struct extern_desc *b = _b;
4138 
4139 	if (a->type != b->type)
4140 		return a->type < b->type ? -1 : 1;
4141 
4142 	if (a->type == EXT_KCFG) {
4143 		/* descending order by alignment requirements */
4144 		if (a->kcfg.align != b->kcfg.align)
4145 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4146 		/* ascending order by size, within same alignment class */
4147 		if (a->kcfg.sz != b->kcfg.sz)
4148 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4149 	}
4150 
4151 	/* resolve ties by name */
4152 	return strcmp(a->name, b->name);
4153 }
4154 
find_int_btf_id(const struct btf * btf)4155 static int find_int_btf_id(const struct btf *btf)
4156 {
4157 	const struct btf_type *t;
4158 	int i, n;
4159 
4160 	n = btf__type_cnt(btf);
4161 	for (i = 1; i < n; i++) {
4162 		t = btf__type_by_id(btf, i);
4163 
4164 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4165 			return i;
4166 	}
4167 
4168 	return 0;
4169 }
4170 
add_dummy_ksym_var(struct btf * btf)4171 static int add_dummy_ksym_var(struct btf *btf)
4172 {
4173 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4174 	const struct btf_var_secinfo *vs;
4175 	const struct btf_type *sec;
4176 
4177 	if (!btf)
4178 		return 0;
4179 
4180 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4181 					    BTF_KIND_DATASEC);
4182 	if (sec_btf_id < 0)
4183 		return 0;
4184 
4185 	sec = btf__type_by_id(btf, sec_btf_id);
4186 	vs = btf_var_secinfos(sec);
4187 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4188 		const struct btf_type *vt;
4189 
4190 		vt = btf__type_by_id(btf, vs->type);
4191 		if (btf_is_func(vt))
4192 			break;
4193 	}
4194 
4195 	/* No func in ksyms sec.  No need to add dummy var. */
4196 	if (i == btf_vlen(sec))
4197 		return 0;
4198 
4199 	int_btf_id = find_int_btf_id(btf);
4200 	dummy_var_btf_id = btf__add_var(btf,
4201 					"dummy_ksym",
4202 					BTF_VAR_GLOBAL_ALLOCATED,
4203 					int_btf_id);
4204 	if (dummy_var_btf_id < 0)
4205 		pr_warn("cannot create a dummy_ksym var\n");
4206 
4207 	return dummy_var_btf_id;
4208 }
4209 
bpf_object__collect_externs(struct bpf_object * obj)4210 static int bpf_object__collect_externs(struct bpf_object *obj)
4211 {
4212 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4213 	const struct btf_type *t;
4214 	struct extern_desc *ext;
4215 	int i, n, off, dummy_var_btf_id;
4216 	const char *ext_name, *sec_name;
4217 	size_t ext_essent_len;
4218 	Elf_Scn *scn;
4219 	Elf64_Shdr *sh;
4220 
4221 	if (!obj->efile.symbols)
4222 		return 0;
4223 
4224 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4225 	sh = elf_sec_hdr(obj, scn);
4226 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4227 		return -LIBBPF_ERRNO__FORMAT;
4228 
4229 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4230 	if (dummy_var_btf_id < 0)
4231 		return dummy_var_btf_id;
4232 
4233 	n = sh->sh_size / sh->sh_entsize;
4234 	pr_debug("looking for externs among %d symbols...\n", n);
4235 
4236 	for (i = 0; i < n; i++) {
4237 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4238 
4239 		if (!sym)
4240 			return -LIBBPF_ERRNO__FORMAT;
4241 		if (!sym_is_extern(sym))
4242 			continue;
4243 		ext_name = elf_sym_str(obj, sym->st_name);
4244 		if (!ext_name || !ext_name[0])
4245 			continue;
4246 
4247 		ext = obj->externs;
4248 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4249 		if (!ext)
4250 			return -ENOMEM;
4251 		obj->externs = ext;
4252 		ext = &ext[obj->nr_extern];
4253 		memset(ext, 0, sizeof(*ext));
4254 		obj->nr_extern++;
4255 
4256 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4257 		if (ext->btf_id <= 0) {
4258 			pr_warn("failed to find BTF for extern '%s': %d\n",
4259 				ext_name, ext->btf_id);
4260 			return ext->btf_id;
4261 		}
4262 		t = btf__type_by_id(obj->btf, ext->btf_id);
4263 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4264 		if (!ext->name)
4265 			return -ENOMEM;
4266 		ext->sym_idx = i;
4267 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4268 
4269 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4270 		ext->essent_name = NULL;
4271 		if (ext_essent_len != strlen(ext->name)) {
4272 			ext->essent_name = strndup(ext->name, ext_essent_len);
4273 			if (!ext->essent_name)
4274 				return -ENOMEM;
4275 		}
4276 
4277 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4278 		if (ext->sec_btf_id <= 0) {
4279 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4280 				ext_name, ext->btf_id, ext->sec_btf_id);
4281 			return ext->sec_btf_id;
4282 		}
4283 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4284 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4285 
4286 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4287 			if (btf_is_func(t)) {
4288 				pr_warn("extern function %s is unsupported under %s section\n",
4289 					ext->name, KCONFIG_SEC);
4290 				return -ENOTSUP;
4291 			}
4292 			kcfg_sec = sec;
4293 			ext->type = EXT_KCFG;
4294 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4295 			if (ext->kcfg.sz <= 0) {
4296 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4297 					ext_name, ext->kcfg.sz);
4298 				return ext->kcfg.sz;
4299 			}
4300 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4301 			if (ext->kcfg.align <= 0) {
4302 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4303 					ext_name, ext->kcfg.align);
4304 				return -EINVAL;
4305 			}
4306 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4307 							&ext->kcfg.is_signed);
4308 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4309 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4310 				return -ENOTSUP;
4311 			}
4312 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4313 			ksym_sec = sec;
4314 			ext->type = EXT_KSYM;
4315 			skip_mods_and_typedefs(obj->btf, t->type,
4316 					       &ext->ksym.type_id);
4317 		} else {
4318 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4319 			return -ENOTSUP;
4320 		}
4321 	}
4322 	pr_debug("collected %d externs total\n", obj->nr_extern);
4323 
4324 	if (!obj->nr_extern)
4325 		return 0;
4326 
4327 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4328 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4329 
4330 	/* for .ksyms section, we need to turn all externs into allocated
4331 	 * variables in BTF to pass kernel verification; we do this by
4332 	 * pretending that each extern is a 8-byte variable
4333 	 */
4334 	if (ksym_sec) {
4335 		/* find existing 4-byte integer type in BTF to use for fake
4336 		 * extern variables in DATASEC
4337 		 */
4338 		int int_btf_id = find_int_btf_id(obj->btf);
4339 		/* For extern function, a dummy_var added earlier
4340 		 * will be used to replace the vs->type and
4341 		 * its name string will be used to refill
4342 		 * the missing param's name.
4343 		 */
4344 		const struct btf_type *dummy_var;
4345 
4346 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4347 		for (i = 0; i < obj->nr_extern; i++) {
4348 			ext = &obj->externs[i];
4349 			if (ext->type != EXT_KSYM)
4350 				continue;
4351 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4352 				 i, ext->sym_idx, ext->name);
4353 		}
4354 
4355 		sec = ksym_sec;
4356 		n = btf_vlen(sec);
4357 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4358 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4359 			struct btf_type *vt;
4360 
4361 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4362 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4363 			ext = find_extern_by_name(obj, ext_name);
4364 			if (!ext) {
4365 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4366 					btf_kind_str(vt), ext_name);
4367 				return -ESRCH;
4368 			}
4369 			if (btf_is_func(vt)) {
4370 				const struct btf_type *func_proto;
4371 				struct btf_param *param;
4372 				int j;
4373 
4374 				func_proto = btf__type_by_id(obj->btf,
4375 							     vt->type);
4376 				param = btf_params(func_proto);
4377 				/* Reuse the dummy_var string if the
4378 				 * func proto does not have param name.
4379 				 */
4380 				for (j = 0; j < btf_vlen(func_proto); j++)
4381 					if (param[j].type && !param[j].name_off)
4382 						param[j].name_off =
4383 							dummy_var->name_off;
4384 				vs->type = dummy_var_btf_id;
4385 				vt->info &= ~0xffff;
4386 				vt->info |= BTF_FUNC_GLOBAL;
4387 			} else {
4388 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4389 				vt->type = int_btf_id;
4390 			}
4391 			vs->offset = off;
4392 			vs->size = sizeof(int);
4393 		}
4394 		sec->size = off;
4395 	}
4396 
4397 	if (kcfg_sec) {
4398 		sec = kcfg_sec;
4399 		/* for kcfg externs calculate their offsets within a .kconfig map */
4400 		off = 0;
4401 		for (i = 0; i < obj->nr_extern; i++) {
4402 			ext = &obj->externs[i];
4403 			if (ext->type != EXT_KCFG)
4404 				continue;
4405 
4406 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4407 			off = ext->kcfg.data_off + ext->kcfg.sz;
4408 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4409 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4410 		}
4411 		sec->size = off;
4412 		n = btf_vlen(sec);
4413 		for (i = 0; i < n; i++) {
4414 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4415 
4416 			t = btf__type_by_id(obj->btf, vs->type);
4417 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4418 			ext = find_extern_by_name(obj, ext_name);
4419 			if (!ext) {
4420 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4421 					ext_name);
4422 				return -ESRCH;
4423 			}
4424 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4425 			vs->offset = ext->kcfg.data_off;
4426 		}
4427 	}
4428 	return 0;
4429 }
4430 
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)4431 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4432 {
4433 	return prog->sec_idx == obj->efile.text_shndx;
4434 }
4435 
4436 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)4437 bpf_object__find_program_by_name(const struct bpf_object *obj,
4438 				 const char *name)
4439 {
4440 	struct bpf_program *prog;
4441 
4442 	bpf_object__for_each_program(prog, obj) {
4443 		if (prog_is_subprog(obj, prog))
4444 			continue;
4445 		if (!strcmp(prog->name, name))
4446 			return prog;
4447 	}
4448 	return errno = ENOENT, NULL;
4449 }
4450 
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4451 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4452 				      int shndx)
4453 {
4454 	switch (obj->efile.secs[shndx].sec_type) {
4455 	case SEC_BSS:
4456 	case SEC_DATA:
4457 	case SEC_RODATA:
4458 		return true;
4459 	default:
4460 		return false;
4461 	}
4462 }
4463 
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4464 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4465 				      int shndx)
4466 {
4467 	return shndx == obj->efile.btf_maps_shndx;
4468 }
4469 
4470 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4471 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4472 {
4473 	if (shndx == obj->efile.symbols_shndx)
4474 		return LIBBPF_MAP_KCONFIG;
4475 
4476 	switch (obj->efile.secs[shndx].sec_type) {
4477 	case SEC_BSS:
4478 		return LIBBPF_MAP_BSS;
4479 	case SEC_DATA:
4480 		return LIBBPF_MAP_DATA;
4481 	case SEC_RODATA:
4482 		return LIBBPF_MAP_RODATA;
4483 	default:
4484 		return LIBBPF_MAP_UNSPEC;
4485 	}
4486 }
4487 
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)4488 static int bpf_program__record_reloc(struct bpf_program *prog,
4489 				     struct reloc_desc *reloc_desc,
4490 				     __u32 insn_idx, const char *sym_name,
4491 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4492 {
4493 	struct bpf_insn *insn = &prog->insns[insn_idx];
4494 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4495 	struct bpf_object *obj = prog->obj;
4496 	__u32 shdr_idx = sym->st_shndx;
4497 	enum libbpf_map_type type;
4498 	const char *sym_sec_name;
4499 	struct bpf_map *map;
4500 
4501 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4502 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4503 			prog->name, sym_name, insn_idx, insn->code);
4504 		return -LIBBPF_ERRNO__RELOC;
4505 	}
4506 
4507 	if (sym_is_extern(sym)) {
4508 		int sym_idx = ELF64_R_SYM(rel->r_info);
4509 		int i, n = obj->nr_extern;
4510 		struct extern_desc *ext;
4511 
4512 		for (i = 0; i < n; i++) {
4513 			ext = &obj->externs[i];
4514 			if (ext->sym_idx == sym_idx)
4515 				break;
4516 		}
4517 		if (i >= n) {
4518 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4519 				prog->name, sym_name, sym_idx);
4520 			return -LIBBPF_ERRNO__RELOC;
4521 		}
4522 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4523 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4524 		if (insn->code == (BPF_JMP | BPF_CALL))
4525 			reloc_desc->type = RELO_EXTERN_CALL;
4526 		else
4527 			reloc_desc->type = RELO_EXTERN_LD64;
4528 		reloc_desc->insn_idx = insn_idx;
4529 		reloc_desc->ext_idx = i;
4530 		return 0;
4531 	}
4532 
4533 	/* sub-program call relocation */
4534 	if (is_call_insn(insn)) {
4535 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4536 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4537 			return -LIBBPF_ERRNO__RELOC;
4538 		}
4539 		/* text_shndx can be 0, if no default "main" program exists */
4540 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4541 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4542 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4543 				prog->name, sym_name, sym_sec_name);
4544 			return -LIBBPF_ERRNO__RELOC;
4545 		}
4546 		if (sym->st_value % BPF_INSN_SZ) {
4547 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4548 				prog->name, sym_name, (size_t)sym->st_value);
4549 			return -LIBBPF_ERRNO__RELOC;
4550 		}
4551 		reloc_desc->type = RELO_CALL;
4552 		reloc_desc->insn_idx = insn_idx;
4553 		reloc_desc->sym_off = sym->st_value;
4554 		return 0;
4555 	}
4556 
4557 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4558 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4559 			prog->name, sym_name, shdr_idx);
4560 		return -LIBBPF_ERRNO__RELOC;
4561 	}
4562 
4563 	/* loading subprog addresses */
4564 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4565 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4566 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4567 		 */
4568 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4569 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4570 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4571 			return -LIBBPF_ERRNO__RELOC;
4572 		}
4573 
4574 		reloc_desc->type = RELO_SUBPROG_ADDR;
4575 		reloc_desc->insn_idx = insn_idx;
4576 		reloc_desc->sym_off = sym->st_value;
4577 		return 0;
4578 	}
4579 
4580 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4581 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4582 
4583 	/* arena data relocation */
4584 	if (shdr_idx == obj->efile.arena_data_shndx) {
4585 		if (obj->arena_map_idx < 0) {
4586 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4587 				prog->name, insn_idx);
4588 			return -LIBBPF_ERRNO__RELOC;
4589 		}
4590 		reloc_desc->type = RELO_DATA;
4591 		reloc_desc->insn_idx = insn_idx;
4592 		reloc_desc->map_idx = obj->arena_map_idx;
4593 		reloc_desc->sym_off = sym->st_value;
4594 
4595 		map = &obj->maps[obj->arena_map_idx];
4596 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4597 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4598 			 map->sec_offset, insn_idx);
4599 		return 0;
4600 	}
4601 
4602 	/* generic map reference relocation */
4603 	if (type == LIBBPF_MAP_UNSPEC) {
4604 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4605 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4606 				prog->name, sym_name, sym_sec_name);
4607 			return -LIBBPF_ERRNO__RELOC;
4608 		}
4609 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4610 			map = &obj->maps[map_idx];
4611 			if (map->libbpf_type != type ||
4612 			    map->sec_idx != sym->st_shndx ||
4613 			    map->sec_offset != sym->st_value)
4614 				continue;
4615 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4616 				 prog->name, map_idx, map->name, map->sec_idx,
4617 				 map->sec_offset, insn_idx);
4618 			break;
4619 		}
4620 		if (map_idx >= nr_maps) {
4621 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4622 				prog->name, sym_sec_name, (size_t)sym->st_value);
4623 			return -LIBBPF_ERRNO__RELOC;
4624 		}
4625 		reloc_desc->type = RELO_LD64;
4626 		reloc_desc->insn_idx = insn_idx;
4627 		reloc_desc->map_idx = map_idx;
4628 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4629 		return 0;
4630 	}
4631 
4632 	/* global data map relocation */
4633 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4634 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4635 			prog->name, sym_sec_name);
4636 		return -LIBBPF_ERRNO__RELOC;
4637 	}
4638 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4639 		map = &obj->maps[map_idx];
4640 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4641 			continue;
4642 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4643 			 prog->name, map_idx, map->name, map->sec_idx,
4644 			 map->sec_offset, insn_idx);
4645 		break;
4646 	}
4647 	if (map_idx >= nr_maps) {
4648 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4649 			prog->name, sym_sec_name);
4650 		return -LIBBPF_ERRNO__RELOC;
4651 	}
4652 
4653 	reloc_desc->type = RELO_DATA;
4654 	reloc_desc->insn_idx = insn_idx;
4655 	reloc_desc->map_idx = map_idx;
4656 	reloc_desc->sym_off = sym->st_value;
4657 	return 0;
4658 }
4659 
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4660 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4661 {
4662 	return insn_idx >= prog->sec_insn_off &&
4663 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4664 }
4665 
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4666 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4667 						 size_t sec_idx, size_t insn_idx)
4668 {
4669 	int l = 0, r = obj->nr_programs - 1, m;
4670 	struct bpf_program *prog;
4671 
4672 	if (!obj->nr_programs)
4673 		return NULL;
4674 
4675 	while (l < r) {
4676 		m = l + (r - l + 1) / 2;
4677 		prog = &obj->programs[m];
4678 
4679 		if (prog->sec_idx < sec_idx ||
4680 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4681 			l = m;
4682 		else
4683 			r = m - 1;
4684 	}
4685 	/* matching program could be at index l, but it still might be the
4686 	 * wrong one, so we need to double check conditions for the last time
4687 	 */
4688 	prog = &obj->programs[l];
4689 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4690 		return prog;
4691 	return NULL;
4692 }
4693 
4694 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4695 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4696 {
4697 	const char *relo_sec_name, *sec_name;
4698 	size_t sec_idx = shdr->sh_info, sym_idx;
4699 	struct bpf_program *prog;
4700 	struct reloc_desc *relos;
4701 	int err, i, nrels;
4702 	const char *sym_name;
4703 	__u32 insn_idx;
4704 	Elf_Scn *scn;
4705 	Elf_Data *scn_data;
4706 	Elf64_Sym *sym;
4707 	Elf64_Rel *rel;
4708 
4709 	if (sec_idx >= obj->efile.sec_cnt)
4710 		return -EINVAL;
4711 
4712 	scn = elf_sec_by_idx(obj, sec_idx);
4713 	scn_data = elf_sec_data(obj, scn);
4714 	if (!scn_data)
4715 		return -LIBBPF_ERRNO__FORMAT;
4716 
4717 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4718 	sec_name = elf_sec_name(obj, scn);
4719 	if (!relo_sec_name || !sec_name)
4720 		return -EINVAL;
4721 
4722 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4723 		 relo_sec_name, sec_idx, sec_name);
4724 	nrels = shdr->sh_size / shdr->sh_entsize;
4725 
4726 	for (i = 0; i < nrels; i++) {
4727 		rel = elf_rel_by_idx(data, i);
4728 		if (!rel) {
4729 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4730 			return -LIBBPF_ERRNO__FORMAT;
4731 		}
4732 
4733 		sym_idx = ELF64_R_SYM(rel->r_info);
4734 		sym = elf_sym_by_idx(obj, sym_idx);
4735 		if (!sym) {
4736 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4737 				relo_sec_name, sym_idx, i);
4738 			return -LIBBPF_ERRNO__FORMAT;
4739 		}
4740 
4741 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4742 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4743 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4744 			return -LIBBPF_ERRNO__FORMAT;
4745 		}
4746 
4747 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4748 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4749 				relo_sec_name, (size_t)rel->r_offset, i);
4750 			return -LIBBPF_ERRNO__FORMAT;
4751 		}
4752 
4753 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4754 		/* relocations against static functions are recorded as
4755 		 * relocations against the section that contains a function;
4756 		 * in such case, symbol will be STT_SECTION and sym.st_name
4757 		 * will point to empty string (0), so fetch section name
4758 		 * instead
4759 		 */
4760 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4761 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4762 		else
4763 			sym_name = elf_sym_str(obj, sym->st_name);
4764 		sym_name = sym_name ?: "<?";
4765 
4766 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4767 			 relo_sec_name, i, insn_idx, sym_name);
4768 
4769 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4770 		if (!prog) {
4771 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4772 				relo_sec_name, i, sec_name, insn_idx);
4773 			continue;
4774 		}
4775 
4776 		relos = libbpf_reallocarray(prog->reloc_desc,
4777 					    prog->nr_reloc + 1, sizeof(*relos));
4778 		if (!relos)
4779 			return -ENOMEM;
4780 		prog->reloc_desc = relos;
4781 
4782 		/* adjust insn_idx to local BPF program frame of reference */
4783 		insn_idx -= prog->sec_insn_off;
4784 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4785 						insn_idx, sym_name, sym, rel);
4786 		if (err)
4787 			return err;
4788 
4789 		prog->nr_reloc++;
4790 	}
4791 	return 0;
4792 }
4793 
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4794 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4795 {
4796 	int id;
4797 
4798 	if (!obj->btf)
4799 		return -ENOENT;
4800 
4801 	/* if it's BTF-defined map, we don't need to search for type IDs.
4802 	 * For struct_ops map, it does not need btf_key_type_id and
4803 	 * btf_value_type_id.
4804 	 */
4805 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4806 		return 0;
4807 
4808 	/*
4809 	 * LLVM annotates global data differently in BTF, that is,
4810 	 * only as '.data', '.bss' or '.rodata'.
4811 	 */
4812 	if (!bpf_map__is_internal(map))
4813 		return -ENOENT;
4814 
4815 	id = btf__find_by_name(obj->btf, map->real_name);
4816 	if (id < 0)
4817 		return id;
4818 
4819 	map->btf_key_type_id = 0;
4820 	map->btf_value_type_id = id;
4821 	return 0;
4822 }
4823 
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4824 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4825 {
4826 	char file[PATH_MAX], buff[4096];
4827 	FILE *fp;
4828 	__u32 val;
4829 	int err;
4830 
4831 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4832 	memset(info, 0, sizeof(*info));
4833 
4834 	fp = fopen(file, "re");
4835 	if (!fp) {
4836 		err = -errno;
4837 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4838 			errstr(err));
4839 		return err;
4840 	}
4841 
4842 	while (fgets(buff, sizeof(buff), fp)) {
4843 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4844 			info->type = val;
4845 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4846 			info->key_size = val;
4847 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4848 			info->value_size = val;
4849 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4850 			info->max_entries = val;
4851 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4852 			info->map_flags = val;
4853 	}
4854 
4855 	fclose(fp);
4856 
4857 	return 0;
4858 }
4859 
map_is_created(const struct bpf_map * map)4860 static bool map_is_created(const struct bpf_map *map)
4861 {
4862 	return map->obj->state >= OBJ_PREPARED || map->reused;
4863 }
4864 
bpf_map__autocreate(const struct bpf_map * map)4865 bool bpf_map__autocreate(const struct bpf_map *map)
4866 {
4867 	return map->autocreate;
4868 }
4869 
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4870 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4871 {
4872 	if (map_is_created(map))
4873 		return libbpf_err(-EBUSY);
4874 
4875 	map->autocreate = autocreate;
4876 	return 0;
4877 }
4878 
bpf_map__set_autoattach(struct bpf_map * map,bool autoattach)4879 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4880 {
4881 	if (!bpf_map__is_struct_ops(map))
4882 		return libbpf_err(-EINVAL);
4883 
4884 	map->autoattach = autoattach;
4885 	return 0;
4886 }
4887 
bpf_map__autoattach(const struct bpf_map * map)4888 bool bpf_map__autoattach(const struct bpf_map *map)
4889 {
4890 	return map->autoattach;
4891 }
4892 
bpf_map__reuse_fd(struct bpf_map * map,int fd)4893 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4894 {
4895 	struct bpf_map_info info;
4896 	__u32 len = sizeof(info), name_len;
4897 	int new_fd, err;
4898 	char *new_name;
4899 
4900 	memset(&info, 0, len);
4901 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4902 	if (err && errno == EINVAL)
4903 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4904 	if (err)
4905 		return libbpf_err(err);
4906 
4907 	name_len = strlen(info.name);
4908 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4909 		new_name = strdup(map->name);
4910 	else
4911 		new_name = strdup(info.name);
4912 
4913 	if (!new_name)
4914 		return libbpf_err(-errno);
4915 
4916 	/*
4917 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4918 	 * This is similar to what we do in ensure_good_fd(), but without
4919 	 * closing original FD.
4920 	 */
4921 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4922 	if (new_fd < 0) {
4923 		err = -errno;
4924 		goto err_free_new_name;
4925 	}
4926 
4927 	err = reuse_fd(map->fd, new_fd);
4928 	if (err)
4929 		goto err_free_new_name;
4930 
4931 	free(map->name);
4932 
4933 	map->name = new_name;
4934 	map->def.type = info.type;
4935 	map->def.key_size = info.key_size;
4936 	map->def.value_size = info.value_size;
4937 	map->def.max_entries = info.max_entries;
4938 	map->def.map_flags = info.map_flags;
4939 	map->btf_key_type_id = info.btf_key_type_id;
4940 	map->btf_value_type_id = info.btf_value_type_id;
4941 	map->reused = true;
4942 	map->map_extra = info.map_extra;
4943 
4944 	return 0;
4945 
4946 err_free_new_name:
4947 	free(new_name);
4948 	return libbpf_err(err);
4949 }
4950 
bpf_map__max_entries(const struct bpf_map * map)4951 __u32 bpf_map__max_entries(const struct bpf_map *map)
4952 {
4953 	return map->def.max_entries;
4954 }
4955 
bpf_map__inner_map(struct bpf_map * map)4956 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4957 {
4958 	if (!bpf_map_type__is_map_in_map(map->def.type))
4959 		return errno = EINVAL, NULL;
4960 
4961 	return map->inner_map;
4962 }
4963 
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4964 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4965 {
4966 	if (map_is_created(map))
4967 		return libbpf_err(-EBUSY);
4968 
4969 	map->def.max_entries = max_entries;
4970 
4971 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4972 	if (map_is_ringbuf(map))
4973 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4974 
4975 	return 0;
4976 }
4977 
bpf_object_prepare_token(struct bpf_object * obj)4978 static int bpf_object_prepare_token(struct bpf_object *obj)
4979 {
4980 	const char *bpffs_path;
4981 	int bpffs_fd = -1, token_fd, err;
4982 	bool mandatory;
4983 	enum libbpf_print_level level;
4984 
4985 	/* token is explicitly prevented */
4986 	if (obj->token_path && obj->token_path[0] == '\0') {
4987 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4988 		return 0;
4989 	}
4990 
4991 	mandatory = obj->token_path != NULL;
4992 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4993 
4994 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4995 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4996 	if (bpffs_fd < 0) {
4997 		err = -errno;
4998 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
4999 		     obj->name, errstr(err), bpffs_path,
5000 		     mandatory ? "" : ", skipping optional step...");
5001 		return mandatory ? err : 0;
5002 	}
5003 
5004 	token_fd = bpf_token_create(bpffs_fd, 0);
5005 	close(bpffs_fd);
5006 	if (token_fd < 0) {
5007 		if (!mandatory && token_fd == -ENOENT) {
5008 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5009 				 obj->name, bpffs_path);
5010 			return 0;
5011 		}
5012 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5013 		     obj->name, token_fd, bpffs_path,
5014 		     mandatory ? "" : ", skipping optional step...");
5015 		return mandatory ? token_fd : 0;
5016 	}
5017 
5018 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5019 	if (!obj->feat_cache) {
5020 		close(token_fd);
5021 		return -ENOMEM;
5022 	}
5023 
5024 	obj->token_fd = token_fd;
5025 	obj->feat_cache->token_fd = token_fd;
5026 
5027 	return 0;
5028 }
5029 
5030 static int
bpf_object__probe_loading(struct bpf_object * obj)5031 bpf_object__probe_loading(struct bpf_object *obj)
5032 {
5033 	struct bpf_insn insns[] = {
5034 		BPF_MOV64_IMM(BPF_REG_0, 0),
5035 		BPF_EXIT_INSN(),
5036 	};
5037 	int ret, insn_cnt = ARRAY_SIZE(insns);
5038 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5039 		.token_fd = obj->token_fd,
5040 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5041 	);
5042 
5043 	if (obj->gen_loader)
5044 		return 0;
5045 
5046 	ret = bump_rlimit_memlock();
5047 	if (ret)
5048 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5049 			errstr(ret));
5050 
5051 	/* make sure basic loading works */
5052 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5053 	if (ret < 0)
5054 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5055 	if (ret < 0) {
5056 		ret = errno;
5057 		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",
5058 			__func__, errstr(ret));
5059 		return -ret;
5060 	}
5061 	close(ret);
5062 
5063 	return 0;
5064 }
5065 
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)5066 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5067 {
5068 	if (obj->gen_loader)
5069 		/* To generate loader program assume the latest kernel
5070 		 * to avoid doing extra prog_load, map_create syscalls.
5071 		 */
5072 		return true;
5073 
5074 	if (obj->token_fd)
5075 		return feat_supported(obj->feat_cache, feat_id);
5076 
5077 	return feat_supported(NULL, feat_id);
5078 }
5079 
map_is_reuse_compat(const struct bpf_map * map,int map_fd)5080 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5081 {
5082 	struct bpf_map_info map_info;
5083 	__u32 map_info_len = sizeof(map_info);
5084 	int err;
5085 
5086 	memset(&map_info, 0, map_info_len);
5087 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5088 	if (err && errno == EINVAL)
5089 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5090 	if (err) {
5091 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5092 			errstr(err));
5093 		return false;
5094 	}
5095 
5096 	return (map_info.type == map->def.type &&
5097 		map_info.key_size == map->def.key_size &&
5098 		map_info.value_size == map->def.value_size &&
5099 		map_info.max_entries == map->def.max_entries &&
5100 		map_info.map_flags == map->def.map_flags &&
5101 		map_info.map_extra == map->map_extra);
5102 }
5103 
5104 static int
bpf_object__reuse_map(struct bpf_map * map)5105 bpf_object__reuse_map(struct bpf_map *map)
5106 {
5107 	int err, pin_fd;
5108 
5109 	pin_fd = bpf_obj_get(map->pin_path);
5110 	if (pin_fd < 0) {
5111 		err = -errno;
5112 		if (err == -ENOENT) {
5113 			pr_debug("found no pinned map to reuse at '%s'\n",
5114 				 map->pin_path);
5115 			return 0;
5116 		}
5117 
5118 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5119 			map->pin_path, errstr(err));
5120 		return err;
5121 	}
5122 
5123 	if (!map_is_reuse_compat(map, pin_fd)) {
5124 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5125 			map->pin_path);
5126 		close(pin_fd);
5127 		return -EINVAL;
5128 	}
5129 
5130 	err = bpf_map__reuse_fd(map, pin_fd);
5131 	close(pin_fd);
5132 	if (err)
5133 		return err;
5134 
5135 	map->pinned = true;
5136 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5137 
5138 	return 0;
5139 }
5140 
5141 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5142 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5143 {
5144 	enum libbpf_map_type map_type = map->libbpf_type;
5145 	int err, zero = 0;
5146 	size_t mmap_sz;
5147 
5148 	if (obj->gen_loader) {
5149 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5150 					 map->mmaped, map->def.value_size);
5151 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5152 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5153 		return 0;
5154 	}
5155 
5156 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5157 	if (err) {
5158 		err = -errno;
5159 		pr_warn("map '%s': failed to set initial contents: %s\n",
5160 			bpf_map__name(map), errstr(err));
5161 		return err;
5162 	}
5163 
5164 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5165 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5166 		err = bpf_map_freeze(map->fd);
5167 		if (err) {
5168 			err = -errno;
5169 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5170 				bpf_map__name(map), errstr(err));
5171 			return err;
5172 		}
5173 	}
5174 
5175 	/* Remap anonymous mmap()-ed "map initialization image" as
5176 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5177 	 * memory address. This will cause kernel to change process'
5178 	 * page table to point to a different piece of kernel memory,
5179 	 * but from userspace point of view memory address (and its
5180 	 * contents, being identical at this point) will stay the
5181 	 * same. This mapping will be released by bpf_object__close()
5182 	 * as per normal clean up procedure.
5183 	 */
5184 	mmap_sz = bpf_map_mmap_sz(map);
5185 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5186 		void *mmaped;
5187 		int prot;
5188 
5189 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5190 			prot = PROT_READ;
5191 		else
5192 			prot = PROT_READ | PROT_WRITE;
5193 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5194 		if (mmaped == MAP_FAILED) {
5195 			err = -errno;
5196 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5197 				bpf_map__name(map), errstr(err));
5198 			return err;
5199 		}
5200 		map->mmaped = mmaped;
5201 	} else if (map->mmaped) {
5202 		munmap(map->mmaped, mmap_sz);
5203 		map->mmaped = NULL;
5204 	}
5205 
5206 	return 0;
5207 }
5208 
5209 static void bpf_map__destroy(struct bpf_map *map);
5210 
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5211 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5212 {
5213 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5214 	struct bpf_map_def *def = &map->def;
5215 	const char *map_name = NULL;
5216 	int err = 0, map_fd;
5217 
5218 	if (kernel_supports(obj, FEAT_PROG_NAME))
5219 		map_name = map->name;
5220 	create_attr.map_ifindex = map->map_ifindex;
5221 	create_attr.map_flags = def->map_flags;
5222 	create_attr.numa_node = map->numa_node;
5223 	create_attr.map_extra = map->map_extra;
5224 	create_attr.token_fd = obj->token_fd;
5225 	if (obj->token_fd)
5226 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5227 
5228 	if (bpf_map__is_struct_ops(map)) {
5229 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5230 		if (map->mod_btf_fd >= 0) {
5231 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5232 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5233 		}
5234 	}
5235 
5236 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5237 		create_attr.btf_fd = btf__fd(obj->btf);
5238 		create_attr.btf_key_type_id = map->btf_key_type_id;
5239 		create_attr.btf_value_type_id = map->btf_value_type_id;
5240 	}
5241 
5242 	if (bpf_map_type__is_map_in_map(def->type)) {
5243 		if (map->inner_map) {
5244 			err = map_set_def_max_entries(map->inner_map);
5245 			if (err)
5246 				return err;
5247 			err = bpf_object__create_map(obj, map->inner_map, true);
5248 			if (err) {
5249 				pr_warn("map '%s': failed to create inner map: %s\n",
5250 					map->name, errstr(err));
5251 				return err;
5252 			}
5253 			map->inner_map_fd = map->inner_map->fd;
5254 		}
5255 		if (map->inner_map_fd >= 0)
5256 			create_attr.inner_map_fd = map->inner_map_fd;
5257 	}
5258 
5259 	switch (def->type) {
5260 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5261 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5262 	case BPF_MAP_TYPE_STACK_TRACE:
5263 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5264 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5265 	case BPF_MAP_TYPE_DEVMAP:
5266 	case BPF_MAP_TYPE_DEVMAP_HASH:
5267 	case BPF_MAP_TYPE_CPUMAP:
5268 	case BPF_MAP_TYPE_XSKMAP:
5269 	case BPF_MAP_TYPE_SOCKMAP:
5270 	case BPF_MAP_TYPE_SOCKHASH:
5271 	case BPF_MAP_TYPE_QUEUE:
5272 	case BPF_MAP_TYPE_STACK:
5273 	case BPF_MAP_TYPE_ARENA:
5274 		create_attr.btf_fd = 0;
5275 		create_attr.btf_key_type_id = 0;
5276 		create_attr.btf_value_type_id = 0;
5277 		map->btf_key_type_id = 0;
5278 		map->btf_value_type_id = 0;
5279 		break;
5280 	case BPF_MAP_TYPE_STRUCT_OPS:
5281 		create_attr.btf_value_type_id = 0;
5282 		break;
5283 	default:
5284 		break;
5285 	}
5286 
5287 	if (obj->gen_loader) {
5288 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5289 				    def->key_size, def->value_size, def->max_entries,
5290 				    &create_attr, is_inner ? -1 : map - obj->maps);
5291 		/* We keep pretenting we have valid FD to pass various fd >= 0
5292 		 * checks by just keeping original placeholder FDs in place.
5293 		 * See bpf_object__add_map() comment.
5294 		 * This placeholder fd will not be used with any syscall and
5295 		 * will be reset to -1 eventually.
5296 		 */
5297 		map_fd = map->fd;
5298 	} else {
5299 		map_fd = bpf_map_create(def->type, map_name,
5300 					def->key_size, def->value_size,
5301 					def->max_entries, &create_attr);
5302 	}
5303 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5304 		err = -errno;
5305 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5306 			map->name, errstr(err));
5307 		create_attr.btf_fd = 0;
5308 		create_attr.btf_key_type_id = 0;
5309 		create_attr.btf_value_type_id = 0;
5310 		map->btf_key_type_id = 0;
5311 		map->btf_value_type_id = 0;
5312 		map_fd = bpf_map_create(def->type, map_name,
5313 					def->key_size, def->value_size,
5314 					def->max_entries, &create_attr);
5315 	}
5316 
5317 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5318 		if (obj->gen_loader)
5319 			map->inner_map->fd = -1;
5320 		bpf_map__destroy(map->inner_map);
5321 		zfree(&map->inner_map);
5322 	}
5323 
5324 	if (map_fd < 0)
5325 		return map_fd;
5326 
5327 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5328 	if (map->fd == map_fd)
5329 		return 0;
5330 
5331 	/* Keep placeholder FD value but now point it to the BPF map object.
5332 	 * This way everything that relied on this map's FD (e.g., relocated
5333 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5334 	 * map->fd stays valid but now point to what map_fd points to.
5335 	 */
5336 	return reuse_fd(map->fd, map_fd);
5337 }
5338 
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5339 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5340 {
5341 	const struct bpf_map *targ_map;
5342 	unsigned int i;
5343 	int fd, err = 0;
5344 
5345 	for (i = 0; i < map->init_slots_sz; i++) {
5346 		if (!map->init_slots[i])
5347 			continue;
5348 
5349 		targ_map = map->init_slots[i];
5350 		fd = targ_map->fd;
5351 
5352 		if (obj->gen_loader) {
5353 			bpf_gen__populate_outer_map(obj->gen_loader,
5354 						    map - obj->maps, i,
5355 						    targ_map - obj->maps);
5356 		} else {
5357 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5358 		}
5359 		if (err) {
5360 			err = -errno;
5361 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5362 				map->name, i, targ_map->name, fd, errstr(err));
5363 			return err;
5364 		}
5365 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5366 			 map->name, i, targ_map->name, fd);
5367 	}
5368 
5369 	zfree(&map->init_slots);
5370 	map->init_slots_sz = 0;
5371 
5372 	return 0;
5373 }
5374 
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5375 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5376 {
5377 	const struct bpf_program *targ_prog;
5378 	unsigned int i;
5379 	int fd, err;
5380 
5381 	if (obj->gen_loader)
5382 		return -ENOTSUP;
5383 
5384 	for (i = 0; i < map->init_slots_sz; i++) {
5385 		if (!map->init_slots[i])
5386 			continue;
5387 
5388 		targ_prog = map->init_slots[i];
5389 		fd = bpf_program__fd(targ_prog);
5390 
5391 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5392 		if (err) {
5393 			err = -errno;
5394 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5395 				map->name, i, targ_prog->name, fd, errstr(err));
5396 			return err;
5397 		}
5398 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5399 			 map->name, i, targ_prog->name, fd);
5400 	}
5401 
5402 	zfree(&map->init_slots);
5403 	map->init_slots_sz = 0;
5404 
5405 	return 0;
5406 }
5407 
bpf_object_init_prog_arrays(struct bpf_object * obj)5408 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5409 {
5410 	struct bpf_map *map;
5411 	int i, err;
5412 
5413 	for (i = 0; i < obj->nr_maps; i++) {
5414 		map = &obj->maps[i];
5415 
5416 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5417 			continue;
5418 
5419 		err = init_prog_array_slots(obj, map);
5420 		if (err < 0)
5421 			return err;
5422 	}
5423 	return 0;
5424 }
5425 
map_set_def_max_entries(struct bpf_map * map)5426 static int map_set_def_max_entries(struct bpf_map *map)
5427 {
5428 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5429 		int nr_cpus;
5430 
5431 		nr_cpus = libbpf_num_possible_cpus();
5432 		if (nr_cpus < 0) {
5433 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5434 				map->name, nr_cpus);
5435 			return nr_cpus;
5436 		}
5437 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5438 		map->def.max_entries = nr_cpus;
5439 	}
5440 
5441 	return 0;
5442 }
5443 
5444 static int
bpf_object__create_maps(struct bpf_object * obj)5445 bpf_object__create_maps(struct bpf_object *obj)
5446 {
5447 	struct bpf_map *map;
5448 	unsigned int i, j;
5449 	int err;
5450 	bool retried;
5451 
5452 	for (i = 0; i < obj->nr_maps; i++) {
5453 		map = &obj->maps[i];
5454 
5455 		/* To support old kernels, we skip creating global data maps
5456 		 * (.rodata, .data, .kconfig, etc); later on, during program
5457 		 * loading, if we detect that at least one of the to-be-loaded
5458 		 * programs is referencing any global data map, we'll error
5459 		 * out with program name and relocation index logged.
5460 		 * This approach allows to accommodate Clang emitting
5461 		 * unnecessary .rodata.str1.1 sections for string literals,
5462 		 * but also it allows to have CO-RE applications that use
5463 		 * global variables in some of BPF programs, but not others.
5464 		 * If those global variable-using programs are not loaded at
5465 		 * runtime due to bpf_program__set_autoload(prog, false),
5466 		 * bpf_object loading will succeed just fine even on old
5467 		 * kernels.
5468 		 */
5469 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5470 			map->autocreate = false;
5471 
5472 		if (!map->autocreate) {
5473 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5474 			continue;
5475 		}
5476 
5477 		err = map_set_def_max_entries(map);
5478 		if (err)
5479 			goto err_out;
5480 
5481 		retried = false;
5482 retry:
5483 		if (map->pin_path) {
5484 			err = bpf_object__reuse_map(map);
5485 			if (err) {
5486 				pr_warn("map '%s': error reusing pinned map\n",
5487 					map->name);
5488 				goto err_out;
5489 			}
5490 			if (retried && map->fd < 0) {
5491 				pr_warn("map '%s': cannot find pinned map\n",
5492 					map->name);
5493 				err = -ENOENT;
5494 				goto err_out;
5495 			}
5496 		}
5497 
5498 		if (map->reused) {
5499 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5500 				 map->name, map->fd);
5501 		} else {
5502 			err = bpf_object__create_map(obj, map, false);
5503 			if (err)
5504 				goto err_out;
5505 
5506 			pr_debug("map '%s': created successfully, fd=%d\n",
5507 				 map->name, map->fd);
5508 
5509 			if (bpf_map__is_internal(map)) {
5510 				err = bpf_object__populate_internal_map(obj, map);
5511 				if (err < 0)
5512 					goto err_out;
5513 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5514 				map->mmaped = mmap((void *)(long)map->map_extra,
5515 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5516 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5517 						   map->fd, 0);
5518 				if (map->mmaped == MAP_FAILED) {
5519 					err = -errno;
5520 					map->mmaped = NULL;
5521 					pr_warn("map '%s': failed to mmap arena: %s\n",
5522 						map->name, errstr(err));
5523 					return err;
5524 				}
5525 				if (obj->arena_data) {
5526 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5527 					zfree(&obj->arena_data);
5528 				}
5529 			}
5530 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5531 				err = init_map_in_map_slots(obj, map);
5532 				if (err < 0)
5533 					goto err_out;
5534 			}
5535 		}
5536 
5537 		if (map->pin_path && !map->pinned) {
5538 			err = bpf_map__pin(map, NULL);
5539 			if (err) {
5540 				if (!retried && err == -EEXIST) {
5541 					retried = true;
5542 					goto retry;
5543 				}
5544 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5545 					map->name, map->pin_path, errstr(err));
5546 				goto err_out;
5547 			}
5548 		}
5549 	}
5550 
5551 	return 0;
5552 
5553 err_out:
5554 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5555 	pr_perm_msg(err);
5556 	for (j = 0; j < i; j++)
5557 		zclose(obj->maps[j].fd);
5558 	return err;
5559 }
5560 
bpf_core_is_flavor_sep(const char * s)5561 static bool bpf_core_is_flavor_sep(const char *s)
5562 {
5563 	/* check X___Y name pattern, where X and Y are not underscores */
5564 	return s[0] != '_' &&				      /* X */
5565 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5566 	       s[4] != '_';				      /* Y */
5567 }
5568 
5569 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5570  * before last triple underscore. Struct name part after last triple
5571  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5572  */
bpf_core_essential_name_len(const char * name)5573 size_t bpf_core_essential_name_len(const char *name)
5574 {
5575 	size_t n = strlen(name);
5576 	int i;
5577 
5578 	for (i = n - 5; i >= 0; i--) {
5579 		if (bpf_core_is_flavor_sep(name + i))
5580 			return i + 1;
5581 	}
5582 	return n;
5583 }
5584 
bpf_core_free_cands(struct bpf_core_cand_list * cands)5585 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5586 {
5587 	if (!cands)
5588 		return;
5589 
5590 	free(cands->cands);
5591 	free(cands);
5592 }
5593 
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)5594 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5595 		       size_t local_essent_len,
5596 		       const struct btf *targ_btf,
5597 		       const char *targ_btf_name,
5598 		       int targ_start_id,
5599 		       struct bpf_core_cand_list *cands)
5600 {
5601 	struct bpf_core_cand *new_cands, *cand;
5602 	const struct btf_type *t, *local_t;
5603 	const char *targ_name, *local_name;
5604 	size_t targ_essent_len;
5605 	int n, i;
5606 
5607 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5608 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5609 
5610 	n = btf__type_cnt(targ_btf);
5611 	for (i = targ_start_id; i < n; i++) {
5612 		t = btf__type_by_id(targ_btf, i);
5613 		if (!btf_kind_core_compat(t, local_t))
5614 			continue;
5615 
5616 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5617 		if (str_is_empty(targ_name))
5618 			continue;
5619 
5620 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5621 		if (targ_essent_len != local_essent_len)
5622 			continue;
5623 
5624 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5625 			continue;
5626 
5627 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5628 			 local_cand->id, btf_kind_str(local_t),
5629 			 local_name, i, btf_kind_str(t), targ_name,
5630 			 targ_btf_name);
5631 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5632 					      sizeof(*cands->cands));
5633 		if (!new_cands)
5634 			return -ENOMEM;
5635 
5636 		cand = &new_cands[cands->len];
5637 		cand->btf = targ_btf;
5638 		cand->id = i;
5639 
5640 		cands->cands = new_cands;
5641 		cands->len++;
5642 	}
5643 	return 0;
5644 }
5645 
load_module_btfs(struct bpf_object * obj)5646 static int load_module_btfs(struct bpf_object *obj)
5647 {
5648 	struct bpf_btf_info info;
5649 	struct module_btf *mod_btf;
5650 	struct btf *btf;
5651 	char name[64];
5652 	__u32 id = 0, len;
5653 	int err, fd;
5654 
5655 	if (obj->btf_modules_loaded)
5656 		return 0;
5657 
5658 	if (obj->gen_loader)
5659 		return 0;
5660 
5661 	/* don't do this again, even if we find no module BTFs */
5662 	obj->btf_modules_loaded = true;
5663 
5664 	/* kernel too old to support module BTFs */
5665 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5666 		return 0;
5667 
5668 	while (true) {
5669 		err = bpf_btf_get_next_id(id, &id);
5670 		if (err && errno == ENOENT)
5671 			return 0;
5672 		if (err && errno == EPERM) {
5673 			pr_debug("skipping module BTFs loading, missing privileges\n");
5674 			return 0;
5675 		}
5676 		if (err) {
5677 			err = -errno;
5678 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5679 			return err;
5680 		}
5681 
5682 		fd = bpf_btf_get_fd_by_id(id);
5683 		if (fd < 0) {
5684 			if (errno == ENOENT)
5685 				continue; /* expected race: BTF was unloaded */
5686 			err = -errno;
5687 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5688 			return err;
5689 		}
5690 
5691 		len = sizeof(info);
5692 		memset(&info, 0, sizeof(info));
5693 		info.name = ptr_to_u64(name);
5694 		info.name_len = sizeof(name);
5695 
5696 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5697 		if (err) {
5698 			err = -errno;
5699 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5700 			goto err_out;
5701 		}
5702 
5703 		/* ignore non-module BTFs */
5704 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5705 			close(fd);
5706 			continue;
5707 		}
5708 
5709 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5710 		err = libbpf_get_error(btf);
5711 		if (err) {
5712 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5713 				name, id, errstr(err));
5714 			goto err_out;
5715 		}
5716 
5717 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5718 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5719 		if (err)
5720 			goto err_out;
5721 
5722 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5723 
5724 		mod_btf->btf = btf;
5725 		mod_btf->id = id;
5726 		mod_btf->fd = fd;
5727 		mod_btf->name = strdup(name);
5728 		if (!mod_btf->name) {
5729 			err = -ENOMEM;
5730 			goto err_out;
5731 		}
5732 		continue;
5733 
5734 err_out:
5735 		close(fd);
5736 		return err;
5737 	}
5738 
5739 	return 0;
5740 }
5741 
5742 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5743 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5744 {
5745 	struct bpf_core_cand local_cand = {};
5746 	struct bpf_core_cand_list *cands;
5747 	const struct btf *main_btf;
5748 	const struct btf_type *local_t;
5749 	const char *local_name;
5750 	size_t local_essent_len;
5751 	int err, i;
5752 
5753 	local_cand.btf = local_btf;
5754 	local_cand.id = local_type_id;
5755 	local_t = btf__type_by_id(local_btf, local_type_id);
5756 	if (!local_t)
5757 		return ERR_PTR(-EINVAL);
5758 
5759 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5760 	if (str_is_empty(local_name))
5761 		return ERR_PTR(-EINVAL);
5762 	local_essent_len = bpf_core_essential_name_len(local_name);
5763 
5764 	cands = calloc(1, sizeof(*cands));
5765 	if (!cands)
5766 		return ERR_PTR(-ENOMEM);
5767 
5768 	/* Attempt to find target candidates in vmlinux BTF first */
5769 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5770 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5771 	if (err)
5772 		goto err_out;
5773 
5774 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5775 	if (cands->len)
5776 		return cands;
5777 
5778 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5779 	if (obj->btf_vmlinux_override)
5780 		return cands;
5781 
5782 	/* now look through module BTFs, trying to still find candidates */
5783 	err = load_module_btfs(obj);
5784 	if (err)
5785 		goto err_out;
5786 
5787 	for (i = 0; i < obj->btf_module_cnt; i++) {
5788 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5789 					 obj->btf_modules[i].btf,
5790 					 obj->btf_modules[i].name,
5791 					 btf__type_cnt(obj->btf_vmlinux),
5792 					 cands);
5793 		if (err)
5794 			goto err_out;
5795 	}
5796 
5797 	return cands;
5798 err_out:
5799 	bpf_core_free_cands(cands);
5800 	return ERR_PTR(err);
5801 }
5802 
5803 /* Check local and target types for compatibility. This check is used for
5804  * type-based CO-RE relocations and follow slightly different rules than
5805  * field-based relocations. This function assumes that root types were already
5806  * checked for name match. Beyond that initial root-level name check, names
5807  * are completely ignored. Compatibility rules are as follows:
5808  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5809  *     kind should match for local and target types (i.e., STRUCT is not
5810  *     compatible with UNION);
5811  *   - for ENUMs, the size is ignored;
5812  *   - for INT, size and signedness are ignored;
5813  *   - for ARRAY, dimensionality is ignored, element types are checked for
5814  *     compatibility recursively;
5815  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5816  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5817  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5818  *     number of input args and compatible return and argument types.
5819  * These rules are not set in stone and probably will be adjusted as we get
5820  * more experience with using BPF CO-RE relocations.
5821  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5822 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5823 			      const struct btf *targ_btf, __u32 targ_id)
5824 {
5825 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5826 }
5827 
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5828 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5829 			 const struct btf *targ_btf, __u32 targ_id)
5830 {
5831 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5832 }
5833 
bpf_core_hash_fn(const long key,void * ctx)5834 static size_t bpf_core_hash_fn(const long key, void *ctx)
5835 {
5836 	return key;
5837 }
5838 
bpf_core_equal_fn(const long k1,const long k2,void * ctx)5839 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5840 {
5841 	return k1 == k2;
5842 }
5843 
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5844 static int record_relo_core(struct bpf_program *prog,
5845 			    const struct bpf_core_relo *core_relo, int insn_idx)
5846 {
5847 	struct reloc_desc *relos, *relo;
5848 
5849 	relos = libbpf_reallocarray(prog->reloc_desc,
5850 				    prog->nr_reloc + 1, sizeof(*relos));
5851 	if (!relos)
5852 		return -ENOMEM;
5853 	relo = &relos[prog->nr_reloc];
5854 	relo->type = RELO_CORE;
5855 	relo->insn_idx = insn_idx;
5856 	relo->core_relo = core_relo;
5857 	prog->reloc_desc = relos;
5858 	prog->nr_reloc++;
5859 	return 0;
5860 }
5861 
find_relo_core(struct bpf_program * prog,int insn_idx)5862 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5863 {
5864 	struct reloc_desc *relo;
5865 	int i;
5866 
5867 	for (i = 0; i < prog->nr_reloc; i++) {
5868 		relo = &prog->reloc_desc[i];
5869 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5870 			continue;
5871 
5872 		return relo->core_relo;
5873 	}
5874 
5875 	return NULL;
5876 }
5877 
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)5878 static int bpf_core_resolve_relo(struct bpf_program *prog,
5879 				 const struct bpf_core_relo *relo,
5880 				 int relo_idx,
5881 				 const struct btf *local_btf,
5882 				 struct hashmap *cand_cache,
5883 				 struct bpf_core_relo_res *targ_res)
5884 {
5885 	struct bpf_core_spec specs_scratch[3] = {};
5886 	struct bpf_core_cand_list *cands = NULL;
5887 	const char *prog_name = prog->name;
5888 	const struct btf_type *local_type;
5889 	const char *local_name;
5890 	__u32 local_id = relo->type_id;
5891 	int err;
5892 
5893 	local_type = btf__type_by_id(local_btf, local_id);
5894 	if (!local_type)
5895 		return -EINVAL;
5896 
5897 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5898 	if (!local_name)
5899 		return -EINVAL;
5900 
5901 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5902 	    !hashmap__find(cand_cache, local_id, &cands)) {
5903 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5904 		if (IS_ERR(cands)) {
5905 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5906 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5907 				local_name, PTR_ERR(cands));
5908 			return PTR_ERR(cands);
5909 		}
5910 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5911 		if (err) {
5912 			bpf_core_free_cands(cands);
5913 			return err;
5914 		}
5915 	}
5916 
5917 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5918 				       targ_res);
5919 }
5920 
5921 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5922 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5923 {
5924 	const struct btf_ext_info_sec *sec;
5925 	struct bpf_core_relo_res targ_res;
5926 	const struct bpf_core_relo *rec;
5927 	const struct btf_ext_info *seg;
5928 	struct hashmap_entry *entry;
5929 	struct hashmap *cand_cache = NULL;
5930 	struct bpf_program *prog;
5931 	struct bpf_insn *insn;
5932 	const char *sec_name;
5933 	int i, err = 0, insn_idx, sec_idx, sec_num;
5934 
5935 	if (obj->btf_ext->core_relo_info.len == 0)
5936 		return 0;
5937 
5938 	if (targ_btf_path) {
5939 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5940 		err = libbpf_get_error(obj->btf_vmlinux_override);
5941 		if (err) {
5942 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
5943 			return err;
5944 		}
5945 	}
5946 
5947 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5948 	if (IS_ERR(cand_cache)) {
5949 		err = PTR_ERR(cand_cache);
5950 		goto out;
5951 	}
5952 
5953 	seg = &obj->btf_ext->core_relo_info;
5954 	sec_num = 0;
5955 	for_each_btf_ext_sec(seg, sec) {
5956 		sec_idx = seg->sec_idxs[sec_num];
5957 		sec_num++;
5958 
5959 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5960 		if (str_is_empty(sec_name)) {
5961 			err = -EINVAL;
5962 			goto out;
5963 		}
5964 
5965 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5966 
5967 		for_each_btf_ext_rec(seg, sec, i, rec) {
5968 			if (rec->insn_off % BPF_INSN_SZ)
5969 				return -EINVAL;
5970 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5971 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5972 			if (!prog) {
5973 				/* When __weak subprog is "overridden" by another instance
5974 				 * of the subprog from a different object file, linker still
5975 				 * appends all the .BTF.ext info that used to belong to that
5976 				 * eliminated subprogram.
5977 				 * This is similar to what x86-64 linker does for relocations.
5978 				 * So just ignore such relocations just like we ignore
5979 				 * subprog instructions when discovering subprograms.
5980 				 */
5981 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5982 					 sec_name, i, insn_idx);
5983 				continue;
5984 			}
5985 			/* no need to apply CO-RE relocation if the program is
5986 			 * not going to be loaded
5987 			 */
5988 			if (!prog->autoload)
5989 				continue;
5990 
5991 			/* adjust insn_idx from section frame of reference to the local
5992 			 * program's frame of reference; (sub-)program code is not yet
5993 			 * relocated, so it's enough to just subtract in-section offset
5994 			 */
5995 			insn_idx = insn_idx - prog->sec_insn_off;
5996 			if (insn_idx >= prog->insns_cnt)
5997 				return -EINVAL;
5998 			insn = &prog->insns[insn_idx];
5999 
6000 			err = record_relo_core(prog, rec, insn_idx);
6001 			if (err) {
6002 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6003 					prog->name, i, errstr(err));
6004 				goto out;
6005 			}
6006 
6007 			if (prog->obj->gen_loader)
6008 				continue;
6009 
6010 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6011 			if (err) {
6012 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6013 					prog->name, i, errstr(err));
6014 				goto out;
6015 			}
6016 
6017 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6018 			if (err) {
6019 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6020 					prog->name, i, insn_idx, errstr(err));
6021 				goto out;
6022 			}
6023 		}
6024 	}
6025 
6026 out:
6027 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6028 	btf__free(obj->btf_vmlinux_override);
6029 	obj->btf_vmlinux_override = NULL;
6030 
6031 	if (!IS_ERR_OR_NULL(cand_cache)) {
6032 		hashmap__for_each_entry(cand_cache, entry, i) {
6033 			bpf_core_free_cands(entry->pvalue);
6034 		}
6035 		hashmap__free(cand_cache);
6036 	}
6037 	return err;
6038 }
6039 
6040 /* base map load ldimm64 special constant, used also for log fixup logic */
6041 #define POISON_LDIMM64_MAP_BASE 2001000000
6042 #define POISON_LDIMM64_MAP_PFX "200100"
6043 
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)6044 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6045 			       int insn_idx, struct bpf_insn *insn,
6046 			       int map_idx, const struct bpf_map *map)
6047 {
6048 	int i;
6049 
6050 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6051 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6052 
6053 	/* we turn single ldimm64 into two identical invalid calls */
6054 	for (i = 0; i < 2; i++) {
6055 		insn->code = BPF_JMP | BPF_CALL;
6056 		insn->dst_reg = 0;
6057 		insn->src_reg = 0;
6058 		insn->off = 0;
6059 		/* if this instruction is reachable (not a dead code),
6060 		 * verifier will complain with something like:
6061 		 * invalid func unknown#2001000123
6062 		 * where lower 123 is map index into obj->maps[] array
6063 		 */
6064 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6065 
6066 		insn++;
6067 	}
6068 }
6069 
6070 /* unresolved kfunc call special constant, used also for log fixup logic */
6071 #define POISON_CALL_KFUNC_BASE 2002000000
6072 #define POISON_CALL_KFUNC_PFX "2002"
6073 
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)6074 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6075 			      int insn_idx, struct bpf_insn *insn,
6076 			      int ext_idx, const struct extern_desc *ext)
6077 {
6078 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6079 		 prog->name, relo_idx, insn_idx, ext->name);
6080 
6081 	/* we turn kfunc call into invalid helper call with identifiable constant */
6082 	insn->code = BPF_JMP | BPF_CALL;
6083 	insn->dst_reg = 0;
6084 	insn->src_reg = 0;
6085 	insn->off = 0;
6086 	/* if this instruction is reachable (not a dead code),
6087 	 * verifier will complain with something like:
6088 	 * invalid func unknown#2001000123
6089 	 * where lower 123 is extern index into obj->externs[] array
6090 	 */
6091 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6092 }
6093 
6094 /* Relocate data references within program code:
6095  *  - map references;
6096  *  - global variable references;
6097  *  - extern references.
6098  */
6099 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)6100 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6101 {
6102 	int i;
6103 
6104 	for (i = 0; i < prog->nr_reloc; i++) {
6105 		struct reloc_desc *relo = &prog->reloc_desc[i];
6106 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6107 		const struct bpf_map *map;
6108 		struct extern_desc *ext;
6109 
6110 		switch (relo->type) {
6111 		case RELO_LD64:
6112 			map = &obj->maps[relo->map_idx];
6113 			if (obj->gen_loader) {
6114 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6115 				insn[0].imm = relo->map_idx;
6116 			} else if (map->autocreate) {
6117 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6118 				insn[0].imm = map->fd;
6119 			} else {
6120 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6121 						   relo->map_idx, map);
6122 			}
6123 			break;
6124 		case RELO_DATA:
6125 			map = &obj->maps[relo->map_idx];
6126 			insn[1].imm = insn[0].imm + relo->sym_off;
6127 			if (obj->gen_loader) {
6128 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6129 				insn[0].imm = relo->map_idx;
6130 			} else if (map->autocreate) {
6131 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6132 				insn[0].imm = map->fd;
6133 			} else {
6134 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6135 						   relo->map_idx, map);
6136 			}
6137 			break;
6138 		case RELO_EXTERN_LD64:
6139 			ext = &obj->externs[relo->ext_idx];
6140 			if (ext->type == EXT_KCFG) {
6141 				if (obj->gen_loader) {
6142 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6143 					insn[0].imm = obj->kconfig_map_idx;
6144 				} else {
6145 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6146 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6147 				}
6148 				insn[1].imm = ext->kcfg.data_off;
6149 			} else /* EXT_KSYM */ {
6150 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6151 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6152 					insn[0].imm = ext->ksym.kernel_btf_id;
6153 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6154 				} else { /* typeless ksyms or unresolved typed ksyms */
6155 					insn[0].imm = (__u32)ext->ksym.addr;
6156 					insn[1].imm = ext->ksym.addr >> 32;
6157 				}
6158 			}
6159 			break;
6160 		case RELO_EXTERN_CALL:
6161 			ext = &obj->externs[relo->ext_idx];
6162 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6163 			if (ext->is_set) {
6164 				insn[0].imm = ext->ksym.kernel_btf_id;
6165 				insn[0].off = ext->ksym.btf_fd_idx;
6166 			} else { /* unresolved weak kfunc call */
6167 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6168 						  relo->ext_idx, ext);
6169 			}
6170 			break;
6171 		case RELO_SUBPROG_ADDR:
6172 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6173 				pr_warn("prog '%s': relo #%d: bad insn\n",
6174 					prog->name, i);
6175 				return -EINVAL;
6176 			}
6177 			/* handled already */
6178 			break;
6179 		case RELO_CALL:
6180 			/* handled already */
6181 			break;
6182 		case RELO_CORE:
6183 			/* will be handled by bpf_program_record_relos() */
6184 			break;
6185 		default:
6186 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6187 				prog->name, i, relo->type);
6188 			return -EINVAL;
6189 		}
6190 	}
6191 
6192 	return 0;
6193 }
6194 
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)6195 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6196 				    const struct bpf_program *prog,
6197 				    const struct btf_ext_info *ext_info,
6198 				    void **prog_info, __u32 *prog_rec_cnt,
6199 				    __u32 *prog_rec_sz)
6200 {
6201 	void *copy_start = NULL, *copy_end = NULL;
6202 	void *rec, *rec_end, *new_prog_info;
6203 	const struct btf_ext_info_sec *sec;
6204 	size_t old_sz, new_sz;
6205 	int i, sec_num, sec_idx, off_adj;
6206 
6207 	sec_num = 0;
6208 	for_each_btf_ext_sec(ext_info, sec) {
6209 		sec_idx = ext_info->sec_idxs[sec_num];
6210 		sec_num++;
6211 		if (prog->sec_idx != sec_idx)
6212 			continue;
6213 
6214 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6215 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6216 
6217 			if (insn_off < prog->sec_insn_off)
6218 				continue;
6219 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6220 				break;
6221 
6222 			if (!copy_start)
6223 				copy_start = rec;
6224 			copy_end = rec + ext_info->rec_size;
6225 		}
6226 
6227 		if (!copy_start)
6228 			return -ENOENT;
6229 
6230 		/* append func/line info of a given (sub-)program to the main
6231 		 * program func/line info
6232 		 */
6233 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6234 		new_sz = old_sz + (copy_end - copy_start);
6235 		new_prog_info = realloc(*prog_info, new_sz);
6236 		if (!new_prog_info)
6237 			return -ENOMEM;
6238 		*prog_info = new_prog_info;
6239 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6240 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6241 
6242 		/* Kernel instruction offsets are in units of 8-byte
6243 		 * instructions, while .BTF.ext instruction offsets generated
6244 		 * by Clang are in units of bytes. So convert Clang offsets
6245 		 * into kernel offsets and adjust offset according to program
6246 		 * relocated position.
6247 		 */
6248 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6249 		rec = new_prog_info + old_sz;
6250 		rec_end = new_prog_info + new_sz;
6251 		for (; rec < rec_end; rec += ext_info->rec_size) {
6252 			__u32 *insn_off = rec;
6253 
6254 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6255 		}
6256 		*prog_rec_sz = ext_info->rec_size;
6257 		return 0;
6258 	}
6259 
6260 	return -ENOENT;
6261 }
6262 
6263 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6264 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6265 			      struct bpf_program *main_prog,
6266 			      const struct bpf_program *prog)
6267 {
6268 	int err;
6269 
6270 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6271 	 * support func/line info
6272 	 */
6273 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6274 		return 0;
6275 
6276 	/* only attempt func info relocation if main program's func_info
6277 	 * relocation was successful
6278 	 */
6279 	if (main_prog != prog && !main_prog->func_info)
6280 		goto line_info;
6281 
6282 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6283 				       &main_prog->func_info,
6284 				       &main_prog->func_info_cnt,
6285 				       &main_prog->func_info_rec_size);
6286 	if (err) {
6287 		if (err != -ENOENT) {
6288 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6289 				prog->name, errstr(err));
6290 			return err;
6291 		}
6292 		if (main_prog->func_info) {
6293 			/*
6294 			 * Some info has already been found but has problem
6295 			 * in the last btf_ext reloc. Must have to error out.
6296 			 */
6297 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6298 			return err;
6299 		}
6300 		/* Have problem loading the very first info. Ignore the rest. */
6301 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6302 			prog->name);
6303 	}
6304 
6305 line_info:
6306 	/* don't relocate line info if main program's relocation failed */
6307 	if (main_prog != prog && !main_prog->line_info)
6308 		return 0;
6309 
6310 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6311 				       &main_prog->line_info,
6312 				       &main_prog->line_info_cnt,
6313 				       &main_prog->line_info_rec_size);
6314 	if (err) {
6315 		if (err != -ENOENT) {
6316 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6317 				prog->name, errstr(err));
6318 			return err;
6319 		}
6320 		if (main_prog->line_info) {
6321 			/*
6322 			 * Some info has already been found but has problem
6323 			 * in the last btf_ext reloc. Must have to error out.
6324 			 */
6325 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6326 			return err;
6327 		}
6328 		/* Have problem loading the very first info. Ignore the rest. */
6329 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6330 			prog->name);
6331 	}
6332 	return 0;
6333 }
6334 
cmp_relo_by_insn_idx(const void * key,const void * elem)6335 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6336 {
6337 	size_t insn_idx = *(const size_t *)key;
6338 	const struct reloc_desc *relo = elem;
6339 
6340 	if (insn_idx == relo->insn_idx)
6341 		return 0;
6342 	return insn_idx < relo->insn_idx ? -1 : 1;
6343 }
6344 
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6345 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6346 {
6347 	if (!prog->nr_reloc)
6348 		return NULL;
6349 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6350 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6351 }
6352 
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6353 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6354 {
6355 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6356 	struct reloc_desc *relos;
6357 	int i;
6358 
6359 	if (main_prog == subprog)
6360 		return 0;
6361 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6362 	/* if new count is zero, reallocarray can return a valid NULL result;
6363 	 * in this case the previous pointer will be freed, so we *have to*
6364 	 * reassign old pointer to the new value (even if it's NULL)
6365 	 */
6366 	if (!relos && new_cnt)
6367 		return -ENOMEM;
6368 	if (subprog->nr_reloc)
6369 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6370 		       sizeof(*relos) * subprog->nr_reloc);
6371 
6372 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6373 		relos[i].insn_idx += subprog->sub_insn_off;
6374 	/* After insn_idx adjustment the 'relos' array is still sorted
6375 	 * by insn_idx and doesn't break bsearch.
6376 	 */
6377 	main_prog->reloc_desc = relos;
6378 	main_prog->nr_reloc = new_cnt;
6379 	return 0;
6380 }
6381 
6382 static int
bpf_object__append_subprog_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * subprog)6383 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6384 				struct bpf_program *subprog)
6385 {
6386        struct bpf_insn *insns;
6387        size_t new_cnt;
6388        int err;
6389 
6390        subprog->sub_insn_off = main_prog->insns_cnt;
6391 
6392        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6393        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6394        if (!insns) {
6395                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6396                return -ENOMEM;
6397        }
6398        main_prog->insns = insns;
6399        main_prog->insns_cnt = new_cnt;
6400 
6401        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6402               subprog->insns_cnt * sizeof(*insns));
6403 
6404        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6405                 main_prog->name, subprog->insns_cnt, subprog->name);
6406 
6407        /* The subprog insns are now appended. Append its relos too. */
6408        err = append_subprog_relos(main_prog, subprog);
6409        if (err)
6410                return err;
6411        return 0;
6412 }
6413 
6414 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6415 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6416 		       struct bpf_program *prog)
6417 {
6418 	size_t sub_insn_idx, insn_idx;
6419 	struct bpf_program *subprog;
6420 	struct reloc_desc *relo;
6421 	struct bpf_insn *insn;
6422 	int err;
6423 
6424 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6425 	if (err)
6426 		return err;
6427 
6428 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6429 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6430 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6431 			continue;
6432 
6433 		relo = find_prog_insn_relo(prog, insn_idx);
6434 		if (relo && relo->type == RELO_EXTERN_CALL)
6435 			/* kfunc relocations will be handled later
6436 			 * in bpf_object__relocate_data()
6437 			 */
6438 			continue;
6439 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6440 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6441 				prog->name, insn_idx, relo->type);
6442 			return -LIBBPF_ERRNO__RELOC;
6443 		}
6444 		if (relo) {
6445 			/* sub-program instruction index is a combination of
6446 			 * an offset of a symbol pointed to by relocation and
6447 			 * call instruction's imm field; for global functions,
6448 			 * call always has imm = -1, but for static functions
6449 			 * relocation is against STT_SECTION and insn->imm
6450 			 * points to a start of a static function
6451 			 *
6452 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6453 			 * the byte offset in the corresponding section.
6454 			 */
6455 			if (relo->type == RELO_CALL)
6456 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6457 			else
6458 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6459 		} else if (insn_is_pseudo_func(insn)) {
6460 			/*
6461 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6462 			 * functions are in the same section, so it shouldn't reach here.
6463 			 */
6464 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6465 				prog->name, insn_idx);
6466 			return -LIBBPF_ERRNO__RELOC;
6467 		} else {
6468 			/* if subprogram call is to a static function within
6469 			 * the same ELF section, there won't be any relocation
6470 			 * emitted, but it also means there is no additional
6471 			 * offset necessary, insns->imm is relative to
6472 			 * instruction's original position within the section
6473 			 */
6474 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6475 		}
6476 
6477 		/* we enforce that sub-programs should be in .text section */
6478 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6479 		if (!subprog) {
6480 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6481 				prog->name);
6482 			return -LIBBPF_ERRNO__RELOC;
6483 		}
6484 
6485 		/* if it's the first call instruction calling into this
6486 		 * subprogram (meaning this subprog hasn't been processed
6487 		 * yet) within the context of current main program:
6488 		 *   - append it at the end of main program's instructions blog;
6489 		 *   - process is recursively, while current program is put on hold;
6490 		 *   - if that subprogram calls some other not yet processes
6491 		 *   subprogram, same thing will happen recursively until
6492 		 *   there are no more unprocesses subprograms left to append
6493 		 *   and relocate.
6494 		 */
6495 		if (subprog->sub_insn_off == 0) {
6496 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6497 			if (err)
6498 				return err;
6499 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6500 			if (err)
6501 				return err;
6502 		}
6503 
6504 		/* main_prog->insns memory could have been re-allocated, so
6505 		 * calculate pointer again
6506 		 */
6507 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6508 		/* calculate correct instruction position within current main
6509 		 * prog; each main prog can have a different set of
6510 		 * subprograms appended (potentially in different order as
6511 		 * well), so position of any subprog can be different for
6512 		 * different main programs
6513 		 */
6514 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6515 
6516 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6517 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6518 	}
6519 
6520 	return 0;
6521 }
6522 
6523 /*
6524  * Relocate sub-program calls.
6525  *
6526  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6527  * main prog) is processed separately. For each subprog (non-entry functions,
6528  * that can be called from either entry progs or other subprogs) gets their
6529  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6530  * hasn't been yet appended and relocated within current main prog. Once its
6531  * relocated, sub_insn_off will point at the position within current main prog
6532  * where given subprog was appended. This will further be used to relocate all
6533  * the call instructions jumping into this subprog.
6534  *
6535  * We start with main program and process all call instructions. If the call
6536  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6537  * is zero), subprog instructions are appended at the end of main program's
6538  * instruction array. Then main program is "put on hold" while we recursively
6539  * process newly appended subprogram. If that subprogram calls into another
6540  * subprogram that hasn't been appended, new subprogram is appended again to
6541  * the *main* prog's instructions (subprog's instructions are always left
6542  * untouched, as they need to be in unmodified state for subsequent main progs
6543  * and subprog instructions are always sent only as part of a main prog) and
6544  * the process continues recursively. Once all the subprogs called from a main
6545  * prog or any of its subprogs are appended (and relocated), all their
6546  * positions within finalized instructions array are known, so it's easy to
6547  * rewrite call instructions with correct relative offsets, corresponding to
6548  * desired target subprog.
6549  *
6550  * Its important to realize that some subprogs might not be called from some
6551  * main prog and any of its called/used subprogs. Those will keep their
6552  * subprog->sub_insn_off as zero at all times and won't be appended to current
6553  * main prog and won't be relocated within the context of current main prog.
6554  * They might still be used from other main progs later.
6555  *
6556  * Visually this process can be shown as below. Suppose we have two main
6557  * programs mainA and mainB and BPF object contains three subprogs: subA,
6558  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6559  * subC both call subB:
6560  *
6561  *        +--------+ +-------+
6562  *        |        v v       |
6563  *     +--+---+ +--+-+-+ +---+--+
6564  *     | subA | | subB | | subC |
6565  *     +--+---+ +------+ +---+--+
6566  *        ^                  ^
6567  *        |                  |
6568  *    +---+-------+   +------+----+
6569  *    |   mainA   |   |   mainB   |
6570  *    +-----------+   +-----------+
6571  *
6572  * We'll start relocating mainA, will find subA, append it and start
6573  * processing sub A recursively:
6574  *
6575  *    +-----------+------+
6576  *    |   mainA   | subA |
6577  *    +-----------+------+
6578  *
6579  * At this point we notice that subB is used from subA, so we append it and
6580  * relocate (there are no further subcalls from subB):
6581  *
6582  *    +-----------+------+------+
6583  *    |   mainA   | subA | subB |
6584  *    +-----------+------+------+
6585  *
6586  * At this point, we relocate subA calls, then go one level up and finish with
6587  * relocatin mainA calls. mainA is done.
6588  *
6589  * For mainB process is similar but results in different order. We start with
6590  * mainB and skip subA and subB, as mainB never calls them (at least
6591  * directly), but we see subC is needed, so we append and start processing it:
6592  *
6593  *    +-----------+------+
6594  *    |   mainB   | subC |
6595  *    +-----------+------+
6596  * Now we see subC needs subB, so we go back to it, append and relocate it:
6597  *
6598  *    +-----------+------+------+
6599  *    |   mainB   | subC | subB |
6600  *    +-----------+------+------+
6601  *
6602  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6603  */
6604 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6605 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6606 {
6607 	struct bpf_program *subprog;
6608 	int i, err;
6609 
6610 	/* mark all subprogs as not relocated (yet) within the context of
6611 	 * current main program
6612 	 */
6613 	for (i = 0; i < obj->nr_programs; i++) {
6614 		subprog = &obj->programs[i];
6615 		if (!prog_is_subprog(obj, subprog))
6616 			continue;
6617 
6618 		subprog->sub_insn_off = 0;
6619 	}
6620 
6621 	err = bpf_object__reloc_code(obj, prog, prog);
6622 	if (err)
6623 		return err;
6624 
6625 	return 0;
6626 }
6627 
6628 static void
bpf_object__free_relocs(struct bpf_object * obj)6629 bpf_object__free_relocs(struct bpf_object *obj)
6630 {
6631 	struct bpf_program *prog;
6632 	int i;
6633 
6634 	/* free up relocation descriptors */
6635 	for (i = 0; i < obj->nr_programs; i++) {
6636 		prog = &obj->programs[i];
6637 		zfree(&prog->reloc_desc);
6638 		prog->nr_reloc = 0;
6639 	}
6640 }
6641 
cmp_relocs(const void * _a,const void * _b)6642 static int cmp_relocs(const void *_a, const void *_b)
6643 {
6644 	const struct reloc_desc *a = _a;
6645 	const struct reloc_desc *b = _b;
6646 
6647 	if (a->insn_idx != b->insn_idx)
6648 		return a->insn_idx < b->insn_idx ? -1 : 1;
6649 
6650 	/* no two relocations should have the same insn_idx, but ... */
6651 	if (a->type != b->type)
6652 		return a->type < b->type ? -1 : 1;
6653 
6654 	return 0;
6655 }
6656 
bpf_object__sort_relos(struct bpf_object * obj)6657 static void bpf_object__sort_relos(struct bpf_object *obj)
6658 {
6659 	int i;
6660 
6661 	for (i = 0; i < obj->nr_programs; i++) {
6662 		struct bpf_program *p = &obj->programs[i];
6663 
6664 		if (!p->nr_reloc)
6665 			continue;
6666 
6667 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6668 	}
6669 }
6670 
bpf_prog_assign_exc_cb(struct bpf_object * obj,struct bpf_program * prog)6671 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6672 {
6673 	const char *str = "exception_callback:";
6674 	size_t pfx_len = strlen(str);
6675 	int i, j, n;
6676 
6677 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6678 		return 0;
6679 
6680 	n = btf__type_cnt(obj->btf);
6681 	for (i = 1; i < n; i++) {
6682 		const char *name;
6683 		struct btf_type *t;
6684 
6685 		t = btf_type_by_id(obj->btf, i);
6686 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6687 			continue;
6688 
6689 		name = btf__str_by_offset(obj->btf, t->name_off);
6690 		if (strncmp(name, str, pfx_len) != 0)
6691 			continue;
6692 
6693 		t = btf_type_by_id(obj->btf, t->type);
6694 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6695 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6696 				prog->name);
6697 			return -EINVAL;
6698 		}
6699 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6700 			continue;
6701 		/* Multiple callbacks are specified for the same prog,
6702 		 * the verifier will eventually return an error for this
6703 		 * case, hence simply skip appending a subprog.
6704 		 */
6705 		if (prog->exception_cb_idx >= 0) {
6706 			prog->exception_cb_idx = -1;
6707 			break;
6708 		}
6709 
6710 		name += pfx_len;
6711 		if (str_is_empty(name)) {
6712 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6713 				prog->name);
6714 			return -EINVAL;
6715 		}
6716 
6717 		for (j = 0; j < obj->nr_programs; j++) {
6718 			struct bpf_program *subprog = &obj->programs[j];
6719 
6720 			if (!prog_is_subprog(obj, subprog))
6721 				continue;
6722 			if (strcmp(name, subprog->name) != 0)
6723 				continue;
6724 			/* Enforce non-hidden, as from verifier point of
6725 			 * view it expects global functions, whereas the
6726 			 * mark_btf_static fixes up linkage as static.
6727 			 */
6728 			if (!subprog->sym_global || subprog->mark_btf_static) {
6729 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6730 					prog->name, subprog->name);
6731 				return -EINVAL;
6732 			}
6733 			/* Let's see if we already saw a static exception callback with the same name */
6734 			if (prog->exception_cb_idx >= 0) {
6735 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6736 					prog->name, subprog->name);
6737 				return -EINVAL;
6738 			}
6739 			prog->exception_cb_idx = j;
6740 			break;
6741 		}
6742 
6743 		if (prog->exception_cb_idx >= 0)
6744 			continue;
6745 
6746 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6747 		return -ENOENT;
6748 	}
6749 
6750 	return 0;
6751 }
6752 
6753 static struct {
6754 	enum bpf_prog_type prog_type;
6755 	const char *ctx_name;
6756 } global_ctx_map[] = {
6757 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6758 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6759 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6760 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6761 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6762 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6763 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6764 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6765 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6766 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6767 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6768 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6769 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6770 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6771 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6772 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6773 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6774 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6775 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6776 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6777 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6778 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6779 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6780 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6781 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6782 	/* all other program types don't have "named" context structs */
6783 };
6784 
6785 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6786  * for below __builtin_types_compatible_p() checks;
6787  * with this approach we don't need any extra arch-specific #ifdef guards
6788  */
6789 struct pt_regs;
6790 struct user_pt_regs;
6791 struct user_regs_struct;
6792 
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)6793 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6794 				     const char *subprog_name, int arg_idx,
6795 				     int arg_type_id, const char *ctx_name)
6796 {
6797 	const struct btf_type *t;
6798 	const char *tname;
6799 
6800 	/* check if existing parameter already matches verifier expectations */
6801 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6802 	if (!btf_is_ptr(t))
6803 		goto out_warn;
6804 
6805 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6806 	 * and perf_event programs, so check this case early on and forget
6807 	 * about it for subsequent checks
6808 	 */
6809 	while (btf_is_mod(t))
6810 		t = btf__type_by_id(btf, t->type);
6811 	if (btf_is_typedef(t) &&
6812 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6813 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6814 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6815 			return false; /* canonical type for kprobe/perf_event */
6816 	}
6817 
6818 	/* now we can ignore typedefs moving forward */
6819 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6820 
6821 	/* if it's `void *`, definitely fix up BTF info */
6822 	if (btf_is_void(t))
6823 		return true;
6824 
6825 	/* if it's already proper canonical type, no need to fix up */
6826 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6827 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6828 		return false;
6829 
6830 	/* special cases */
6831 	switch (prog->type) {
6832 	case BPF_PROG_TYPE_KPROBE:
6833 		/* `struct pt_regs *` is expected, but we need to fix up */
6834 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6835 			return true;
6836 		break;
6837 	case BPF_PROG_TYPE_PERF_EVENT:
6838 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6839 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6840 			return true;
6841 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6842 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6843 			return true;
6844 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6845 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6846 			return true;
6847 		break;
6848 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6849 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6850 		/* allow u64* as ctx */
6851 		if (btf_is_int(t) && t->size == 8)
6852 			return true;
6853 		break;
6854 	default:
6855 		break;
6856 	}
6857 
6858 out_warn:
6859 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6860 		prog->name, subprog_name, arg_idx, ctx_name);
6861 	return false;
6862 }
6863 
clone_func_btf_info(struct btf * btf,int orig_fn_id,struct bpf_program * prog)6864 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6865 {
6866 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6867 	int i, err, arg_cnt, fn_name_off, linkage;
6868 	struct btf_type *fn_t, *fn_proto_t, *t;
6869 	struct btf_param *p;
6870 
6871 	/* caller already validated FUNC -> FUNC_PROTO validity */
6872 	fn_t = btf_type_by_id(btf, orig_fn_id);
6873 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6874 
6875 	/* Note that each btf__add_xxx() operation invalidates
6876 	 * all btf_type and string pointers, so we need to be
6877 	 * very careful when cloning BTF types. BTF type
6878 	 * pointers have to be always refetched. And to avoid
6879 	 * problems with invalidated string pointers, we
6880 	 * add empty strings initially, then just fix up
6881 	 * name_off offsets in place. Offsets are stable for
6882 	 * existing strings, so that works out.
6883 	 */
6884 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6885 	linkage = btf_func_linkage(fn_t);
6886 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6887 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6888 	arg_cnt = btf_vlen(fn_proto_t);
6889 
6890 	/* clone FUNC_PROTO and its params */
6891 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6892 	if (fn_proto_id < 0)
6893 		return -EINVAL;
6894 
6895 	for (i = 0; i < arg_cnt; i++) {
6896 		int name_off;
6897 
6898 		/* copy original parameter data */
6899 		t = btf_type_by_id(btf, orig_proto_id);
6900 		p = &btf_params(t)[i];
6901 		name_off = p->name_off;
6902 
6903 		err = btf__add_func_param(btf, "", p->type);
6904 		if (err)
6905 			return err;
6906 
6907 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6908 		p = &btf_params(fn_proto_t)[i];
6909 		p->name_off = name_off; /* use remembered str offset */
6910 	}
6911 
6912 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6913 	 * entry program's name as a placeholder, which we replace immediately
6914 	 * with original name_off
6915 	 */
6916 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6917 	if (fn_id < 0)
6918 		return -EINVAL;
6919 
6920 	fn_t = btf_type_by_id(btf, fn_id);
6921 	fn_t->name_off = fn_name_off; /* reuse original string */
6922 
6923 	return fn_id;
6924 }
6925 
6926 /* Check if main program or global subprog's function prototype has `arg:ctx`
6927  * argument tags, and, if necessary, substitute correct type to match what BPF
6928  * verifier would expect, taking into account specific program type. This
6929  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6930  * have a native support for it in the verifier, making user's life much
6931  * easier.
6932  */
bpf_program_fixup_func_info(struct bpf_object * obj,struct bpf_program * prog)6933 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6934 {
6935 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6936 	struct bpf_func_info_min *func_rec;
6937 	struct btf_type *fn_t, *fn_proto_t;
6938 	struct btf *btf = obj->btf;
6939 	const struct btf_type *t;
6940 	struct btf_param *p;
6941 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6942 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6943 	int *orig_ids;
6944 
6945 	/* no .BTF.ext, no problem */
6946 	if (!obj->btf_ext || !prog->func_info)
6947 		return 0;
6948 
6949 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6950 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6951 		return 0;
6952 
6953 	/* some BPF program types just don't have named context structs, so
6954 	 * this fallback mechanism doesn't work for them
6955 	 */
6956 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6957 		if (global_ctx_map[i].prog_type != prog->type)
6958 			continue;
6959 		ctx_name = global_ctx_map[i].ctx_name;
6960 		break;
6961 	}
6962 	if (!ctx_name)
6963 		return 0;
6964 
6965 	/* remember original func BTF IDs to detect if we already cloned them */
6966 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6967 	if (!orig_ids)
6968 		return -ENOMEM;
6969 	for (i = 0; i < prog->func_info_cnt; i++) {
6970 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6971 		orig_ids[i] = func_rec->type_id;
6972 	}
6973 
6974 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6975 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6976 	 * clone and adjust FUNC -> FUNC_PROTO combo
6977 	 */
6978 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6979 		/* only DECL_TAG with "arg:ctx" value are interesting */
6980 		t = btf__type_by_id(btf, i);
6981 		if (!btf_is_decl_tag(t))
6982 			continue;
6983 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6984 			continue;
6985 
6986 		/* only global funcs need adjustment, if at all */
6987 		orig_fn_id = t->type;
6988 		fn_t = btf_type_by_id(btf, orig_fn_id);
6989 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6990 			continue;
6991 
6992 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6993 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6994 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6995 			continue;
6996 
6997 		/* find corresponding func_info record */
6998 		func_rec = NULL;
6999 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7000 			if (orig_ids[rec_idx] == t->type) {
7001 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7002 				break;
7003 			}
7004 		}
7005 		/* current main program doesn't call into this subprog */
7006 		if (!func_rec)
7007 			continue;
7008 
7009 		/* some more sanity checking of DECL_TAG */
7010 		arg_cnt = btf_vlen(fn_proto_t);
7011 		arg_idx = btf_decl_tag(t)->component_idx;
7012 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7013 			continue;
7014 
7015 		/* check if we should fix up argument type */
7016 		p = &btf_params(fn_proto_t)[arg_idx];
7017 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7018 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7019 			continue;
7020 
7021 		/* clone fn/fn_proto, unless we already did it for another arg */
7022 		if (func_rec->type_id == orig_fn_id) {
7023 			int fn_id;
7024 
7025 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7026 			if (fn_id < 0) {
7027 				err = fn_id;
7028 				goto err_out;
7029 			}
7030 
7031 			/* point func_info record to a cloned FUNC type */
7032 			func_rec->type_id = fn_id;
7033 		}
7034 
7035 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7036 		 * we do it just once per main BPF program, as all global
7037 		 * funcs share the same program type, so need only PTR ->
7038 		 * STRUCT type chain
7039 		 */
7040 		if (ptr_id == 0) {
7041 			struct_id = btf__add_struct(btf, ctx_name, 0);
7042 			ptr_id = btf__add_ptr(btf, struct_id);
7043 			if (ptr_id < 0 || struct_id < 0) {
7044 				err = -EINVAL;
7045 				goto err_out;
7046 			}
7047 		}
7048 
7049 		/* for completeness, clone DECL_TAG and point it to cloned param */
7050 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7051 		if (tag_id < 0) {
7052 			err = -EINVAL;
7053 			goto err_out;
7054 		}
7055 
7056 		/* all the BTF manipulations invalidated pointers, refetch them */
7057 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7058 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7059 
7060 		/* fix up type ID pointed to by param */
7061 		p = &btf_params(fn_proto_t)[arg_idx];
7062 		p->type = ptr_id;
7063 	}
7064 
7065 	free(orig_ids);
7066 	return 0;
7067 err_out:
7068 	free(orig_ids);
7069 	return err;
7070 }
7071 
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)7072 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7073 {
7074 	struct bpf_program *prog;
7075 	size_t i, j;
7076 	int err;
7077 
7078 	if (obj->btf_ext) {
7079 		err = bpf_object__relocate_core(obj, targ_btf_path);
7080 		if (err) {
7081 			pr_warn("failed to perform CO-RE relocations: %s\n",
7082 				errstr(err));
7083 			return err;
7084 		}
7085 		bpf_object__sort_relos(obj);
7086 	}
7087 
7088 	/* Before relocating calls pre-process relocations and mark
7089 	 * few ld_imm64 instructions that points to subprogs.
7090 	 * Otherwise bpf_object__reloc_code() later would have to consider
7091 	 * all ld_imm64 insns as relocation candidates. That would
7092 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7093 	 * would increase and most of them will fail to find a relo.
7094 	 */
7095 	for (i = 0; i < obj->nr_programs; i++) {
7096 		prog = &obj->programs[i];
7097 		for (j = 0; j < prog->nr_reloc; j++) {
7098 			struct reloc_desc *relo = &prog->reloc_desc[j];
7099 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7100 
7101 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7102 			if (relo->type == RELO_SUBPROG_ADDR)
7103 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7104 		}
7105 	}
7106 
7107 	/* relocate subprogram calls and append used subprograms to main
7108 	 * programs; each copy of subprogram code needs to be relocated
7109 	 * differently for each main program, because its code location might
7110 	 * have changed.
7111 	 * Append subprog relos to main programs to allow data relos to be
7112 	 * processed after text is completely relocated.
7113 	 */
7114 	for (i = 0; i < obj->nr_programs; i++) {
7115 		prog = &obj->programs[i];
7116 		/* sub-program's sub-calls are relocated within the context of
7117 		 * its main program only
7118 		 */
7119 		if (prog_is_subprog(obj, prog))
7120 			continue;
7121 		if (!prog->autoload)
7122 			continue;
7123 
7124 		err = bpf_object__relocate_calls(obj, prog);
7125 		if (err) {
7126 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7127 				prog->name, errstr(err));
7128 			return err;
7129 		}
7130 
7131 		err = bpf_prog_assign_exc_cb(obj, prog);
7132 		if (err)
7133 			return err;
7134 		/* Now, also append exception callback if it has not been done already. */
7135 		if (prog->exception_cb_idx >= 0) {
7136 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7137 
7138 			/* Calling exception callback directly is disallowed, which the
7139 			 * verifier will reject later. In case it was processed already,
7140 			 * we can skip this step, otherwise for all other valid cases we
7141 			 * have to append exception callback now.
7142 			 */
7143 			if (subprog->sub_insn_off == 0) {
7144 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7145 				if (err)
7146 					return err;
7147 				err = bpf_object__reloc_code(obj, prog, subprog);
7148 				if (err)
7149 					return err;
7150 			}
7151 		}
7152 	}
7153 	for (i = 0; i < obj->nr_programs; i++) {
7154 		prog = &obj->programs[i];
7155 		if (prog_is_subprog(obj, prog))
7156 			continue;
7157 		if (!prog->autoload)
7158 			continue;
7159 
7160 		/* Process data relos for main programs */
7161 		err = bpf_object__relocate_data(obj, prog);
7162 		if (err) {
7163 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7164 				prog->name, errstr(err));
7165 			return err;
7166 		}
7167 
7168 		/* Fix up .BTF.ext information, if necessary */
7169 		err = bpf_program_fixup_func_info(obj, prog);
7170 		if (err) {
7171 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7172 				prog->name, errstr(err));
7173 			return err;
7174 		}
7175 	}
7176 
7177 	return 0;
7178 }
7179 
7180 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7181 					    Elf64_Shdr *shdr, Elf_Data *data);
7182 
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)7183 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7184 					 Elf64_Shdr *shdr, Elf_Data *data)
7185 {
7186 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7187 	int i, j, nrels, new_sz;
7188 	const struct btf_var_secinfo *vi = NULL;
7189 	const struct btf_type *sec, *var, *def;
7190 	struct bpf_map *map = NULL, *targ_map = NULL;
7191 	struct bpf_program *targ_prog = NULL;
7192 	bool is_prog_array, is_map_in_map;
7193 	const struct btf_member *member;
7194 	const char *name, *mname, *type;
7195 	unsigned int moff;
7196 	Elf64_Sym *sym;
7197 	Elf64_Rel *rel;
7198 	void *tmp;
7199 
7200 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7201 		return -EINVAL;
7202 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7203 	if (!sec)
7204 		return -EINVAL;
7205 
7206 	nrels = shdr->sh_size / shdr->sh_entsize;
7207 	for (i = 0; i < nrels; i++) {
7208 		rel = elf_rel_by_idx(data, i);
7209 		if (!rel) {
7210 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7211 			return -LIBBPF_ERRNO__FORMAT;
7212 		}
7213 
7214 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7215 		if (!sym) {
7216 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7217 				i, (size_t)ELF64_R_SYM(rel->r_info));
7218 			return -LIBBPF_ERRNO__FORMAT;
7219 		}
7220 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7221 
7222 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7223 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7224 			 (size_t)rel->r_offset, sym->st_name, name);
7225 
7226 		for (j = 0; j < obj->nr_maps; j++) {
7227 			map = &obj->maps[j];
7228 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7229 				continue;
7230 
7231 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7232 			if (vi->offset <= rel->r_offset &&
7233 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7234 				break;
7235 		}
7236 		if (j == obj->nr_maps) {
7237 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7238 				i, name, (size_t)rel->r_offset);
7239 			return -EINVAL;
7240 		}
7241 
7242 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7243 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7244 		type = is_map_in_map ? "map" : "prog";
7245 		if (is_map_in_map) {
7246 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7247 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7248 					i, name);
7249 				return -LIBBPF_ERRNO__RELOC;
7250 			}
7251 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7252 			    map->def.key_size != sizeof(int)) {
7253 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7254 					i, map->name, sizeof(int));
7255 				return -EINVAL;
7256 			}
7257 			targ_map = bpf_object__find_map_by_name(obj, name);
7258 			if (!targ_map) {
7259 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7260 					i, name);
7261 				return -ESRCH;
7262 			}
7263 		} else if (is_prog_array) {
7264 			targ_prog = bpf_object__find_program_by_name(obj, name);
7265 			if (!targ_prog) {
7266 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7267 					i, name);
7268 				return -ESRCH;
7269 			}
7270 			if (targ_prog->sec_idx != sym->st_shndx ||
7271 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7272 			    prog_is_subprog(obj, targ_prog)) {
7273 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7274 					i, name);
7275 				return -LIBBPF_ERRNO__RELOC;
7276 			}
7277 		} else {
7278 			return -EINVAL;
7279 		}
7280 
7281 		var = btf__type_by_id(obj->btf, vi->type);
7282 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7283 		if (btf_vlen(def) == 0)
7284 			return -EINVAL;
7285 		member = btf_members(def) + btf_vlen(def) - 1;
7286 		mname = btf__name_by_offset(obj->btf, member->name_off);
7287 		if (strcmp(mname, "values"))
7288 			return -EINVAL;
7289 
7290 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7291 		if (rel->r_offset - vi->offset < moff)
7292 			return -EINVAL;
7293 
7294 		moff = rel->r_offset - vi->offset - moff;
7295 		/* here we use BPF pointer size, which is always 64 bit, as we
7296 		 * are parsing ELF that was built for BPF target
7297 		 */
7298 		if (moff % bpf_ptr_sz)
7299 			return -EINVAL;
7300 		moff /= bpf_ptr_sz;
7301 		if (moff >= map->init_slots_sz) {
7302 			new_sz = moff + 1;
7303 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7304 			if (!tmp)
7305 				return -ENOMEM;
7306 			map->init_slots = tmp;
7307 			memset(map->init_slots + map->init_slots_sz, 0,
7308 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7309 			map->init_slots_sz = new_sz;
7310 		}
7311 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7312 
7313 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7314 			 i, map->name, moff, type, name);
7315 	}
7316 
7317 	return 0;
7318 }
7319 
bpf_object__collect_relos(struct bpf_object * obj)7320 static int bpf_object__collect_relos(struct bpf_object *obj)
7321 {
7322 	int i, err;
7323 
7324 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7325 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7326 		Elf64_Shdr *shdr;
7327 		Elf_Data *data;
7328 		int idx;
7329 
7330 		if (sec_desc->sec_type != SEC_RELO)
7331 			continue;
7332 
7333 		shdr = sec_desc->shdr;
7334 		data = sec_desc->data;
7335 		idx = shdr->sh_info;
7336 
7337 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7338 			pr_warn("internal error at %d\n", __LINE__);
7339 			return -LIBBPF_ERRNO__INTERNAL;
7340 		}
7341 
7342 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7343 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7344 		else if (idx == obj->efile.btf_maps_shndx)
7345 			err = bpf_object__collect_map_relos(obj, shdr, data);
7346 		else
7347 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7348 		if (err)
7349 			return err;
7350 	}
7351 
7352 	bpf_object__sort_relos(obj);
7353 	return 0;
7354 }
7355 
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)7356 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7357 {
7358 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7359 	    BPF_OP(insn->code) == BPF_CALL &&
7360 	    BPF_SRC(insn->code) == BPF_K &&
7361 	    insn->src_reg == 0 &&
7362 	    insn->dst_reg == 0) {
7363 		    *func_id = insn->imm;
7364 		    return true;
7365 	}
7366 	return false;
7367 }
7368 
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)7369 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7370 {
7371 	struct bpf_insn *insn = prog->insns;
7372 	enum bpf_func_id func_id;
7373 	int i;
7374 
7375 	if (obj->gen_loader)
7376 		return 0;
7377 
7378 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7379 		if (!insn_is_helper_call(insn, &func_id))
7380 			continue;
7381 
7382 		/* on kernels that don't yet support
7383 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7384 		 * to bpf_probe_read() which works well for old kernels
7385 		 */
7386 		switch (func_id) {
7387 		case BPF_FUNC_probe_read_kernel:
7388 		case BPF_FUNC_probe_read_user:
7389 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7390 				insn->imm = BPF_FUNC_probe_read;
7391 			break;
7392 		case BPF_FUNC_probe_read_kernel_str:
7393 		case BPF_FUNC_probe_read_user_str:
7394 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7395 				insn->imm = BPF_FUNC_probe_read_str;
7396 			break;
7397 		default:
7398 			break;
7399 		}
7400 	}
7401 	return 0;
7402 }
7403 
7404 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7405 				     int *btf_obj_fd, int *btf_type_id);
7406 
7407 /* 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)7408 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7409 				    struct bpf_prog_load_opts *opts, long cookie)
7410 {
7411 	enum sec_def_flags def = cookie;
7412 
7413 	/* old kernels might not support specifying expected_attach_type */
7414 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7415 		opts->expected_attach_type = 0;
7416 
7417 	if (def & SEC_SLEEPABLE)
7418 		opts->prog_flags |= BPF_F_SLEEPABLE;
7419 
7420 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7421 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7422 
7423 	/* special check for usdt to use uprobe_multi link */
7424 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7425 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7426 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7427 		 * update both.
7428 		 */
7429 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7430 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7431 	}
7432 
7433 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7434 		int btf_obj_fd = 0, btf_type_id = 0, err;
7435 		const char *attach_name;
7436 
7437 		attach_name = strchr(prog->sec_name, '/');
7438 		if (!attach_name) {
7439 			/* if BPF program is annotated with just SEC("fentry")
7440 			 * (or similar) without declaratively specifying
7441 			 * target, then it is expected that target will be
7442 			 * specified with bpf_program__set_attach_target() at
7443 			 * runtime before BPF object load step. If not, then
7444 			 * there is nothing to load into the kernel as BPF
7445 			 * verifier won't be able to validate BPF program
7446 			 * correctness anyways.
7447 			 */
7448 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7449 				prog->name);
7450 			return -EINVAL;
7451 		}
7452 		attach_name++; /* skip over / */
7453 
7454 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7455 		if (err)
7456 			return err;
7457 
7458 		/* cache resolved BTF FD and BTF type ID in the prog */
7459 		prog->attach_btf_obj_fd = btf_obj_fd;
7460 		prog->attach_btf_id = btf_type_id;
7461 
7462 		/* but by now libbpf common logic is not utilizing
7463 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7464 		 * this callback is called after opts were populated by
7465 		 * libbpf, so this callback has to update opts explicitly here
7466 		 */
7467 		opts->attach_btf_obj_fd = btf_obj_fd;
7468 		opts->attach_btf_id = btf_type_id;
7469 	}
7470 	return 0;
7471 }
7472 
7473 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7474 
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)7475 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7476 				struct bpf_insn *insns, int insns_cnt,
7477 				const char *license, __u32 kern_version, int *prog_fd)
7478 {
7479 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7480 	const char *prog_name = NULL;
7481 	size_t log_buf_size = 0;
7482 	char *log_buf = NULL, *tmp;
7483 	bool own_log_buf = true;
7484 	__u32 log_level = prog->log_level;
7485 	int ret, err;
7486 
7487 	/* Be more helpful by rejecting programs that can't be validated early
7488 	 * with more meaningful and actionable error message.
7489 	 */
7490 	switch (prog->type) {
7491 	case BPF_PROG_TYPE_UNSPEC:
7492 		/*
7493 		 * The program type must be set.  Most likely we couldn't find a proper
7494 		 * section definition at load time, and thus we didn't infer the type.
7495 		 */
7496 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7497 			prog->name, prog->sec_name);
7498 		return -EINVAL;
7499 	case BPF_PROG_TYPE_STRUCT_OPS:
7500 		if (prog->attach_btf_id == 0) {
7501 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7502 				prog->name);
7503 			return -EINVAL;
7504 		}
7505 		break;
7506 	default:
7507 		break;
7508 	}
7509 
7510 	if (!insns || !insns_cnt)
7511 		return -EINVAL;
7512 
7513 	if (kernel_supports(obj, FEAT_PROG_NAME))
7514 		prog_name = prog->name;
7515 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7516 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7517 	load_attr.attach_btf_id = prog->attach_btf_id;
7518 	load_attr.kern_version = kern_version;
7519 	load_attr.prog_ifindex = prog->prog_ifindex;
7520 	load_attr.expected_attach_type = prog->expected_attach_type;
7521 
7522 	/* specify func_info/line_info only if kernel supports them */
7523 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7524 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7525 		load_attr.func_info = prog->func_info;
7526 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7527 		load_attr.func_info_cnt = prog->func_info_cnt;
7528 		load_attr.line_info = prog->line_info;
7529 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7530 		load_attr.line_info_cnt = prog->line_info_cnt;
7531 	}
7532 	load_attr.log_level = log_level;
7533 	load_attr.prog_flags = prog->prog_flags;
7534 	load_attr.fd_array = obj->fd_array;
7535 
7536 	load_attr.token_fd = obj->token_fd;
7537 	if (obj->token_fd)
7538 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7539 
7540 	/* adjust load_attr if sec_def provides custom preload callback */
7541 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7542 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7543 		if (err < 0) {
7544 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7545 				prog->name, errstr(err));
7546 			return err;
7547 		}
7548 		insns = prog->insns;
7549 		insns_cnt = prog->insns_cnt;
7550 	}
7551 
7552 	if (obj->gen_loader) {
7553 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7554 				   license, insns, insns_cnt, &load_attr,
7555 				   prog - obj->programs);
7556 		*prog_fd = -1;
7557 		return 0;
7558 	}
7559 
7560 retry_load:
7561 	/* if log_level is zero, we don't request logs initially even if
7562 	 * custom log_buf is specified; if the program load fails, then we'll
7563 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7564 	 * our own and retry the load to get details on what failed
7565 	 */
7566 	if (log_level) {
7567 		if (prog->log_buf) {
7568 			log_buf = prog->log_buf;
7569 			log_buf_size = prog->log_size;
7570 			own_log_buf = false;
7571 		} else if (obj->log_buf) {
7572 			log_buf = obj->log_buf;
7573 			log_buf_size = obj->log_size;
7574 			own_log_buf = false;
7575 		} else {
7576 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7577 			tmp = realloc(log_buf, log_buf_size);
7578 			if (!tmp) {
7579 				ret = -ENOMEM;
7580 				goto out;
7581 			}
7582 			log_buf = tmp;
7583 			log_buf[0] = '\0';
7584 			own_log_buf = true;
7585 		}
7586 	}
7587 
7588 	load_attr.log_buf = log_buf;
7589 	load_attr.log_size = log_buf_size;
7590 	load_attr.log_level = log_level;
7591 
7592 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7593 	if (ret >= 0) {
7594 		if (log_level && own_log_buf) {
7595 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7596 				 prog->name, log_buf);
7597 		}
7598 
7599 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7600 			struct bpf_map *map;
7601 			int i;
7602 
7603 			for (i = 0; i < obj->nr_maps; i++) {
7604 				map = &prog->obj->maps[i];
7605 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7606 					continue;
7607 
7608 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7609 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7610 						prog->name, map->real_name, errstr(errno));
7611 					/* Don't fail hard if can't bind rodata. */
7612 				}
7613 			}
7614 		}
7615 
7616 		*prog_fd = ret;
7617 		ret = 0;
7618 		goto out;
7619 	}
7620 
7621 	if (log_level == 0) {
7622 		log_level = 1;
7623 		goto retry_load;
7624 	}
7625 	/* On ENOSPC, increase log buffer size and retry, unless custom
7626 	 * log_buf is specified.
7627 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7628 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7629 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7630 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7631 	 */
7632 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7633 		goto retry_load;
7634 
7635 	ret = -errno;
7636 
7637 	/* post-process verifier log to improve error descriptions */
7638 	fixup_verifier_log(prog, log_buf, log_buf_size);
7639 
7640 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7641 	pr_perm_msg(ret);
7642 
7643 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7644 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7645 			prog->name, log_buf);
7646 	}
7647 
7648 out:
7649 	if (own_log_buf)
7650 		free(log_buf);
7651 	return ret;
7652 }
7653 
find_prev_line(char * buf,char * cur)7654 static char *find_prev_line(char *buf, char *cur)
7655 {
7656 	char *p;
7657 
7658 	if (cur == buf) /* end of a log buf */
7659 		return NULL;
7660 
7661 	p = cur - 1;
7662 	while (p - 1 >= buf && *(p - 1) != '\n')
7663 		p--;
7664 
7665 	return p;
7666 }
7667 
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)7668 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7669 		      char *orig, size_t orig_sz, const char *patch)
7670 {
7671 	/* size of the remaining log content to the right from the to-be-replaced part */
7672 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7673 	size_t patch_sz = strlen(patch);
7674 
7675 	if (patch_sz != orig_sz) {
7676 		/* If patch line(s) are longer than original piece of verifier log,
7677 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7678 		 * starting from after to-be-replaced part of the log.
7679 		 *
7680 		 * If patch line(s) are shorter than original piece of verifier log,
7681 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7682 		 * starting from after to-be-replaced part of the log
7683 		 *
7684 		 * We need to be careful about not overflowing available
7685 		 * buf_sz capacity. If that's the case, we'll truncate the end
7686 		 * of the original log, as necessary.
7687 		 */
7688 		if (patch_sz > orig_sz) {
7689 			if (orig + patch_sz >= buf + buf_sz) {
7690 				/* patch is big enough to cover remaining space completely */
7691 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7692 				rem_sz = 0;
7693 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7694 				/* patch causes part of remaining log to be truncated */
7695 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7696 			}
7697 		}
7698 		/* shift remaining log to the right by calculated amount */
7699 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7700 	}
7701 
7702 	memcpy(orig, patch, patch_sz);
7703 }
7704 
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)7705 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7706 				       char *buf, size_t buf_sz, size_t log_sz,
7707 				       char *line1, char *line2, char *line3)
7708 {
7709 	/* Expected log for failed and not properly guarded CO-RE relocation:
7710 	 * line1 -> 123: (85) call unknown#195896080
7711 	 * line2 -> invalid func unknown#195896080
7712 	 * line3 -> <anything else or end of buffer>
7713 	 *
7714 	 * "123" is the index of the instruction that was poisoned. We extract
7715 	 * instruction index to find corresponding CO-RE relocation and
7716 	 * replace this part of the log with more relevant information about
7717 	 * failed CO-RE relocation.
7718 	 */
7719 	const struct bpf_core_relo *relo;
7720 	struct bpf_core_spec spec;
7721 	char patch[512], spec_buf[256];
7722 	int insn_idx, err, spec_len;
7723 
7724 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7725 		return;
7726 
7727 	relo = find_relo_core(prog, insn_idx);
7728 	if (!relo)
7729 		return;
7730 
7731 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7732 	if (err)
7733 		return;
7734 
7735 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7736 	snprintf(patch, sizeof(patch),
7737 		 "%d: <invalid CO-RE relocation>\n"
7738 		 "failed to resolve CO-RE relocation %s%s\n",
7739 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7740 
7741 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7742 }
7743 
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)7744 static void fixup_log_missing_map_load(struct bpf_program *prog,
7745 				       char *buf, size_t buf_sz, size_t log_sz,
7746 				       char *line1, char *line2, char *line3)
7747 {
7748 	/* Expected log for failed and not properly guarded map reference:
7749 	 * line1 -> 123: (85) call unknown#2001000345
7750 	 * line2 -> invalid func unknown#2001000345
7751 	 * line3 -> <anything else or end of buffer>
7752 	 *
7753 	 * "123" is the index of the instruction that was poisoned.
7754 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7755 	 */
7756 	struct bpf_object *obj = prog->obj;
7757 	const struct bpf_map *map;
7758 	int insn_idx, map_idx;
7759 	char patch[128];
7760 
7761 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7762 		return;
7763 
7764 	map_idx -= POISON_LDIMM64_MAP_BASE;
7765 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7766 		return;
7767 	map = &obj->maps[map_idx];
7768 
7769 	snprintf(patch, sizeof(patch),
7770 		 "%d: <invalid BPF map reference>\n"
7771 		 "BPF map '%s' is referenced but wasn't created\n",
7772 		 insn_idx, map->name);
7773 
7774 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7775 }
7776 
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)7777 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7778 					 char *buf, size_t buf_sz, size_t log_sz,
7779 					 char *line1, char *line2, char *line3)
7780 {
7781 	/* Expected log for failed and not properly guarded kfunc call:
7782 	 * line1 -> 123: (85) call unknown#2002000345
7783 	 * line2 -> invalid func unknown#2002000345
7784 	 * line3 -> <anything else or end of buffer>
7785 	 *
7786 	 * "123" is the index of the instruction that was poisoned.
7787 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7788 	 */
7789 	struct bpf_object *obj = prog->obj;
7790 	const struct extern_desc *ext;
7791 	int insn_idx, ext_idx;
7792 	char patch[128];
7793 
7794 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7795 		return;
7796 
7797 	ext_idx -= POISON_CALL_KFUNC_BASE;
7798 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7799 		return;
7800 	ext = &obj->externs[ext_idx];
7801 
7802 	snprintf(patch, sizeof(patch),
7803 		 "%d: <invalid kfunc call>\n"
7804 		 "kfunc '%s' is referenced but wasn't resolved\n",
7805 		 insn_idx, ext->name);
7806 
7807 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7808 }
7809 
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7810 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7811 {
7812 	/* look for familiar error patterns in last N lines of the log */
7813 	const size_t max_last_line_cnt = 10;
7814 	char *prev_line, *cur_line, *next_line;
7815 	size_t log_sz;
7816 	int i;
7817 
7818 	if (!buf)
7819 		return;
7820 
7821 	log_sz = strlen(buf) + 1;
7822 	next_line = buf + log_sz - 1;
7823 
7824 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7825 		cur_line = find_prev_line(buf, next_line);
7826 		if (!cur_line)
7827 			return;
7828 
7829 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7830 			prev_line = find_prev_line(buf, cur_line);
7831 			if (!prev_line)
7832 				continue;
7833 
7834 			/* failed CO-RE relocation case */
7835 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7836 						   prev_line, cur_line, next_line);
7837 			return;
7838 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7839 			prev_line = find_prev_line(buf, cur_line);
7840 			if (!prev_line)
7841 				continue;
7842 
7843 			/* reference to uncreated BPF map */
7844 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7845 						   prev_line, cur_line, next_line);
7846 			return;
7847 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7848 			prev_line = find_prev_line(buf, cur_line);
7849 			if (!prev_line)
7850 				continue;
7851 
7852 			/* reference to unresolved kfunc */
7853 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7854 						     prev_line, cur_line, next_line);
7855 			return;
7856 		}
7857 	}
7858 }
7859 
bpf_program_record_relos(struct bpf_program * prog)7860 static int bpf_program_record_relos(struct bpf_program *prog)
7861 {
7862 	struct bpf_object *obj = prog->obj;
7863 	int i;
7864 
7865 	for (i = 0; i < prog->nr_reloc; i++) {
7866 		struct reloc_desc *relo = &prog->reloc_desc[i];
7867 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7868 		int kind;
7869 
7870 		switch (relo->type) {
7871 		case RELO_EXTERN_LD64:
7872 			if (ext->type != EXT_KSYM)
7873 				continue;
7874 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7875 				BTF_KIND_VAR : BTF_KIND_FUNC;
7876 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7877 					       ext->is_weak, !ext->ksym.type_id,
7878 					       true, kind, relo->insn_idx);
7879 			break;
7880 		case RELO_EXTERN_CALL:
7881 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7882 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7883 					       relo->insn_idx);
7884 			break;
7885 		case RELO_CORE: {
7886 			struct bpf_core_relo cr = {
7887 				.insn_off = relo->insn_idx * 8,
7888 				.type_id = relo->core_relo->type_id,
7889 				.access_str_off = relo->core_relo->access_str_off,
7890 				.kind = relo->core_relo->kind,
7891 			};
7892 
7893 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7894 			break;
7895 		}
7896 		default:
7897 			continue;
7898 		}
7899 	}
7900 	return 0;
7901 }
7902 
7903 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7904 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7905 {
7906 	struct bpf_program *prog;
7907 	size_t i;
7908 	int err;
7909 
7910 	for (i = 0; i < obj->nr_programs; i++) {
7911 		prog = &obj->programs[i];
7912 		if (prog_is_subprog(obj, prog))
7913 			continue;
7914 		if (!prog->autoload) {
7915 			pr_debug("prog '%s': skipped loading\n", prog->name);
7916 			continue;
7917 		}
7918 		prog->log_level |= log_level;
7919 
7920 		if (obj->gen_loader)
7921 			bpf_program_record_relos(prog);
7922 
7923 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7924 					   obj->license, obj->kern_version, &prog->fd);
7925 		if (err) {
7926 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7927 			return err;
7928 		}
7929 	}
7930 
7931 	bpf_object__free_relocs(obj);
7932 	return 0;
7933 }
7934 
bpf_object_prepare_progs(struct bpf_object * obj)7935 static int bpf_object_prepare_progs(struct bpf_object *obj)
7936 {
7937 	struct bpf_program *prog;
7938 	size_t i;
7939 	int err;
7940 
7941 	for (i = 0; i < obj->nr_programs; i++) {
7942 		prog = &obj->programs[i];
7943 		err = bpf_object__sanitize_prog(obj, prog);
7944 		if (err)
7945 			return err;
7946 	}
7947 	return 0;
7948 }
7949 
7950 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7951 
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7952 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7953 {
7954 	struct bpf_program *prog;
7955 	int err;
7956 
7957 	bpf_object__for_each_program(prog, obj) {
7958 		prog->sec_def = find_sec_def(prog->sec_name);
7959 		if (!prog->sec_def) {
7960 			/* couldn't guess, but user might manually specify */
7961 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7962 				prog->name, prog->sec_name);
7963 			continue;
7964 		}
7965 
7966 		prog->type = prog->sec_def->prog_type;
7967 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7968 
7969 		/* sec_def can have custom callback which should be called
7970 		 * after bpf_program is initialized to adjust its properties
7971 		 */
7972 		if (prog->sec_def->prog_setup_fn) {
7973 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7974 			if (err < 0) {
7975 				pr_warn("prog '%s': failed to initialize: %s\n",
7976 					prog->name, errstr(err));
7977 				return err;
7978 			}
7979 		}
7980 	}
7981 
7982 	return 0;
7983 }
7984 
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)7985 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7986 					  const char *obj_name,
7987 					  const struct bpf_object_open_opts *opts)
7988 {
7989 	const char *kconfig, *btf_tmp_path, *token_path;
7990 	struct bpf_object *obj;
7991 	int err;
7992 	char *log_buf;
7993 	size_t log_size;
7994 	__u32 log_level;
7995 
7996 	if (obj_buf && !obj_name)
7997 		return ERR_PTR(-EINVAL);
7998 
7999 	if (elf_version(EV_CURRENT) == EV_NONE) {
8000 		pr_warn("failed to init libelf for %s\n",
8001 			path ? : "(mem buf)");
8002 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8003 	}
8004 
8005 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8006 		return ERR_PTR(-EINVAL);
8007 
8008 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8009 	if (obj_buf) {
8010 		path = obj_name;
8011 		pr_debug("loading object '%s' from buffer\n", obj_name);
8012 	} else {
8013 		pr_debug("loading object from %s\n", path);
8014 	}
8015 
8016 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8017 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8018 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8019 	if (log_size > UINT_MAX)
8020 		return ERR_PTR(-EINVAL);
8021 	if (log_size && !log_buf)
8022 		return ERR_PTR(-EINVAL);
8023 
8024 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8025 	/* if user didn't specify bpf_token_path explicitly, check if
8026 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8027 	 * option
8028 	 */
8029 	if (!token_path)
8030 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8031 	if (token_path && strlen(token_path) >= PATH_MAX)
8032 		return ERR_PTR(-ENAMETOOLONG);
8033 
8034 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8035 	if (IS_ERR(obj))
8036 		return obj;
8037 
8038 	obj->log_buf = log_buf;
8039 	obj->log_size = log_size;
8040 	obj->log_level = log_level;
8041 
8042 	if (token_path) {
8043 		obj->token_path = strdup(token_path);
8044 		if (!obj->token_path) {
8045 			err = -ENOMEM;
8046 			goto out;
8047 		}
8048 	}
8049 
8050 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8051 	if (btf_tmp_path) {
8052 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8053 			err = -ENAMETOOLONG;
8054 			goto out;
8055 		}
8056 		obj->btf_custom_path = strdup(btf_tmp_path);
8057 		if (!obj->btf_custom_path) {
8058 			err = -ENOMEM;
8059 			goto out;
8060 		}
8061 	}
8062 
8063 	kconfig = OPTS_GET(opts, kconfig, NULL);
8064 	if (kconfig) {
8065 		obj->kconfig = strdup(kconfig);
8066 		if (!obj->kconfig) {
8067 			err = -ENOMEM;
8068 			goto out;
8069 		}
8070 	}
8071 
8072 	err = bpf_object__elf_init(obj);
8073 	err = err ? : bpf_object__elf_collect(obj);
8074 	err = err ? : bpf_object__collect_externs(obj);
8075 	err = err ? : bpf_object_fixup_btf(obj);
8076 	err = err ? : bpf_object__init_maps(obj, opts);
8077 	err = err ? : bpf_object_init_progs(obj, opts);
8078 	err = err ? : bpf_object__collect_relos(obj);
8079 	if (err)
8080 		goto out;
8081 
8082 	bpf_object__elf_finish(obj);
8083 
8084 	return obj;
8085 out:
8086 	bpf_object__close(obj);
8087 	return ERR_PTR(err);
8088 }
8089 
8090 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)8091 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8092 {
8093 	if (!path)
8094 		return libbpf_err_ptr(-EINVAL);
8095 
8096 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8097 }
8098 
bpf_object__open(const char * path)8099 struct bpf_object *bpf_object__open(const char *path)
8100 {
8101 	return bpf_object__open_file(path, NULL);
8102 }
8103 
8104 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)8105 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8106 		     const struct bpf_object_open_opts *opts)
8107 {
8108 	char tmp_name[64];
8109 
8110 	if (!obj_buf || obj_buf_sz == 0)
8111 		return libbpf_err_ptr(-EINVAL);
8112 
8113 	/* create a (quite useless) default "name" for this memory buffer object */
8114 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8115 
8116 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8117 }
8118 
bpf_object_unload(struct bpf_object * obj)8119 static int bpf_object_unload(struct bpf_object *obj)
8120 {
8121 	size_t i;
8122 
8123 	if (!obj)
8124 		return libbpf_err(-EINVAL);
8125 
8126 	for (i = 0; i < obj->nr_maps; i++) {
8127 		zclose(obj->maps[i].fd);
8128 		if (obj->maps[i].st_ops)
8129 			zfree(&obj->maps[i].st_ops->kern_vdata);
8130 	}
8131 
8132 	for (i = 0; i < obj->nr_programs; i++)
8133 		bpf_program__unload(&obj->programs[i]);
8134 
8135 	return 0;
8136 }
8137 
bpf_object__sanitize_maps(struct bpf_object * obj)8138 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8139 {
8140 	struct bpf_map *m;
8141 
8142 	bpf_object__for_each_map(m, obj) {
8143 		if (!bpf_map__is_internal(m))
8144 			continue;
8145 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8146 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8147 	}
8148 
8149 	return 0;
8150 }
8151 
8152 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8153 			     const char *sym_name, void *ctx);
8154 
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)8155 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8156 {
8157 	char sym_type, sym_name[500];
8158 	unsigned long long sym_addr;
8159 	int ret, err = 0;
8160 	FILE *f;
8161 
8162 	f = fopen("/proc/kallsyms", "re");
8163 	if (!f) {
8164 		err = -errno;
8165 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8166 		return err;
8167 	}
8168 
8169 	while (true) {
8170 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8171 			     &sym_addr, &sym_type, sym_name);
8172 		if (ret == EOF && feof(f))
8173 			break;
8174 		if (ret != 3) {
8175 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8176 			err = -EINVAL;
8177 			break;
8178 		}
8179 
8180 		err = cb(sym_addr, sym_type, sym_name, ctx);
8181 		if (err)
8182 			break;
8183 	}
8184 
8185 	fclose(f);
8186 	return err;
8187 }
8188 
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)8189 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8190 		       const char *sym_name, void *ctx)
8191 {
8192 	struct bpf_object *obj = ctx;
8193 	const struct btf_type *t;
8194 	struct extern_desc *ext;
8195 	char *res;
8196 
8197 	res = strstr(sym_name, ".llvm.");
8198 	if (sym_type == 'd' && res)
8199 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8200 	else
8201 		ext = find_extern_by_name(obj, sym_name);
8202 	if (!ext || ext->type != EXT_KSYM)
8203 		return 0;
8204 
8205 	t = btf__type_by_id(obj->btf, ext->btf_id);
8206 	if (!btf_is_var(t))
8207 		return 0;
8208 
8209 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8210 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8211 			sym_name, ext->ksym.addr, sym_addr);
8212 		return -EINVAL;
8213 	}
8214 	if (!ext->is_set) {
8215 		ext->is_set = true;
8216 		ext->ksym.addr = sym_addr;
8217 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8218 	}
8219 	return 0;
8220 }
8221 
bpf_object__read_kallsyms_file(struct bpf_object * obj)8222 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8223 {
8224 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8225 }
8226 
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)8227 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8228 			    __u16 kind, struct btf **res_btf,
8229 			    struct module_btf **res_mod_btf)
8230 {
8231 	struct module_btf *mod_btf;
8232 	struct btf *btf;
8233 	int i, id, err;
8234 
8235 	btf = obj->btf_vmlinux;
8236 	mod_btf = NULL;
8237 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8238 
8239 	if (id == -ENOENT) {
8240 		err = load_module_btfs(obj);
8241 		if (err)
8242 			return err;
8243 
8244 		for (i = 0; i < obj->btf_module_cnt; i++) {
8245 			/* we assume module_btf's BTF FD is always >0 */
8246 			mod_btf = &obj->btf_modules[i];
8247 			btf = mod_btf->btf;
8248 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8249 			if (id != -ENOENT)
8250 				break;
8251 		}
8252 	}
8253 	if (id <= 0)
8254 		return -ESRCH;
8255 
8256 	*res_btf = btf;
8257 	*res_mod_btf = mod_btf;
8258 	return id;
8259 }
8260 
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)8261 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8262 					       struct extern_desc *ext)
8263 {
8264 	const struct btf_type *targ_var, *targ_type;
8265 	__u32 targ_type_id, local_type_id;
8266 	struct module_btf *mod_btf = NULL;
8267 	const char *targ_var_name;
8268 	struct btf *btf = NULL;
8269 	int id, err;
8270 
8271 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8272 	if (id < 0) {
8273 		if (id == -ESRCH && ext->is_weak)
8274 			return 0;
8275 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8276 			ext->name);
8277 		return id;
8278 	}
8279 
8280 	/* find local type_id */
8281 	local_type_id = ext->ksym.type_id;
8282 
8283 	/* find target type_id */
8284 	targ_var = btf__type_by_id(btf, id);
8285 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8286 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8287 
8288 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8289 					btf, targ_type_id);
8290 	if (err <= 0) {
8291 		const struct btf_type *local_type;
8292 		const char *targ_name, *local_name;
8293 
8294 		local_type = btf__type_by_id(obj->btf, local_type_id);
8295 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8296 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8297 
8298 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8299 			ext->name, local_type_id,
8300 			btf_kind_str(local_type), local_name, targ_type_id,
8301 			btf_kind_str(targ_type), targ_name);
8302 		return -EINVAL;
8303 	}
8304 
8305 	ext->is_set = true;
8306 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8307 	ext->ksym.kernel_btf_id = id;
8308 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8309 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8310 
8311 	return 0;
8312 }
8313 
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)8314 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8315 						struct extern_desc *ext)
8316 {
8317 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8318 	struct module_btf *mod_btf = NULL;
8319 	const struct btf_type *kern_func;
8320 	struct btf *kern_btf = NULL;
8321 	int ret;
8322 
8323 	local_func_proto_id = ext->ksym.type_id;
8324 
8325 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8326 				    &mod_btf);
8327 	if (kfunc_id < 0) {
8328 		if (kfunc_id == -ESRCH && ext->is_weak)
8329 			return 0;
8330 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8331 			ext->name);
8332 		return kfunc_id;
8333 	}
8334 
8335 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8336 	kfunc_proto_id = kern_func->type;
8337 
8338 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8339 					kern_btf, kfunc_proto_id);
8340 	if (ret <= 0) {
8341 		if (ext->is_weak)
8342 			return 0;
8343 
8344 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8345 			ext->name, local_func_proto_id,
8346 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8347 		return -EINVAL;
8348 	}
8349 
8350 	/* set index for module BTF fd in fd_array, if unset */
8351 	if (mod_btf && !mod_btf->fd_array_idx) {
8352 		/* insn->off is s16 */
8353 		if (obj->fd_array_cnt == INT16_MAX) {
8354 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8355 				ext->name, mod_btf->fd_array_idx);
8356 			return -E2BIG;
8357 		}
8358 		/* Cannot use index 0 for module BTF fd */
8359 		if (!obj->fd_array_cnt)
8360 			obj->fd_array_cnt = 1;
8361 
8362 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8363 					obj->fd_array_cnt + 1);
8364 		if (ret)
8365 			return ret;
8366 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8367 		/* we assume module BTF FD is always >0 */
8368 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8369 	}
8370 
8371 	ext->is_set = true;
8372 	ext->ksym.kernel_btf_id = kfunc_id;
8373 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8374 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8375 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8376 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8377 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8378 	 */
8379 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8380 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8381 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8382 
8383 	return 0;
8384 }
8385 
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)8386 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8387 {
8388 	const struct btf_type *t;
8389 	struct extern_desc *ext;
8390 	int i, err;
8391 
8392 	for (i = 0; i < obj->nr_extern; i++) {
8393 		ext = &obj->externs[i];
8394 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8395 			continue;
8396 
8397 		if (obj->gen_loader) {
8398 			ext->is_set = true;
8399 			ext->ksym.kernel_btf_obj_fd = 0;
8400 			ext->ksym.kernel_btf_id = 0;
8401 			continue;
8402 		}
8403 		t = btf__type_by_id(obj->btf, ext->btf_id);
8404 		if (btf_is_var(t))
8405 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8406 		else
8407 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8408 		if (err)
8409 			return err;
8410 	}
8411 	return 0;
8412 }
8413 
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)8414 static int bpf_object__resolve_externs(struct bpf_object *obj,
8415 				       const char *extra_kconfig)
8416 {
8417 	bool need_config = false, need_kallsyms = false;
8418 	bool need_vmlinux_btf = false;
8419 	struct extern_desc *ext;
8420 	void *kcfg_data = NULL;
8421 	int err, i;
8422 
8423 	if (obj->nr_extern == 0)
8424 		return 0;
8425 
8426 	if (obj->kconfig_map_idx >= 0)
8427 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8428 
8429 	for (i = 0; i < obj->nr_extern; i++) {
8430 		ext = &obj->externs[i];
8431 
8432 		if (ext->type == EXT_KSYM) {
8433 			if (ext->ksym.type_id)
8434 				need_vmlinux_btf = true;
8435 			else
8436 				need_kallsyms = true;
8437 			continue;
8438 		} else if (ext->type == EXT_KCFG) {
8439 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8440 			__u64 value = 0;
8441 
8442 			/* Kconfig externs need actual /proc/config.gz */
8443 			if (str_has_pfx(ext->name, "CONFIG_")) {
8444 				need_config = true;
8445 				continue;
8446 			}
8447 
8448 			/* Virtual kcfg externs are customly handled by libbpf */
8449 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8450 				value = get_kernel_version();
8451 				if (!value) {
8452 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8453 					return -EINVAL;
8454 				}
8455 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8456 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8457 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8458 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8459 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8460 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8461 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8462 				 * customly by libbpf (their values don't come from Kconfig).
8463 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8464 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8465 				 * externs.
8466 				 */
8467 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8468 				return -EINVAL;
8469 			}
8470 
8471 			err = set_kcfg_value_num(ext, ext_ptr, value);
8472 			if (err)
8473 				return err;
8474 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8475 				 ext->name, (long long)value);
8476 		} else {
8477 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8478 			return -EINVAL;
8479 		}
8480 	}
8481 	if (need_config && extra_kconfig) {
8482 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8483 		if (err)
8484 			return -EINVAL;
8485 		need_config = false;
8486 		for (i = 0; i < obj->nr_extern; i++) {
8487 			ext = &obj->externs[i];
8488 			if (ext->type == EXT_KCFG && !ext->is_set) {
8489 				need_config = true;
8490 				break;
8491 			}
8492 		}
8493 	}
8494 	if (need_config) {
8495 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8496 		if (err)
8497 			return -EINVAL;
8498 	}
8499 	if (need_kallsyms) {
8500 		err = bpf_object__read_kallsyms_file(obj);
8501 		if (err)
8502 			return -EINVAL;
8503 	}
8504 	if (need_vmlinux_btf) {
8505 		err = bpf_object__resolve_ksyms_btf_id(obj);
8506 		if (err)
8507 			return -EINVAL;
8508 	}
8509 	for (i = 0; i < obj->nr_extern; i++) {
8510 		ext = &obj->externs[i];
8511 
8512 		if (!ext->is_set && !ext->is_weak) {
8513 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8514 			return -ESRCH;
8515 		} else if (!ext->is_set) {
8516 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8517 				 ext->name);
8518 		}
8519 	}
8520 
8521 	return 0;
8522 }
8523 
bpf_map_prepare_vdata(const struct bpf_map * map)8524 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8525 {
8526 	const struct btf_type *type;
8527 	struct bpf_struct_ops *st_ops;
8528 	__u32 i;
8529 
8530 	st_ops = map->st_ops;
8531 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8532 	for (i = 0; i < btf_vlen(type); i++) {
8533 		struct bpf_program *prog = st_ops->progs[i];
8534 		void *kern_data;
8535 		int prog_fd;
8536 
8537 		if (!prog)
8538 			continue;
8539 
8540 		prog_fd = bpf_program__fd(prog);
8541 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8542 		*(unsigned long *)kern_data = prog_fd;
8543 	}
8544 }
8545 
bpf_object_prepare_struct_ops(struct bpf_object * obj)8546 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8547 {
8548 	struct bpf_map *map;
8549 	int i;
8550 
8551 	for (i = 0; i < obj->nr_maps; i++) {
8552 		map = &obj->maps[i];
8553 
8554 		if (!bpf_map__is_struct_ops(map))
8555 			continue;
8556 
8557 		if (!map->autocreate)
8558 			continue;
8559 
8560 		bpf_map_prepare_vdata(map);
8561 	}
8562 
8563 	return 0;
8564 }
8565 
bpf_object_unpin(struct bpf_object * obj)8566 static void bpf_object_unpin(struct bpf_object *obj)
8567 {
8568 	int i;
8569 
8570 	/* unpin any maps that were auto-pinned during load */
8571 	for (i = 0; i < obj->nr_maps; i++)
8572 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8573 			bpf_map__unpin(&obj->maps[i], NULL);
8574 }
8575 
bpf_object_post_load_cleanup(struct bpf_object * obj)8576 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8577 {
8578 	int i;
8579 
8580 	/* clean up fd_array */
8581 	zfree(&obj->fd_array);
8582 
8583 	/* clean up module BTFs */
8584 	for (i = 0; i < obj->btf_module_cnt; i++) {
8585 		close(obj->btf_modules[i].fd);
8586 		btf__free(obj->btf_modules[i].btf);
8587 		free(obj->btf_modules[i].name);
8588 	}
8589 	obj->btf_module_cnt = 0;
8590 	zfree(&obj->btf_modules);
8591 
8592 	/* clean up vmlinux BTF */
8593 	btf__free(obj->btf_vmlinux);
8594 	obj->btf_vmlinux = NULL;
8595 }
8596 
bpf_object_prepare(struct bpf_object * obj,const char * target_btf_path)8597 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8598 {
8599 	int err;
8600 
8601 	if (obj->state >= OBJ_PREPARED) {
8602 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8603 		return -EINVAL;
8604 	}
8605 
8606 	err = bpf_object_prepare_token(obj);
8607 	err = err ? : bpf_object__probe_loading(obj);
8608 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8609 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8610 	err = err ? : bpf_object__sanitize_maps(obj);
8611 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8612 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8613 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8614 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8615 	err = err ? : bpf_object__create_maps(obj);
8616 	err = err ? : bpf_object_prepare_progs(obj);
8617 
8618 	if (err) {
8619 		bpf_object_unpin(obj);
8620 		bpf_object_unload(obj);
8621 		obj->state = OBJ_LOADED;
8622 		return err;
8623 	}
8624 
8625 	obj->state = OBJ_PREPARED;
8626 	return 0;
8627 }
8628 
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)8629 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8630 {
8631 	int err;
8632 
8633 	if (!obj)
8634 		return libbpf_err(-EINVAL);
8635 
8636 	if (obj->state >= OBJ_LOADED) {
8637 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8638 		return libbpf_err(-EINVAL);
8639 	}
8640 
8641 	/* Disallow kernel loading programs of non-native endianness but
8642 	 * permit cross-endian creation of "light skeleton".
8643 	 */
8644 	if (obj->gen_loader) {
8645 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8646 	} else if (!is_native_endianness(obj)) {
8647 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8648 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8649 	}
8650 
8651 	if (obj->state < OBJ_PREPARED) {
8652 		err = bpf_object_prepare(obj, target_btf_path);
8653 		if (err)
8654 			return libbpf_err(err);
8655 	}
8656 	err = bpf_object__load_progs(obj, extra_log_level);
8657 	err = err ? : bpf_object_init_prog_arrays(obj);
8658 	err = err ? : bpf_object_prepare_struct_ops(obj);
8659 
8660 	if (obj->gen_loader) {
8661 		/* reset FDs */
8662 		if (obj->btf)
8663 			btf__set_fd(obj->btf, -1);
8664 		if (!err)
8665 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8666 	}
8667 
8668 	bpf_object_post_load_cleanup(obj);
8669 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8670 
8671 	if (err) {
8672 		bpf_object_unpin(obj);
8673 		bpf_object_unload(obj);
8674 		pr_warn("failed to load object '%s'\n", obj->path);
8675 		return libbpf_err(err);
8676 	}
8677 
8678 	return 0;
8679 }
8680 
bpf_object__prepare(struct bpf_object * obj)8681 int bpf_object__prepare(struct bpf_object *obj)
8682 {
8683 	return libbpf_err(bpf_object_prepare(obj, NULL));
8684 }
8685 
bpf_object__load(struct bpf_object * obj)8686 int bpf_object__load(struct bpf_object *obj)
8687 {
8688 	return bpf_object_load(obj, 0, NULL);
8689 }
8690 
make_parent_dir(const char * path)8691 static int make_parent_dir(const char *path)
8692 {
8693 	char *dname, *dir;
8694 	int err = 0;
8695 
8696 	dname = strdup(path);
8697 	if (dname == NULL)
8698 		return -ENOMEM;
8699 
8700 	dir = dirname(dname);
8701 	if (mkdir(dir, 0700) && errno != EEXIST)
8702 		err = -errno;
8703 
8704 	free(dname);
8705 	if (err) {
8706 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8707 	}
8708 	return err;
8709 }
8710 
check_path(const char * path)8711 static int check_path(const char *path)
8712 {
8713 	struct statfs st_fs;
8714 	char *dname, *dir;
8715 	int err = 0;
8716 
8717 	if (path == NULL)
8718 		return -EINVAL;
8719 
8720 	dname = strdup(path);
8721 	if (dname == NULL)
8722 		return -ENOMEM;
8723 
8724 	dir = dirname(dname);
8725 	if (statfs(dir, &st_fs)) {
8726 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8727 		err = -errno;
8728 	}
8729 	free(dname);
8730 
8731 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8732 		pr_warn("specified path %s is not on BPF FS\n", path);
8733 		err = -EINVAL;
8734 	}
8735 
8736 	return err;
8737 }
8738 
bpf_program__pin(struct bpf_program * prog,const char * path)8739 int bpf_program__pin(struct bpf_program *prog, const char *path)
8740 {
8741 	int err;
8742 
8743 	if (prog->fd < 0) {
8744 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8745 		return libbpf_err(-EINVAL);
8746 	}
8747 
8748 	err = make_parent_dir(path);
8749 	if (err)
8750 		return libbpf_err(err);
8751 
8752 	err = check_path(path);
8753 	if (err)
8754 		return libbpf_err(err);
8755 
8756 	if (bpf_obj_pin(prog->fd, path)) {
8757 		err = -errno;
8758 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8759 		return libbpf_err(err);
8760 	}
8761 
8762 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8763 	return 0;
8764 }
8765 
bpf_program__unpin(struct bpf_program * prog,const char * path)8766 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8767 {
8768 	int err;
8769 
8770 	if (prog->fd < 0) {
8771 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8772 		return libbpf_err(-EINVAL);
8773 	}
8774 
8775 	err = check_path(path);
8776 	if (err)
8777 		return libbpf_err(err);
8778 
8779 	err = unlink(path);
8780 	if (err)
8781 		return libbpf_err(-errno);
8782 
8783 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8784 	return 0;
8785 }
8786 
bpf_map__pin(struct bpf_map * map,const char * path)8787 int bpf_map__pin(struct bpf_map *map, const char *path)
8788 {
8789 	int err;
8790 
8791 	if (map == NULL) {
8792 		pr_warn("invalid map pointer\n");
8793 		return libbpf_err(-EINVAL);
8794 	}
8795 
8796 	if (map->fd < 0) {
8797 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8798 		return libbpf_err(-EINVAL);
8799 	}
8800 
8801 	if (map->pin_path) {
8802 		if (path && strcmp(path, map->pin_path)) {
8803 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8804 				bpf_map__name(map), map->pin_path, path);
8805 			return libbpf_err(-EINVAL);
8806 		} else if (map->pinned) {
8807 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8808 				 bpf_map__name(map), map->pin_path);
8809 			return 0;
8810 		}
8811 	} else {
8812 		if (!path) {
8813 			pr_warn("missing a path to pin map '%s' at\n",
8814 				bpf_map__name(map));
8815 			return libbpf_err(-EINVAL);
8816 		} else if (map->pinned) {
8817 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8818 			return libbpf_err(-EEXIST);
8819 		}
8820 
8821 		map->pin_path = strdup(path);
8822 		if (!map->pin_path) {
8823 			err = -errno;
8824 			goto out_err;
8825 		}
8826 	}
8827 
8828 	err = make_parent_dir(map->pin_path);
8829 	if (err)
8830 		return libbpf_err(err);
8831 
8832 	err = check_path(map->pin_path);
8833 	if (err)
8834 		return libbpf_err(err);
8835 
8836 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8837 		err = -errno;
8838 		goto out_err;
8839 	}
8840 
8841 	map->pinned = true;
8842 	pr_debug("pinned map '%s'\n", map->pin_path);
8843 
8844 	return 0;
8845 
8846 out_err:
8847 	pr_warn("failed to pin map: %s\n", errstr(err));
8848 	return libbpf_err(err);
8849 }
8850 
bpf_map__unpin(struct bpf_map * map,const char * path)8851 int bpf_map__unpin(struct bpf_map *map, const char *path)
8852 {
8853 	int err;
8854 
8855 	if (map == NULL) {
8856 		pr_warn("invalid map pointer\n");
8857 		return libbpf_err(-EINVAL);
8858 	}
8859 
8860 	if (map->pin_path) {
8861 		if (path && strcmp(path, map->pin_path)) {
8862 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8863 				bpf_map__name(map), map->pin_path, path);
8864 			return libbpf_err(-EINVAL);
8865 		}
8866 		path = map->pin_path;
8867 	} else if (!path) {
8868 		pr_warn("no path to unpin map '%s' from\n",
8869 			bpf_map__name(map));
8870 		return libbpf_err(-EINVAL);
8871 	}
8872 
8873 	err = check_path(path);
8874 	if (err)
8875 		return libbpf_err(err);
8876 
8877 	err = unlink(path);
8878 	if (err != 0)
8879 		return libbpf_err(-errno);
8880 
8881 	map->pinned = false;
8882 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8883 
8884 	return 0;
8885 }
8886 
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8887 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8888 {
8889 	char *new = NULL;
8890 
8891 	if (path) {
8892 		new = strdup(path);
8893 		if (!new)
8894 			return libbpf_err(-errno);
8895 	}
8896 
8897 	free(map->pin_path);
8898 	map->pin_path = new;
8899 	return 0;
8900 }
8901 
8902 __alias(bpf_map__pin_path)
8903 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8904 
bpf_map__pin_path(const struct bpf_map * map)8905 const char *bpf_map__pin_path(const struct bpf_map *map)
8906 {
8907 	return map->pin_path;
8908 }
8909 
bpf_map__is_pinned(const struct bpf_map * map)8910 bool bpf_map__is_pinned(const struct bpf_map *map)
8911 {
8912 	return map->pinned;
8913 }
8914 
sanitize_pin_path(char * s)8915 static void sanitize_pin_path(char *s)
8916 {
8917 	/* bpffs disallows periods in path names */
8918 	while (*s) {
8919 		if (*s == '.')
8920 			*s = '_';
8921 		s++;
8922 	}
8923 }
8924 
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8925 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8926 {
8927 	struct bpf_map *map;
8928 	int err;
8929 
8930 	if (!obj)
8931 		return libbpf_err(-ENOENT);
8932 
8933 	if (obj->state < OBJ_PREPARED) {
8934 		pr_warn("object not yet loaded; load it first\n");
8935 		return libbpf_err(-ENOENT);
8936 	}
8937 
8938 	bpf_object__for_each_map(map, obj) {
8939 		char *pin_path = NULL;
8940 		char buf[PATH_MAX];
8941 
8942 		if (!map->autocreate)
8943 			continue;
8944 
8945 		if (path) {
8946 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8947 			if (err)
8948 				goto err_unpin_maps;
8949 			sanitize_pin_path(buf);
8950 			pin_path = buf;
8951 		} else if (!map->pin_path) {
8952 			continue;
8953 		}
8954 
8955 		err = bpf_map__pin(map, pin_path);
8956 		if (err)
8957 			goto err_unpin_maps;
8958 	}
8959 
8960 	return 0;
8961 
8962 err_unpin_maps:
8963 	while ((map = bpf_object__prev_map(obj, map))) {
8964 		if (!map->pin_path)
8965 			continue;
8966 
8967 		bpf_map__unpin(map, NULL);
8968 	}
8969 
8970 	return libbpf_err(err);
8971 }
8972 
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8973 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8974 {
8975 	struct bpf_map *map;
8976 	int err;
8977 
8978 	if (!obj)
8979 		return libbpf_err(-ENOENT);
8980 
8981 	bpf_object__for_each_map(map, obj) {
8982 		char *pin_path = NULL;
8983 		char buf[PATH_MAX];
8984 
8985 		if (path) {
8986 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8987 			if (err)
8988 				return libbpf_err(err);
8989 			sanitize_pin_path(buf);
8990 			pin_path = buf;
8991 		} else if (!map->pin_path) {
8992 			continue;
8993 		}
8994 
8995 		err = bpf_map__unpin(map, pin_path);
8996 		if (err)
8997 			return libbpf_err(err);
8998 	}
8999 
9000 	return 0;
9001 }
9002 
bpf_object__pin_programs(struct bpf_object * obj,const char * path)9003 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9004 {
9005 	struct bpf_program *prog;
9006 	char buf[PATH_MAX];
9007 	int err;
9008 
9009 	if (!obj)
9010 		return libbpf_err(-ENOENT);
9011 
9012 	if (obj->state < OBJ_LOADED) {
9013 		pr_warn("object not yet loaded; load it first\n");
9014 		return libbpf_err(-ENOENT);
9015 	}
9016 
9017 	bpf_object__for_each_program(prog, obj) {
9018 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9019 		if (err)
9020 			goto err_unpin_programs;
9021 
9022 		err = bpf_program__pin(prog, buf);
9023 		if (err)
9024 			goto err_unpin_programs;
9025 	}
9026 
9027 	return 0;
9028 
9029 err_unpin_programs:
9030 	while ((prog = bpf_object__prev_program(obj, prog))) {
9031 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9032 			continue;
9033 
9034 		bpf_program__unpin(prog, buf);
9035 	}
9036 
9037 	return libbpf_err(err);
9038 }
9039 
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)9040 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9041 {
9042 	struct bpf_program *prog;
9043 	int err;
9044 
9045 	if (!obj)
9046 		return libbpf_err(-ENOENT);
9047 
9048 	bpf_object__for_each_program(prog, obj) {
9049 		char buf[PATH_MAX];
9050 
9051 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9052 		if (err)
9053 			return libbpf_err(err);
9054 
9055 		err = bpf_program__unpin(prog, buf);
9056 		if (err)
9057 			return libbpf_err(err);
9058 	}
9059 
9060 	return 0;
9061 }
9062 
bpf_object__pin(struct bpf_object * obj,const char * path)9063 int bpf_object__pin(struct bpf_object *obj, const char *path)
9064 {
9065 	int err;
9066 
9067 	err = bpf_object__pin_maps(obj, path);
9068 	if (err)
9069 		return libbpf_err(err);
9070 
9071 	err = bpf_object__pin_programs(obj, path);
9072 	if (err) {
9073 		bpf_object__unpin_maps(obj, path);
9074 		return libbpf_err(err);
9075 	}
9076 
9077 	return 0;
9078 }
9079 
bpf_object__unpin(struct bpf_object * obj,const char * path)9080 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9081 {
9082 	int err;
9083 
9084 	err = bpf_object__unpin_programs(obj, path);
9085 	if (err)
9086 		return libbpf_err(err);
9087 
9088 	err = bpf_object__unpin_maps(obj, path);
9089 	if (err)
9090 		return libbpf_err(err);
9091 
9092 	return 0;
9093 }
9094 
bpf_map__destroy(struct bpf_map * map)9095 static void bpf_map__destroy(struct bpf_map *map)
9096 {
9097 	if (map->inner_map) {
9098 		bpf_map__destroy(map->inner_map);
9099 		zfree(&map->inner_map);
9100 	}
9101 
9102 	zfree(&map->init_slots);
9103 	map->init_slots_sz = 0;
9104 
9105 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9106 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9107 	map->mmaped = NULL;
9108 
9109 	if (map->st_ops) {
9110 		zfree(&map->st_ops->data);
9111 		zfree(&map->st_ops->progs);
9112 		zfree(&map->st_ops->kern_func_off);
9113 		zfree(&map->st_ops);
9114 	}
9115 
9116 	zfree(&map->name);
9117 	zfree(&map->real_name);
9118 	zfree(&map->pin_path);
9119 
9120 	if (map->fd >= 0)
9121 		zclose(map->fd);
9122 }
9123 
bpf_object__close(struct bpf_object * obj)9124 void bpf_object__close(struct bpf_object *obj)
9125 {
9126 	size_t i;
9127 
9128 	if (IS_ERR_OR_NULL(obj))
9129 		return;
9130 
9131 	/*
9132 	 * if user called bpf_object__prepare() without ever getting to
9133 	 * bpf_object__load(), we need to clean up stuff that is normally
9134 	 * cleaned up at the end of loading step
9135 	 */
9136 	bpf_object_post_load_cleanup(obj);
9137 
9138 	usdt_manager_free(obj->usdt_man);
9139 	obj->usdt_man = NULL;
9140 
9141 	bpf_gen__free(obj->gen_loader);
9142 	bpf_object__elf_finish(obj);
9143 	bpf_object_unload(obj);
9144 	btf__free(obj->btf);
9145 	btf__free(obj->btf_vmlinux);
9146 	btf_ext__free(obj->btf_ext);
9147 
9148 	for (i = 0; i < obj->nr_maps; i++)
9149 		bpf_map__destroy(&obj->maps[i]);
9150 
9151 	zfree(&obj->btf_custom_path);
9152 	zfree(&obj->kconfig);
9153 
9154 	for (i = 0; i < obj->nr_extern; i++) {
9155 		zfree(&obj->externs[i].name);
9156 		zfree(&obj->externs[i].essent_name);
9157 	}
9158 
9159 	zfree(&obj->externs);
9160 	obj->nr_extern = 0;
9161 
9162 	zfree(&obj->maps);
9163 	obj->nr_maps = 0;
9164 
9165 	if (obj->programs && obj->nr_programs) {
9166 		for (i = 0; i < obj->nr_programs; i++)
9167 			bpf_program__exit(&obj->programs[i]);
9168 	}
9169 	zfree(&obj->programs);
9170 
9171 	zfree(&obj->feat_cache);
9172 	zfree(&obj->token_path);
9173 	if (obj->token_fd > 0)
9174 		close(obj->token_fd);
9175 
9176 	zfree(&obj->arena_data);
9177 
9178 	free(obj);
9179 }
9180 
bpf_object__name(const struct bpf_object * obj)9181 const char *bpf_object__name(const struct bpf_object *obj)
9182 {
9183 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9184 }
9185 
bpf_object__kversion(const struct bpf_object * obj)9186 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9187 {
9188 	return obj ? obj->kern_version : 0;
9189 }
9190 
bpf_object__token_fd(const struct bpf_object * obj)9191 int bpf_object__token_fd(const struct bpf_object *obj)
9192 {
9193 	return obj->token_fd ?: -1;
9194 }
9195 
bpf_object__btf(const struct bpf_object * obj)9196 struct btf *bpf_object__btf(const struct bpf_object *obj)
9197 {
9198 	return obj ? obj->btf : NULL;
9199 }
9200 
bpf_object__btf_fd(const struct bpf_object * obj)9201 int bpf_object__btf_fd(const struct bpf_object *obj)
9202 {
9203 	return obj->btf ? btf__fd(obj->btf) : -1;
9204 }
9205 
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)9206 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9207 {
9208 	if (obj->state >= OBJ_LOADED)
9209 		return libbpf_err(-EINVAL);
9210 
9211 	obj->kern_version = kern_version;
9212 
9213 	return 0;
9214 }
9215 
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)9216 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9217 {
9218 	struct bpf_gen *gen;
9219 
9220 	if (!opts)
9221 		return libbpf_err(-EFAULT);
9222 	if (!OPTS_VALID(opts, gen_loader_opts))
9223 		return libbpf_err(-EINVAL);
9224 	gen = calloc(1, sizeof(*gen));
9225 	if (!gen)
9226 		return libbpf_err(-ENOMEM);
9227 	gen->opts = opts;
9228 	gen->swapped_endian = !is_native_endianness(obj);
9229 	obj->gen_loader = gen;
9230 	return 0;
9231 }
9232 
9233 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)9234 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9235 		    bool forward)
9236 {
9237 	size_t nr_programs = obj->nr_programs;
9238 	ssize_t idx;
9239 
9240 	if (!nr_programs)
9241 		return NULL;
9242 
9243 	if (!p)
9244 		/* Iter from the beginning */
9245 		return forward ? &obj->programs[0] :
9246 			&obj->programs[nr_programs - 1];
9247 
9248 	if (p->obj != obj) {
9249 		pr_warn("error: program handler doesn't match object\n");
9250 		return errno = EINVAL, NULL;
9251 	}
9252 
9253 	idx = (p - obj->programs) + (forward ? 1 : -1);
9254 	if (idx >= obj->nr_programs || idx < 0)
9255 		return NULL;
9256 	return &obj->programs[idx];
9257 }
9258 
9259 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)9260 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9261 {
9262 	struct bpf_program *prog = prev;
9263 
9264 	do {
9265 		prog = __bpf_program__iter(prog, obj, true);
9266 	} while (prog && prog_is_subprog(obj, prog));
9267 
9268 	return prog;
9269 }
9270 
9271 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)9272 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9273 {
9274 	struct bpf_program *prog = next;
9275 
9276 	do {
9277 		prog = __bpf_program__iter(prog, obj, false);
9278 	} while (prog && prog_is_subprog(obj, prog));
9279 
9280 	return prog;
9281 }
9282 
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)9283 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9284 {
9285 	prog->prog_ifindex = ifindex;
9286 }
9287 
bpf_program__name(const struct bpf_program * prog)9288 const char *bpf_program__name(const struct bpf_program *prog)
9289 {
9290 	return prog->name;
9291 }
9292 
bpf_program__section_name(const struct bpf_program * prog)9293 const char *bpf_program__section_name(const struct bpf_program *prog)
9294 {
9295 	return prog->sec_name;
9296 }
9297 
bpf_program__autoload(const struct bpf_program * prog)9298 bool bpf_program__autoload(const struct bpf_program *prog)
9299 {
9300 	return prog->autoload;
9301 }
9302 
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)9303 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9304 {
9305 	if (prog->obj->state >= OBJ_LOADED)
9306 		return libbpf_err(-EINVAL);
9307 
9308 	prog->autoload = autoload;
9309 	return 0;
9310 }
9311 
bpf_program__autoattach(const struct bpf_program * prog)9312 bool bpf_program__autoattach(const struct bpf_program *prog)
9313 {
9314 	return prog->autoattach;
9315 }
9316 
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)9317 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9318 {
9319 	prog->autoattach = autoattach;
9320 }
9321 
bpf_program__insns(const struct bpf_program * prog)9322 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9323 {
9324 	return prog->insns;
9325 }
9326 
bpf_program__insn_cnt(const struct bpf_program * prog)9327 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9328 {
9329 	return prog->insns_cnt;
9330 }
9331 
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)9332 int bpf_program__set_insns(struct bpf_program *prog,
9333 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9334 {
9335 	struct bpf_insn *insns;
9336 
9337 	if (prog->obj->state >= OBJ_LOADED)
9338 		return libbpf_err(-EBUSY);
9339 
9340 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9341 	/* NULL is a valid return from reallocarray if the new count is zero */
9342 	if (!insns && new_insn_cnt) {
9343 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9344 		return libbpf_err(-ENOMEM);
9345 	}
9346 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9347 
9348 	prog->insns = insns;
9349 	prog->insns_cnt = new_insn_cnt;
9350 	return 0;
9351 }
9352 
bpf_program__fd(const struct bpf_program * prog)9353 int bpf_program__fd(const struct bpf_program *prog)
9354 {
9355 	if (!prog)
9356 		return libbpf_err(-EINVAL);
9357 
9358 	if (prog->fd < 0)
9359 		return libbpf_err(-ENOENT);
9360 
9361 	return prog->fd;
9362 }
9363 
9364 __alias(bpf_program__type)
9365 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9366 
bpf_program__type(const struct bpf_program * prog)9367 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9368 {
9369 	return prog->type;
9370 }
9371 
9372 static size_t custom_sec_def_cnt;
9373 static struct bpf_sec_def *custom_sec_defs;
9374 static struct bpf_sec_def custom_fallback_def;
9375 static bool has_custom_fallback_def;
9376 static int last_custom_sec_def_handler_id;
9377 
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)9378 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9379 {
9380 	if (prog->obj->state >= OBJ_LOADED)
9381 		return libbpf_err(-EBUSY);
9382 
9383 	/* if type is not changed, do nothing */
9384 	if (prog->type == type)
9385 		return 0;
9386 
9387 	prog->type = type;
9388 
9389 	/* If a program type was changed, we need to reset associated SEC()
9390 	 * handler, as it will be invalid now. The only exception is a generic
9391 	 * fallback handler, which by definition is program type-agnostic and
9392 	 * is a catch-all custom handler, optionally set by the application,
9393 	 * so should be able to handle any type of BPF program.
9394 	 */
9395 	if (prog->sec_def != &custom_fallback_def)
9396 		prog->sec_def = NULL;
9397 	return 0;
9398 }
9399 
9400 __alias(bpf_program__expected_attach_type)
9401 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9402 
bpf_program__expected_attach_type(const struct bpf_program * prog)9403 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9404 {
9405 	return prog->expected_attach_type;
9406 }
9407 
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)9408 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9409 					   enum bpf_attach_type type)
9410 {
9411 	if (prog->obj->state >= OBJ_LOADED)
9412 		return libbpf_err(-EBUSY);
9413 
9414 	prog->expected_attach_type = type;
9415 	return 0;
9416 }
9417 
bpf_program__flags(const struct bpf_program * prog)9418 __u32 bpf_program__flags(const struct bpf_program *prog)
9419 {
9420 	return prog->prog_flags;
9421 }
9422 
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)9423 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9424 {
9425 	if (prog->obj->state >= OBJ_LOADED)
9426 		return libbpf_err(-EBUSY);
9427 
9428 	prog->prog_flags = flags;
9429 	return 0;
9430 }
9431 
bpf_program__log_level(const struct bpf_program * prog)9432 __u32 bpf_program__log_level(const struct bpf_program *prog)
9433 {
9434 	return prog->log_level;
9435 }
9436 
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)9437 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9438 {
9439 	if (prog->obj->state >= OBJ_LOADED)
9440 		return libbpf_err(-EBUSY);
9441 
9442 	prog->log_level = log_level;
9443 	return 0;
9444 }
9445 
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)9446 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9447 {
9448 	*log_size = prog->log_size;
9449 	return prog->log_buf;
9450 }
9451 
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)9452 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9453 {
9454 	if (log_size && !log_buf)
9455 		return libbpf_err(-EINVAL);
9456 	if (prog->log_size > UINT_MAX)
9457 		return libbpf_err(-EINVAL);
9458 	if (prog->obj->state >= OBJ_LOADED)
9459 		return libbpf_err(-EBUSY);
9460 
9461 	prog->log_buf = log_buf;
9462 	prog->log_size = log_size;
9463 	return 0;
9464 }
9465 
bpf_program__func_info(const struct bpf_program * prog)9466 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9467 {
9468 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9469 		return libbpf_err_ptr(-EOPNOTSUPP);
9470 	return prog->func_info;
9471 }
9472 
bpf_program__func_info_cnt(const struct bpf_program * prog)9473 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9474 {
9475 	return prog->func_info_cnt;
9476 }
9477 
bpf_program__line_info(const struct bpf_program * prog)9478 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9479 {
9480 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9481 		return libbpf_err_ptr(-EOPNOTSUPP);
9482 	return prog->line_info;
9483 }
9484 
bpf_program__line_info_cnt(const struct bpf_program * prog)9485 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9486 {
9487 	return prog->line_info_cnt;
9488 }
9489 
9490 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9491 	.sec = (char *)sec_pfx,						    \
9492 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9493 	.expected_attach_type = atype,					    \
9494 	.cookie = (long)(flags),					    \
9495 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9496 	__VA_ARGS__							    \
9497 }
9498 
9499 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9500 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9501 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9502 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9503 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9504 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9505 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9506 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9507 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9508 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9509 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9510 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9511 
9512 static const struct bpf_sec_def section_defs[] = {
9513 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9514 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9515 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9516 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9517 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9518 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9519 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9520 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9521 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9522 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9523 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9524 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9525 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9526 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9527 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9528 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9529 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9530 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9531 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9532 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9533 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9534 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9535 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9536 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9537 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9538 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9539 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9540 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9541 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9542 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9543 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9544 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9545 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9546 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9547 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9548 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9549 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9550 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9551 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9552 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9553 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9554 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9555 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9556 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9557 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9558 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9559 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9560 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9561 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9562 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9563 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9564 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9565 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9566 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9567 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9568 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9569 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9570 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9571 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9572 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9573 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9574 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9575 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9576 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9577 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9578 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9579 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9580 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9581 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9582 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9583 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9584 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9585 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9586 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9587 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9588 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9589 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9590 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9591 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9592 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9593 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9594 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9595 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9596 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9597 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9598 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9599 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9600 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9601 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9602 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9603 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9604 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9605 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9606 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9607 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9608 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9609 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9610 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9611 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9612 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9613 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9614 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9615 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9616 };
9617 
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)9618 int libbpf_register_prog_handler(const char *sec,
9619 				 enum bpf_prog_type prog_type,
9620 				 enum bpf_attach_type exp_attach_type,
9621 				 const struct libbpf_prog_handler_opts *opts)
9622 {
9623 	struct bpf_sec_def *sec_def;
9624 
9625 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9626 		return libbpf_err(-EINVAL);
9627 
9628 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9629 		return libbpf_err(-E2BIG);
9630 
9631 	if (sec) {
9632 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9633 					      sizeof(*sec_def));
9634 		if (!sec_def)
9635 			return libbpf_err(-ENOMEM);
9636 
9637 		custom_sec_defs = sec_def;
9638 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9639 	} else {
9640 		if (has_custom_fallback_def)
9641 			return libbpf_err(-EBUSY);
9642 
9643 		sec_def = &custom_fallback_def;
9644 	}
9645 
9646 	sec_def->sec = sec ? strdup(sec) : NULL;
9647 	if (sec && !sec_def->sec)
9648 		return libbpf_err(-ENOMEM);
9649 
9650 	sec_def->prog_type = prog_type;
9651 	sec_def->expected_attach_type = exp_attach_type;
9652 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9653 
9654 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9655 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9656 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9657 
9658 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9659 
9660 	if (sec)
9661 		custom_sec_def_cnt++;
9662 	else
9663 		has_custom_fallback_def = true;
9664 
9665 	return sec_def->handler_id;
9666 }
9667 
libbpf_unregister_prog_handler(int handler_id)9668 int libbpf_unregister_prog_handler(int handler_id)
9669 {
9670 	struct bpf_sec_def *sec_defs;
9671 	int i;
9672 
9673 	if (handler_id <= 0)
9674 		return libbpf_err(-EINVAL);
9675 
9676 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9677 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9678 		has_custom_fallback_def = false;
9679 		return 0;
9680 	}
9681 
9682 	for (i = 0; i < custom_sec_def_cnt; i++) {
9683 		if (custom_sec_defs[i].handler_id == handler_id)
9684 			break;
9685 	}
9686 
9687 	if (i == custom_sec_def_cnt)
9688 		return libbpf_err(-ENOENT);
9689 
9690 	free(custom_sec_defs[i].sec);
9691 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9692 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9693 	custom_sec_def_cnt--;
9694 
9695 	/* try to shrink the array, but it's ok if we couldn't */
9696 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9697 	/* if new count is zero, reallocarray can return a valid NULL result;
9698 	 * in this case the previous pointer will be freed, so we *have to*
9699 	 * reassign old pointer to the new value (even if it's NULL)
9700 	 */
9701 	if (sec_defs || custom_sec_def_cnt == 0)
9702 		custom_sec_defs = sec_defs;
9703 
9704 	return 0;
9705 }
9706 
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)9707 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9708 {
9709 	size_t len = strlen(sec_def->sec);
9710 
9711 	/* "type/" always has to have proper SEC("type/extras") form */
9712 	if (sec_def->sec[len - 1] == '/') {
9713 		if (str_has_pfx(sec_name, sec_def->sec))
9714 			return true;
9715 		return false;
9716 	}
9717 
9718 	/* "type+" means it can be either exact SEC("type") or
9719 	 * well-formed SEC("type/extras") with proper '/' separator
9720 	 */
9721 	if (sec_def->sec[len - 1] == '+') {
9722 		len--;
9723 		/* not even a prefix */
9724 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9725 			return false;
9726 		/* exact match or has '/' separator */
9727 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9728 			return true;
9729 		return false;
9730 	}
9731 
9732 	return strcmp(sec_name, sec_def->sec) == 0;
9733 }
9734 
find_sec_def(const char * sec_name)9735 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9736 {
9737 	const struct bpf_sec_def *sec_def;
9738 	int i, n;
9739 
9740 	n = custom_sec_def_cnt;
9741 	for (i = 0; i < n; i++) {
9742 		sec_def = &custom_sec_defs[i];
9743 		if (sec_def_matches(sec_def, sec_name))
9744 			return sec_def;
9745 	}
9746 
9747 	n = ARRAY_SIZE(section_defs);
9748 	for (i = 0; i < n; i++) {
9749 		sec_def = &section_defs[i];
9750 		if (sec_def_matches(sec_def, sec_name))
9751 			return sec_def;
9752 	}
9753 
9754 	if (has_custom_fallback_def)
9755 		return &custom_fallback_def;
9756 
9757 	return NULL;
9758 }
9759 
9760 #define MAX_TYPE_NAME_SIZE 32
9761 
libbpf_get_type_names(bool attach_type)9762 static char *libbpf_get_type_names(bool attach_type)
9763 {
9764 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9765 	char *buf;
9766 
9767 	buf = malloc(len);
9768 	if (!buf)
9769 		return NULL;
9770 
9771 	buf[0] = '\0';
9772 	/* Forge string buf with all available names */
9773 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9774 		const struct bpf_sec_def *sec_def = &section_defs[i];
9775 
9776 		if (attach_type) {
9777 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9778 				continue;
9779 
9780 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9781 				continue;
9782 		}
9783 
9784 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9785 			free(buf);
9786 			return NULL;
9787 		}
9788 		strcat(buf, " ");
9789 		strcat(buf, section_defs[i].sec);
9790 	}
9791 
9792 	return buf;
9793 }
9794 
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9795 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9796 			     enum bpf_attach_type *expected_attach_type)
9797 {
9798 	const struct bpf_sec_def *sec_def;
9799 	char *type_names;
9800 
9801 	if (!name)
9802 		return libbpf_err(-EINVAL);
9803 
9804 	sec_def = find_sec_def(name);
9805 	if (sec_def) {
9806 		*prog_type = sec_def->prog_type;
9807 		*expected_attach_type = sec_def->expected_attach_type;
9808 		return 0;
9809 	}
9810 
9811 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9812 	type_names = libbpf_get_type_names(false);
9813 	if (type_names != NULL) {
9814 		pr_debug("supported section(type) names are:%s\n", type_names);
9815 		free(type_names);
9816 	}
9817 
9818 	return libbpf_err(-ESRCH);
9819 }
9820 
libbpf_bpf_attach_type_str(enum bpf_attach_type t)9821 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9822 {
9823 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9824 		return NULL;
9825 
9826 	return attach_type_name[t];
9827 }
9828 
libbpf_bpf_link_type_str(enum bpf_link_type t)9829 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9830 {
9831 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9832 		return NULL;
9833 
9834 	return link_type_name[t];
9835 }
9836 
libbpf_bpf_map_type_str(enum bpf_map_type t)9837 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9838 {
9839 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9840 		return NULL;
9841 
9842 	return map_type_name[t];
9843 }
9844 
libbpf_bpf_prog_type_str(enum bpf_prog_type t)9845 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9846 {
9847 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9848 		return NULL;
9849 
9850 	return prog_type_name[t];
9851 }
9852 
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)9853 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9854 						     int sec_idx,
9855 						     size_t offset)
9856 {
9857 	struct bpf_map *map;
9858 	size_t i;
9859 
9860 	for (i = 0; i < obj->nr_maps; i++) {
9861 		map = &obj->maps[i];
9862 		if (!bpf_map__is_struct_ops(map))
9863 			continue;
9864 		if (map->sec_idx == sec_idx &&
9865 		    map->sec_offset <= offset &&
9866 		    offset - map->sec_offset < map->def.value_size)
9867 			return map;
9868 	}
9869 
9870 	return NULL;
9871 }
9872 
9873 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9874  * st_ops->data for shadow type.
9875  */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)9876 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9877 					    Elf64_Shdr *shdr, Elf_Data *data)
9878 {
9879 	const struct btf_type *type;
9880 	const struct btf_member *member;
9881 	struct bpf_struct_ops *st_ops;
9882 	struct bpf_program *prog;
9883 	unsigned int shdr_idx;
9884 	const struct btf *btf;
9885 	struct bpf_map *map;
9886 	unsigned int moff, insn_idx;
9887 	const char *name;
9888 	__u32 member_idx;
9889 	Elf64_Sym *sym;
9890 	Elf64_Rel *rel;
9891 	int i, nrels;
9892 
9893 	btf = obj->btf;
9894 	nrels = shdr->sh_size / shdr->sh_entsize;
9895 	for (i = 0; i < nrels; i++) {
9896 		rel = elf_rel_by_idx(data, i);
9897 		if (!rel) {
9898 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9899 			return -LIBBPF_ERRNO__FORMAT;
9900 		}
9901 
9902 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9903 		if (!sym) {
9904 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9905 				(size_t)ELF64_R_SYM(rel->r_info));
9906 			return -LIBBPF_ERRNO__FORMAT;
9907 		}
9908 
9909 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9910 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9911 		if (!map) {
9912 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9913 				(size_t)rel->r_offset);
9914 			return -EINVAL;
9915 		}
9916 
9917 		moff = rel->r_offset - map->sec_offset;
9918 		shdr_idx = sym->st_shndx;
9919 		st_ops = map->st_ops;
9920 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
9921 			 map->name,
9922 			 (long long)(rel->r_info >> 32),
9923 			 (long long)sym->st_value,
9924 			 shdr_idx, (size_t)rel->r_offset,
9925 			 map->sec_offset, sym->st_name, name);
9926 
9927 		if (shdr_idx >= SHN_LORESERVE) {
9928 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9929 				map->name, (size_t)rel->r_offset, shdr_idx);
9930 			return -LIBBPF_ERRNO__RELOC;
9931 		}
9932 		if (sym->st_value % BPF_INSN_SZ) {
9933 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9934 				map->name, (unsigned long long)sym->st_value);
9935 			return -LIBBPF_ERRNO__FORMAT;
9936 		}
9937 		insn_idx = sym->st_value / BPF_INSN_SZ;
9938 
9939 		type = btf__type_by_id(btf, st_ops->type_id);
9940 		member = find_member_by_offset(type, moff * 8);
9941 		if (!member) {
9942 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9943 				map->name, moff);
9944 			return -EINVAL;
9945 		}
9946 		member_idx = member - btf_members(type);
9947 		name = btf__name_by_offset(btf, member->name_off);
9948 
9949 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9950 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9951 				map->name, name);
9952 			return -EINVAL;
9953 		}
9954 
9955 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9956 		if (!prog) {
9957 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9958 				map->name, shdr_idx, name);
9959 			return -EINVAL;
9960 		}
9961 
9962 		/* prevent the use of BPF prog with invalid type */
9963 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9964 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9965 				map->name, prog->name);
9966 			return -EINVAL;
9967 		}
9968 
9969 		st_ops->progs[member_idx] = prog;
9970 
9971 		/* st_ops->data will be exposed to users, being returned by
9972 		 * bpf_map__initial_value() as a pointer to the shadow
9973 		 * type. All function pointers in the original struct type
9974 		 * should be converted to a pointer to struct bpf_program
9975 		 * in the shadow type.
9976 		 */
9977 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9978 	}
9979 
9980 	return 0;
9981 }
9982 
9983 #define BTF_TRACE_PREFIX "btf_trace_"
9984 #define BTF_LSM_PREFIX "bpf_lsm_"
9985 #define BTF_ITER_PREFIX "bpf_iter_"
9986 #define BTF_MAX_NAME_SIZE 128
9987 
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9988 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9989 				const char **prefix, int *kind)
9990 {
9991 	switch (attach_type) {
9992 	case BPF_TRACE_RAW_TP:
9993 		*prefix = BTF_TRACE_PREFIX;
9994 		*kind = BTF_KIND_TYPEDEF;
9995 		break;
9996 	case BPF_LSM_MAC:
9997 	case BPF_LSM_CGROUP:
9998 		*prefix = BTF_LSM_PREFIX;
9999 		*kind = BTF_KIND_FUNC;
10000 		break;
10001 	case BPF_TRACE_ITER:
10002 		*prefix = BTF_ITER_PREFIX;
10003 		*kind = BTF_KIND_FUNC;
10004 		break;
10005 	default:
10006 		*prefix = "";
10007 		*kind = BTF_KIND_FUNC;
10008 	}
10009 }
10010 
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)10011 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10012 				   const char *name, __u32 kind)
10013 {
10014 	char btf_type_name[BTF_MAX_NAME_SIZE];
10015 	int ret;
10016 
10017 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10018 		       "%s%s", prefix, name);
10019 	/* snprintf returns the number of characters written excluding the
10020 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10021 	 * indicates truncation.
10022 	 */
10023 	if (ret < 0 || ret >= sizeof(btf_type_name))
10024 		return -ENAMETOOLONG;
10025 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10026 }
10027 
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)10028 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10029 				     enum bpf_attach_type attach_type)
10030 {
10031 	const char *prefix;
10032 	int kind;
10033 
10034 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10035 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10036 }
10037 
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)10038 int libbpf_find_vmlinux_btf_id(const char *name,
10039 			       enum bpf_attach_type attach_type)
10040 {
10041 	struct btf *btf;
10042 	int err;
10043 
10044 	btf = btf__load_vmlinux_btf();
10045 	err = libbpf_get_error(btf);
10046 	if (err) {
10047 		pr_warn("vmlinux BTF is not found\n");
10048 		return libbpf_err(err);
10049 	}
10050 
10051 	err = find_attach_btf_id(btf, name, attach_type);
10052 	if (err <= 0)
10053 		pr_warn("%s is not found in vmlinux BTF\n", name);
10054 
10055 	btf__free(btf);
10056 	return libbpf_err(err);
10057 }
10058 
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd,int token_fd)10059 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10060 {
10061 	struct bpf_prog_info info;
10062 	__u32 info_len = sizeof(info);
10063 	struct btf *btf;
10064 	int err;
10065 
10066 	memset(&info, 0, info_len);
10067 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10068 	if (err) {
10069 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10070 			attach_prog_fd, errstr(err));
10071 		return err;
10072 	}
10073 
10074 	err = -EINVAL;
10075 	if (!info.btf_id) {
10076 		pr_warn("The target program doesn't have BTF\n");
10077 		goto out;
10078 	}
10079 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10080 	err = libbpf_get_error(btf);
10081 	if (err) {
10082 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10083 		goto out;
10084 	}
10085 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10086 	btf__free(btf);
10087 	if (err <= 0) {
10088 		pr_warn("%s is not found in prog's BTF\n", name);
10089 		goto out;
10090 	}
10091 out:
10092 	return err;
10093 }
10094 
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)10095 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10096 			      enum bpf_attach_type attach_type,
10097 			      int *btf_obj_fd, int *btf_type_id)
10098 {
10099 	int ret, i, mod_len = 0;
10100 	const char *fn_name, *mod_name = NULL;
10101 
10102 	fn_name = strchr(attach_name, ':');
10103 	if (fn_name) {
10104 		mod_name = attach_name;
10105 		mod_len = fn_name - mod_name;
10106 		fn_name++;
10107 	}
10108 
10109 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10110 		ret = find_attach_btf_id(obj->btf_vmlinux,
10111 					 mod_name ? fn_name : attach_name,
10112 					 attach_type);
10113 		if (ret > 0) {
10114 			*btf_obj_fd = 0; /* vmlinux BTF */
10115 			*btf_type_id = ret;
10116 			return 0;
10117 		}
10118 		if (ret != -ENOENT)
10119 			return ret;
10120 	}
10121 
10122 	ret = load_module_btfs(obj);
10123 	if (ret)
10124 		return ret;
10125 
10126 	for (i = 0; i < obj->btf_module_cnt; i++) {
10127 		const struct module_btf *mod = &obj->btf_modules[i];
10128 
10129 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10130 			continue;
10131 
10132 		ret = find_attach_btf_id(mod->btf,
10133 					 mod_name ? fn_name : attach_name,
10134 					 attach_type);
10135 		if (ret > 0) {
10136 			*btf_obj_fd = mod->fd;
10137 			*btf_type_id = ret;
10138 			return 0;
10139 		}
10140 		if (ret == -ENOENT)
10141 			continue;
10142 
10143 		return ret;
10144 	}
10145 
10146 	return -ESRCH;
10147 }
10148 
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)10149 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10150 				     int *btf_obj_fd, int *btf_type_id)
10151 {
10152 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10153 	__u32 attach_prog_fd = prog->attach_prog_fd;
10154 	int err = 0;
10155 
10156 	/* BPF program's BTF ID */
10157 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10158 		if (!attach_prog_fd) {
10159 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10160 			return -EINVAL;
10161 		}
10162 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10163 		if (err < 0) {
10164 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10165 				prog->name, attach_prog_fd, attach_name, errstr(err));
10166 			return err;
10167 		}
10168 		*btf_obj_fd = 0;
10169 		*btf_type_id = err;
10170 		return 0;
10171 	}
10172 
10173 	/* kernel/module BTF ID */
10174 	if (prog->obj->gen_loader) {
10175 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10176 		*btf_obj_fd = 0;
10177 		*btf_type_id = 1;
10178 	} else {
10179 		err = find_kernel_btf_id(prog->obj, attach_name,
10180 					 attach_type, btf_obj_fd,
10181 					 btf_type_id);
10182 	}
10183 	if (err) {
10184 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10185 			prog->name, attach_name, errstr(err));
10186 		return err;
10187 	}
10188 	return 0;
10189 }
10190 
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)10191 int libbpf_attach_type_by_name(const char *name,
10192 			       enum bpf_attach_type *attach_type)
10193 {
10194 	char *type_names;
10195 	const struct bpf_sec_def *sec_def;
10196 
10197 	if (!name)
10198 		return libbpf_err(-EINVAL);
10199 
10200 	sec_def = find_sec_def(name);
10201 	if (!sec_def) {
10202 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10203 		type_names = libbpf_get_type_names(true);
10204 		if (type_names != NULL) {
10205 			pr_debug("attachable section(type) names are:%s\n", type_names);
10206 			free(type_names);
10207 		}
10208 
10209 		return libbpf_err(-EINVAL);
10210 	}
10211 
10212 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10213 		return libbpf_err(-EINVAL);
10214 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10215 		return libbpf_err(-EINVAL);
10216 
10217 	*attach_type = sec_def->expected_attach_type;
10218 	return 0;
10219 }
10220 
bpf_map__fd(const struct bpf_map * map)10221 int bpf_map__fd(const struct bpf_map *map)
10222 {
10223 	if (!map)
10224 		return libbpf_err(-EINVAL);
10225 	if (!map_is_created(map))
10226 		return -1;
10227 	return map->fd;
10228 }
10229 
map_uses_real_name(const struct bpf_map * map)10230 static bool map_uses_real_name(const struct bpf_map *map)
10231 {
10232 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10233 	 * their user-visible name differs from kernel-visible name. Users see
10234 	 * such map's corresponding ELF section name as a map name.
10235 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10236 	 * maps to know which name has to be returned to the user.
10237 	 */
10238 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10239 		return true;
10240 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10241 		return true;
10242 	return false;
10243 }
10244 
bpf_map__name(const struct bpf_map * map)10245 const char *bpf_map__name(const struct bpf_map *map)
10246 {
10247 	if (!map)
10248 		return NULL;
10249 
10250 	if (map_uses_real_name(map))
10251 		return map->real_name;
10252 
10253 	return map->name;
10254 }
10255 
bpf_map__type(const struct bpf_map * map)10256 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10257 {
10258 	return map->def.type;
10259 }
10260 
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)10261 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10262 {
10263 	if (map_is_created(map))
10264 		return libbpf_err(-EBUSY);
10265 	map->def.type = type;
10266 	return 0;
10267 }
10268 
bpf_map__map_flags(const struct bpf_map * map)10269 __u32 bpf_map__map_flags(const struct bpf_map *map)
10270 {
10271 	return map->def.map_flags;
10272 }
10273 
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)10274 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10275 {
10276 	if (map_is_created(map))
10277 		return libbpf_err(-EBUSY);
10278 	map->def.map_flags = flags;
10279 	return 0;
10280 }
10281 
bpf_map__map_extra(const struct bpf_map * map)10282 __u64 bpf_map__map_extra(const struct bpf_map *map)
10283 {
10284 	return map->map_extra;
10285 }
10286 
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)10287 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10288 {
10289 	if (map_is_created(map))
10290 		return libbpf_err(-EBUSY);
10291 	map->map_extra = map_extra;
10292 	return 0;
10293 }
10294 
bpf_map__numa_node(const struct bpf_map * map)10295 __u32 bpf_map__numa_node(const struct bpf_map *map)
10296 {
10297 	return map->numa_node;
10298 }
10299 
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)10300 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10301 {
10302 	if (map_is_created(map))
10303 		return libbpf_err(-EBUSY);
10304 	map->numa_node = numa_node;
10305 	return 0;
10306 }
10307 
bpf_map__key_size(const struct bpf_map * map)10308 __u32 bpf_map__key_size(const struct bpf_map *map)
10309 {
10310 	return map->def.key_size;
10311 }
10312 
bpf_map__set_key_size(struct bpf_map * map,__u32 size)10313 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10314 {
10315 	if (map_is_created(map))
10316 		return libbpf_err(-EBUSY);
10317 	map->def.key_size = size;
10318 	return 0;
10319 }
10320 
bpf_map__value_size(const struct bpf_map * map)10321 __u32 bpf_map__value_size(const struct bpf_map *map)
10322 {
10323 	return map->def.value_size;
10324 }
10325 
map_btf_datasec_resize(struct bpf_map * map,__u32 size)10326 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10327 {
10328 	struct btf *btf;
10329 	struct btf_type *datasec_type, *var_type;
10330 	struct btf_var_secinfo *var;
10331 	const struct btf_type *array_type;
10332 	const struct btf_array *array;
10333 	int vlen, element_sz, new_array_id;
10334 	__u32 nr_elements;
10335 
10336 	/* check btf existence */
10337 	btf = bpf_object__btf(map->obj);
10338 	if (!btf)
10339 		return -ENOENT;
10340 
10341 	/* verify map is datasec */
10342 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10343 	if (!btf_is_datasec(datasec_type)) {
10344 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10345 			bpf_map__name(map));
10346 		return -EINVAL;
10347 	}
10348 
10349 	/* verify datasec has at least one var */
10350 	vlen = btf_vlen(datasec_type);
10351 	if (vlen == 0) {
10352 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10353 			bpf_map__name(map));
10354 		return -EINVAL;
10355 	}
10356 
10357 	/* verify last var in the datasec is an array */
10358 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10359 	var_type = btf_type_by_id(btf, var->type);
10360 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10361 	if (!btf_is_array(array_type)) {
10362 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10363 			bpf_map__name(map));
10364 		return -EINVAL;
10365 	}
10366 
10367 	/* verify request size aligns with array */
10368 	array = btf_array(array_type);
10369 	element_sz = btf__resolve_size(btf, array->type);
10370 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10371 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10372 			bpf_map__name(map), element_sz, size);
10373 		return -EINVAL;
10374 	}
10375 
10376 	/* create a new array based on the existing array, but with new length */
10377 	nr_elements = (size - var->offset) / element_sz;
10378 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10379 	if (new_array_id < 0)
10380 		return new_array_id;
10381 
10382 	/* adding a new btf type invalidates existing pointers to btf objects,
10383 	 * so refresh pointers before proceeding
10384 	 */
10385 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10386 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10387 	var_type = btf_type_by_id(btf, var->type);
10388 
10389 	/* finally update btf info */
10390 	datasec_type->size = size;
10391 	var->size = size - var->offset;
10392 	var_type->type = new_array_id;
10393 
10394 	return 0;
10395 }
10396 
bpf_map__set_value_size(struct bpf_map * map,__u32 size)10397 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10398 {
10399 	if (map_is_created(map))
10400 		return libbpf_err(-EBUSY);
10401 
10402 	if (map->mmaped) {
10403 		size_t mmap_old_sz, mmap_new_sz;
10404 		int err;
10405 
10406 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10407 			return libbpf_err(-EOPNOTSUPP);
10408 
10409 		mmap_old_sz = bpf_map_mmap_sz(map);
10410 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10411 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10412 		if (err) {
10413 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10414 				bpf_map__name(map), errstr(err));
10415 			return libbpf_err(err);
10416 		}
10417 		err = map_btf_datasec_resize(map, size);
10418 		if (err && err != -ENOENT) {
10419 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10420 				bpf_map__name(map), errstr(err));
10421 			map->btf_value_type_id = 0;
10422 			map->btf_key_type_id = 0;
10423 		}
10424 	}
10425 
10426 	map->def.value_size = size;
10427 	return 0;
10428 }
10429 
bpf_map__btf_key_type_id(const struct bpf_map * map)10430 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10431 {
10432 	return map ? map->btf_key_type_id : 0;
10433 }
10434 
bpf_map__btf_value_type_id(const struct bpf_map * map)10435 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10436 {
10437 	return map ? map->btf_value_type_id : 0;
10438 }
10439 
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)10440 int bpf_map__set_initial_value(struct bpf_map *map,
10441 			       const void *data, size_t size)
10442 {
10443 	size_t actual_sz;
10444 
10445 	if (map_is_created(map))
10446 		return libbpf_err(-EBUSY);
10447 
10448 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10449 		return libbpf_err(-EINVAL);
10450 
10451 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10452 		actual_sz = map->obj->arena_data_sz;
10453 	else
10454 		actual_sz = map->def.value_size;
10455 	if (size != actual_sz)
10456 		return libbpf_err(-EINVAL);
10457 
10458 	memcpy(map->mmaped, data, size);
10459 	return 0;
10460 }
10461 
bpf_map__initial_value(const struct bpf_map * map,size_t * psize)10462 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10463 {
10464 	if (bpf_map__is_struct_ops(map)) {
10465 		if (psize)
10466 			*psize = map->def.value_size;
10467 		return map->st_ops->data;
10468 	}
10469 
10470 	if (!map->mmaped)
10471 		return NULL;
10472 
10473 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10474 		*psize = map->obj->arena_data_sz;
10475 	else
10476 		*psize = map->def.value_size;
10477 
10478 	return map->mmaped;
10479 }
10480 
bpf_map__is_internal(const struct bpf_map * map)10481 bool bpf_map__is_internal(const struct bpf_map *map)
10482 {
10483 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10484 }
10485 
bpf_map__ifindex(const struct bpf_map * map)10486 __u32 bpf_map__ifindex(const struct bpf_map *map)
10487 {
10488 	return map->map_ifindex;
10489 }
10490 
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)10491 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10492 {
10493 	if (map_is_created(map))
10494 		return libbpf_err(-EBUSY);
10495 	map->map_ifindex = ifindex;
10496 	return 0;
10497 }
10498 
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)10499 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10500 {
10501 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10502 		pr_warn("error: unsupported map type\n");
10503 		return libbpf_err(-EINVAL);
10504 	}
10505 	if (map->inner_map_fd != -1) {
10506 		pr_warn("error: inner_map_fd already specified\n");
10507 		return libbpf_err(-EINVAL);
10508 	}
10509 	if (map->inner_map) {
10510 		bpf_map__destroy(map->inner_map);
10511 		zfree(&map->inner_map);
10512 	}
10513 	map->inner_map_fd = fd;
10514 	return 0;
10515 }
10516 
10517 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)10518 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10519 {
10520 	ssize_t idx;
10521 	struct bpf_map *s, *e;
10522 
10523 	if (!obj || !obj->maps)
10524 		return errno = EINVAL, NULL;
10525 
10526 	s = obj->maps;
10527 	e = obj->maps + obj->nr_maps;
10528 
10529 	if ((m < s) || (m >= e)) {
10530 		pr_warn("error in %s: map handler doesn't belong to object\n",
10531 			 __func__);
10532 		return errno = EINVAL, NULL;
10533 	}
10534 
10535 	idx = (m - obj->maps) + i;
10536 	if (idx >= obj->nr_maps || idx < 0)
10537 		return NULL;
10538 	return &obj->maps[idx];
10539 }
10540 
10541 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)10542 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10543 {
10544 	if (prev == NULL && obj != NULL)
10545 		return obj->maps;
10546 
10547 	return __bpf_map__iter(prev, obj, 1);
10548 }
10549 
10550 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)10551 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10552 {
10553 	if (next == NULL && obj != NULL) {
10554 		if (!obj->nr_maps)
10555 			return NULL;
10556 		return obj->maps + obj->nr_maps - 1;
10557 	}
10558 
10559 	return __bpf_map__iter(next, obj, -1);
10560 }
10561 
10562 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)10563 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10564 {
10565 	struct bpf_map *pos;
10566 
10567 	bpf_object__for_each_map(pos, obj) {
10568 		/* if it's a special internal map name (which always starts
10569 		 * with dot) then check if that special name matches the
10570 		 * real map name (ELF section name)
10571 		 */
10572 		if (name[0] == '.') {
10573 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10574 				return pos;
10575 			continue;
10576 		}
10577 		/* otherwise map name has to be an exact match */
10578 		if (map_uses_real_name(pos)) {
10579 			if (strcmp(pos->real_name, name) == 0)
10580 				return pos;
10581 			continue;
10582 		}
10583 		if (strcmp(pos->name, name) == 0)
10584 			return pos;
10585 	}
10586 	return errno = ENOENT, NULL;
10587 }
10588 
10589 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)10590 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10591 {
10592 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10593 }
10594 
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)10595 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10596 			   size_t value_sz, bool check_value_sz)
10597 {
10598 	if (!map_is_created(map)) /* map is not yet created */
10599 		return -ENOENT;
10600 
10601 	if (map->def.key_size != key_sz) {
10602 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10603 			map->name, key_sz, map->def.key_size);
10604 		return -EINVAL;
10605 	}
10606 
10607 	if (map->fd < 0) {
10608 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10609 		return -EINVAL;
10610 	}
10611 
10612 	if (!check_value_sz)
10613 		return 0;
10614 
10615 	switch (map->def.type) {
10616 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10617 	case BPF_MAP_TYPE_PERCPU_HASH:
10618 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10619 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10620 		int num_cpu = libbpf_num_possible_cpus();
10621 		size_t elem_sz = roundup(map->def.value_size, 8);
10622 
10623 		if (value_sz != num_cpu * elem_sz) {
10624 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10625 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10626 			return -EINVAL;
10627 		}
10628 		break;
10629 	}
10630 	default:
10631 		if (map->def.value_size != value_sz) {
10632 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10633 				map->name, value_sz, map->def.value_size);
10634 			return -EINVAL;
10635 		}
10636 		break;
10637 	}
10638 	return 0;
10639 }
10640 
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)10641 int bpf_map__lookup_elem(const struct bpf_map *map,
10642 			 const void *key, size_t key_sz,
10643 			 void *value, size_t value_sz, __u64 flags)
10644 {
10645 	int err;
10646 
10647 	err = validate_map_op(map, key_sz, value_sz, true);
10648 	if (err)
10649 		return libbpf_err(err);
10650 
10651 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10652 }
10653 
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)10654 int bpf_map__update_elem(const struct bpf_map *map,
10655 			 const void *key, size_t key_sz,
10656 			 const void *value, size_t value_sz, __u64 flags)
10657 {
10658 	int err;
10659 
10660 	err = validate_map_op(map, key_sz, value_sz, true);
10661 	if (err)
10662 		return libbpf_err(err);
10663 
10664 	return bpf_map_update_elem(map->fd, key, value, flags);
10665 }
10666 
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)10667 int bpf_map__delete_elem(const struct bpf_map *map,
10668 			 const void *key, size_t key_sz, __u64 flags)
10669 {
10670 	int err;
10671 
10672 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10673 	if (err)
10674 		return libbpf_err(err);
10675 
10676 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10677 }
10678 
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)10679 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10680 				    const void *key, size_t key_sz,
10681 				    void *value, size_t value_sz, __u64 flags)
10682 {
10683 	int err;
10684 
10685 	err = validate_map_op(map, key_sz, value_sz, true);
10686 	if (err)
10687 		return libbpf_err(err);
10688 
10689 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10690 }
10691 
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)10692 int bpf_map__get_next_key(const struct bpf_map *map,
10693 			  const void *cur_key, void *next_key, size_t key_sz)
10694 {
10695 	int err;
10696 
10697 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10698 	if (err)
10699 		return libbpf_err(err);
10700 
10701 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10702 }
10703 
libbpf_get_error(const void * ptr)10704 long libbpf_get_error(const void *ptr)
10705 {
10706 	if (!IS_ERR_OR_NULL(ptr))
10707 		return 0;
10708 
10709 	if (IS_ERR(ptr))
10710 		errno = -PTR_ERR(ptr);
10711 
10712 	/* If ptr == NULL, then errno should be already set by the failing
10713 	 * API, because libbpf never returns NULL on success and it now always
10714 	 * sets errno on error. So no extra errno handling for ptr == NULL
10715 	 * case.
10716 	 */
10717 	return -errno;
10718 }
10719 
10720 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)10721 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10722 {
10723 	int ret;
10724 	int prog_fd = bpf_program__fd(prog);
10725 
10726 	if (prog_fd < 0) {
10727 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10728 			prog->name);
10729 		return libbpf_err(-EINVAL);
10730 	}
10731 
10732 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10733 	return libbpf_err_errno(ret);
10734 }
10735 
10736 /* Release "ownership" of underlying BPF resource (typically, BPF program
10737  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10738  * link, when destructed through bpf_link__destroy() call won't attempt to
10739  * detach/unregisted that BPF resource. This is useful in situations where,
10740  * say, attached BPF program has to outlive userspace program that attached it
10741  * in the system. Depending on type of BPF program, though, there might be
10742  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10743  * exit of userspace program doesn't trigger automatic detachment and clean up
10744  * inside the kernel.
10745  */
bpf_link__disconnect(struct bpf_link * link)10746 void bpf_link__disconnect(struct bpf_link *link)
10747 {
10748 	link->disconnected = true;
10749 }
10750 
bpf_link__destroy(struct bpf_link * link)10751 int bpf_link__destroy(struct bpf_link *link)
10752 {
10753 	int err = 0;
10754 
10755 	if (IS_ERR_OR_NULL(link))
10756 		return 0;
10757 
10758 	if (!link->disconnected && link->detach)
10759 		err = link->detach(link);
10760 	if (link->pin_path)
10761 		free(link->pin_path);
10762 	if (link->dealloc)
10763 		link->dealloc(link);
10764 	else
10765 		free(link);
10766 
10767 	return libbpf_err(err);
10768 }
10769 
bpf_link__fd(const struct bpf_link * link)10770 int bpf_link__fd(const struct bpf_link *link)
10771 {
10772 	return link->fd;
10773 }
10774 
bpf_link__pin_path(const struct bpf_link * link)10775 const char *bpf_link__pin_path(const struct bpf_link *link)
10776 {
10777 	return link->pin_path;
10778 }
10779 
bpf_link__detach_fd(struct bpf_link * link)10780 static int bpf_link__detach_fd(struct bpf_link *link)
10781 {
10782 	return libbpf_err_errno(close(link->fd));
10783 }
10784 
bpf_link__open(const char * path)10785 struct bpf_link *bpf_link__open(const char *path)
10786 {
10787 	struct bpf_link *link;
10788 	int fd;
10789 
10790 	fd = bpf_obj_get(path);
10791 	if (fd < 0) {
10792 		fd = -errno;
10793 		pr_warn("failed to open link at %s: %d\n", path, fd);
10794 		return libbpf_err_ptr(fd);
10795 	}
10796 
10797 	link = calloc(1, sizeof(*link));
10798 	if (!link) {
10799 		close(fd);
10800 		return libbpf_err_ptr(-ENOMEM);
10801 	}
10802 	link->detach = &bpf_link__detach_fd;
10803 	link->fd = fd;
10804 
10805 	link->pin_path = strdup(path);
10806 	if (!link->pin_path) {
10807 		bpf_link__destroy(link);
10808 		return libbpf_err_ptr(-ENOMEM);
10809 	}
10810 
10811 	return link;
10812 }
10813 
bpf_link__detach(struct bpf_link * link)10814 int bpf_link__detach(struct bpf_link *link)
10815 {
10816 	return bpf_link_detach(link->fd) ? -errno : 0;
10817 }
10818 
bpf_link__pin(struct bpf_link * link,const char * path)10819 int bpf_link__pin(struct bpf_link *link, const char *path)
10820 {
10821 	int err;
10822 
10823 	if (link->pin_path)
10824 		return libbpf_err(-EBUSY);
10825 	err = make_parent_dir(path);
10826 	if (err)
10827 		return libbpf_err(err);
10828 	err = check_path(path);
10829 	if (err)
10830 		return libbpf_err(err);
10831 
10832 	link->pin_path = strdup(path);
10833 	if (!link->pin_path)
10834 		return libbpf_err(-ENOMEM);
10835 
10836 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10837 		err = -errno;
10838 		zfree(&link->pin_path);
10839 		return libbpf_err(err);
10840 	}
10841 
10842 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10843 	return 0;
10844 }
10845 
bpf_link__unpin(struct bpf_link * link)10846 int bpf_link__unpin(struct bpf_link *link)
10847 {
10848 	int err;
10849 
10850 	if (!link->pin_path)
10851 		return libbpf_err(-EINVAL);
10852 
10853 	err = unlink(link->pin_path);
10854 	if (err != 0)
10855 		return -errno;
10856 
10857 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10858 	zfree(&link->pin_path);
10859 	return 0;
10860 }
10861 
10862 struct bpf_link_perf {
10863 	struct bpf_link link;
10864 	int perf_event_fd;
10865 	/* legacy kprobe support: keep track of probe identifier and type */
10866 	char *legacy_probe_name;
10867 	bool legacy_is_kprobe;
10868 	bool legacy_is_retprobe;
10869 };
10870 
10871 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10872 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10873 
bpf_link_perf_detach(struct bpf_link * link)10874 static int bpf_link_perf_detach(struct bpf_link *link)
10875 {
10876 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10877 	int err = 0;
10878 
10879 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10880 		err = -errno;
10881 
10882 	if (perf_link->perf_event_fd != link->fd)
10883 		close(perf_link->perf_event_fd);
10884 	close(link->fd);
10885 
10886 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10887 	if (perf_link->legacy_probe_name) {
10888 		if (perf_link->legacy_is_kprobe) {
10889 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10890 							 perf_link->legacy_is_retprobe);
10891 		} else {
10892 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10893 							 perf_link->legacy_is_retprobe);
10894 		}
10895 	}
10896 
10897 	return err;
10898 }
10899 
bpf_link_perf_dealloc(struct bpf_link * link)10900 static void bpf_link_perf_dealloc(struct bpf_link *link)
10901 {
10902 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10903 
10904 	free(perf_link->legacy_probe_name);
10905 	free(perf_link);
10906 }
10907 
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10908 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10909 						     const struct bpf_perf_event_opts *opts)
10910 {
10911 	struct bpf_link_perf *link;
10912 	int prog_fd, link_fd = -1, err;
10913 	bool force_ioctl_attach;
10914 
10915 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10916 		return libbpf_err_ptr(-EINVAL);
10917 
10918 	if (pfd < 0) {
10919 		pr_warn("prog '%s': invalid perf event FD %d\n",
10920 			prog->name, pfd);
10921 		return libbpf_err_ptr(-EINVAL);
10922 	}
10923 	prog_fd = bpf_program__fd(prog);
10924 	if (prog_fd < 0) {
10925 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10926 			prog->name);
10927 		return libbpf_err_ptr(-EINVAL);
10928 	}
10929 
10930 	link = calloc(1, sizeof(*link));
10931 	if (!link)
10932 		return libbpf_err_ptr(-ENOMEM);
10933 	link->link.detach = &bpf_link_perf_detach;
10934 	link->link.dealloc = &bpf_link_perf_dealloc;
10935 	link->perf_event_fd = pfd;
10936 
10937 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10938 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10939 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10940 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10941 
10942 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10943 		if (link_fd < 0) {
10944 			err = -errno;
10945 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
10946 				prog->name, pfd, errstr(err));
10947 			goto err_out;
10948 		}
10949 		link->link.fd = link_fd;
10950 	} else {
10951 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10952 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10953 			err = -EOPNOTSUPP;
10954 			goto err_out;
10955 		}
10956 
10957 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10958 			err = -errno;
10959 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10960 				prog->name, pfd, errstr(err));
10961 			if (err == -EPROTO)
10962 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10963 					prog->name, pfd);
10964 			goto err_out;
10965 		}
10966 		link->link.fd = pfd;
10967 	}
10968 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10969 		err = -errno;
10970 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10971 			prog->name, pfd, errstr(err));
10972 		goto err_out;
10973 	}
10974 
10975 	return &link->link;
10976 err_out:
10977 	if (link_fd >= 0)
10978 		close(link_fd);
10979 	free(link);
10980 	return libbpf_err_ptr(err);
10981 }
10982 
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10983 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10984 {
10985 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10986 }
10987 
10988 /*
10989  * this function is expected to parse integer in the range of [0, 2^31-1] from
10990  * given file using scanf format string fmt. If actual parsed value is
10991  * negative, the result might be indistinguishable from error
10992  */
parse_uint_from_file(const char * file,const char * fmt)10993 static int parse_uint_from_file(const char *file, const char *fmt)
10994 {
10995 	int err, ret;
10996 	FILE *f;
10997 
10998 	f = fopen(file, "re");
10999 	if (!f) {
11000 		err = -errno;
11001 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11002 		return err;
11003 	}
11004 	err = fscanf(f, fmt, &ret);
11005 	if (err != 1) {
11006 		err = err == EOF ? -EIO : -errno;
11007 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11008 		fclose(f);
11009 		return err;
11010 	}
11011 	fclose(f);
11012 	return ret;
11013 }
11014 
determine_kprobe_perf_type(void)11015 static int determine_kprobe_perf_type(void)
11016 {
11017 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11018 
11019 	return parse_uint_from_file(file, "%d\n");
11020 }
11021 
determine_uprobe_perf_type(void)11022 static int determine_uprobe_perf_type(void)
11023 {
11024 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11025 
11026 	return parse_uint_from_file(file, "%d\n");
11027 }
11028 
determine_kprobe_retprobe_bit(void)11029 static int determine_kprobe_retprobe_bit(void)
11030 {
11031 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11032 
11033 	return parse_uint_from_file(file, "config:%d\n");
11034 }
11035 
determine_uprobe_retprobe_bit(void)11036 static int determine_uprobe_retprobe_bit(void)
11037 {
11038 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11039 
11040 	return parse_uint_from_file(file, "config:%d\n");
11041 }
11042 
11043 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11044 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11045 
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)11046 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11047 				 uint64_t offset, int pid, size_t ref_ctr_off)
11048 {
11049 	const size_t attr_sz = sizeof(struct perf_event_attr);
11050 	struct perf_event_attr attr;
11051 	int type, pfd;
11052 
11053 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11054 		return -EINVAL;
11055 
11056 	memset(&attr, 0, attr_sz);
11057 
11058 	type = uprobe ? determine_uprobe_perf_type()
11059 		      : determine_kprobe_perf_type();
11060 	if (type < 0) {
11061 		pr_warn("failed to determine %s perf type: %s\n",
11062 			uprobe ? "uprobe" : "kprobe",
11063 			errstr(type));
11064 		return type;
11065 	}
11066 	if (retprobe) {
11067 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11068 				 : determine_kprobe_retprobe_bit();
11069 
11070 		if (bit < 0) {
11071 			pr_warn("failed to determine %s retprobe bit: %s\n",
11072 				uprobe ? "uprobe" : "kprobe",
11073 				errstr(bit));
11074 			return bit;
11075 		}
11076 		attr.config |= 1 << bit;
11077 	}
11078 	attr.size = attr_sz;
11079 	attr.type = type;
11080 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11081 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11082 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11083 
11084 	/* pid filter is meaningful only for uprobes */
11085 	pfd = syscall(__NR_perf_event_open, &attr,
11086 		      pid < 0 ? -1 : pid /* pid */,
11087 		      pid == -1 ? 0 : -1 /* cpu */,
11088 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11089 	return pfd >= 0 ? pfd : -errno;
11090 }
11091 
append_to_file(const char * file,const char * fmt,...)11092 static int append_to_file(const char *file, const char *fmt, ...)
11093 {
11094 	int fd, n, err = 0;
11095 	va_list ap;
11096 	char buf[1024];
11097 
11098 	va_start(ap, fmt);
11099 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11100 	va_end(ap);
11101 
11102 	if (n < 0 || n >= sizeof(buf))
11103 		return -EINVAL;
11104 
11105 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11106 	if (fd < 0)
11107 		return -errno;
11108 
11109 	if (write(fd, buf, n) < 0)
11110 		err = -errno;
11111 
11112 	close(fd);
11113 	return err;
11114 }
11115 
11116 #define DEBUGFS "/sys/kernel/debug/tracing"
11117 #define TRACEFS "/sys/kernel/tracing"
11118 
use_debugfs(void)11119 static bool use_debugfs(void)
11120 {
11121 	static int has_debugfs = -1;
11122 
11123 	if (has_debugfs < 0)
11124 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11125 
11126 	return has_debugfs == 1;
11127 }
11128 
tracefs_path(void)11129 static const char *tracefs_path(void)
11130 {
11131 	return use_debugfs() ? DEBUGFS : TRACEFS;
11132 }
11133 
tracefs_kprobe_events(void)11134 static const char *tracefs_kprobe_events(void)
11135 {
11136 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11137 }
11138 
tracefs_uprobe_events(void)11139 static const char *tracefs_uprobe_events(void)
11140 {
11141 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11142 }
11143 
tracefs_available_filter_functions(void)11144 static const char *tracefs_available_filter_functions(void)
11145 {
11146 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11147 			     : TRACEFS"/available_filter_functions";
11148 }
11149 
tracefs_available_filter_functions_addrs(void)11150 static const char *tracefs_available_filter_functions_addrs(void)
11151 {
11152 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11153 			     : TRACEFS"/available_filter_functions_addrs";
11154 }
11155 
gen_probe_legacy_event_name(char * buf,size_t buf_sz,const char * name,size_t offset)11156 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11157 					const char *name, size_t offset)
11158 {
11159 	static int index = 0;
11160 	int i;
11161 
11162 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11163 		 __sync_fetch_and_add(&index, 1), name, offset);
11164 
11165 	/* sanitize name in the probe name */
11166 	for (i = 0; buf[i]; i++) {
11167 		if (!isalnum(buf[i]))
11168 			buf[i] = '_';
11169 	}
11170 }
11171 
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)11172 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11173 				   const char *kfunc_name, size_t offset)
11174 {
11175 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11176 			      retprobe ? 'r' : 'p',
11177 			      retprobe ? "kretprobes" : "kprobes",
11178 			      probe_name, kfunc_name, offset);
11179 }
11180 
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)11181 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11182 {
11183 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11184 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11185 }
11186 
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)11187 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11188 {
11189 	char file[256];
11190 
11191 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11192 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11193 
11194 	return parse_uint_from_file(file, "%d\n");
11195 }
11196 
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)11197 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11198 					 const char *kfunc_name, size_t offset, int pid)
11199 {
11200 	const size_t attr_sz = sizeof(struct perf_event_attr);
11201 	struct perf_event_attr attr;
11202 	int type, pfd, err;
11203 
11204 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11205 	if (err < 0) {
11206 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11207 			kfunc_name, offset,
11208 			errstr(err));
11209 		return err;
11210 	}
11211 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11212 	if (type < 0) {
11213 		err = type;
11214 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11215 			kfunc_name, offset,
11216 			errstr(err));
11217 		goto err_clean_legacy;
11218 	}
11219 
11220 	memset(&attr, 0, attr_sz);
11221 	attr.size = attr_sz;
11222 	attr.config = type;
11223 	attr.type = PERF_TYPE_TRACEPOINT;
11224 
11225 	pfd = syscall(__NR_perf_event_open, &attr,
11226 		      pid < 0 ? -1 : pid, /* pid */
11227 		      pid == -1 ? 0 : -1, /* cpu */
11228 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11229 	if (pfd < 0) {
11230 		err = -errno;
11231 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11232 			errstr(err));
11233 		goto err_clean_legacy;
11234 	}
11235 	return pfd;
11236 
11237 err_clean_legacy:
11238 	/* Clear the newly added legacy kprobe_event */
11239 	remove_kprobe_event_legacy(probe_name, retprobe);
11240 	return err;
11241 }
11242 
arch_specific_syscall_pfx(void)11243 static const char *arch_specific_syscall_pfx(void)
11244 {
11245 #if defined(__x86_64__)
11246 	return "x64";
11247 #elif defined(__i386__)
11248 	return "ia32";
11249 #elif defined(__s390x__)
11250 	return "s390x";
11251 #elif defined(__s390__)
11252 	return "s390";
11253 #elif defined(__arm__)
11254 	return "arm";
11255 #elif defined(__aarch64__)
11256 	return "arm64";
11257 #elif defined(__mips__)
11258 	return "mips";
11259 #elif defined(__riscv)
11260 	return "riscv";
11261 #elif defined(__powerpc__)
11262 	return "powerpc";
11263 #elif defined(__powerpc64__)
11264 	return "powerpc64";
11265 #else
11266 	return NULL;
11267 #endif
11268 }
11269 
probe_kern_syscall_wrapper(int token_fd)11270 int probe_kern_syscall_wrapper(int token_fd)
11271 {
11272 	char syscall_name[64];
11273 	const char *ksys_pfx;
11274 
11275 	ksys_pfx = arch_specific_syscall_pfx();
11276 	if (!ksys_pfx)
11277 		return 0;
11278 
11279 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11280 
11281 	if (determine_kprobe_perf_type() >= 0) {
11282 		int pfd;
11283 
11284 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11285 		if (pfd >= 0)
11286 			close(pfd);
11287 
11288 		return pfd >= 0 ? 1 : 0;
11289 	} else { /* legacy mode */
11290 		char probe_name[MAX_EVENT_NAME_LEN];
11291 
11292 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11293 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11294 			return 0;
11295 
11296 		(void)remove_kprobe_event_legacy(probe_name, false);
11297 		return 1;
11298 	}
11299 }
11300 
11301 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)11302 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11303 				const char *func_name,
11304 				const struct bpf_kprobe_opts *opts)
11305 {
11306 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11307 	enum probe_attach_mode attach_mode;
11308 	char *legacy_probe = NULL;
11309 	struct bpf_link *link;
11310 	size_t offset;
11311 	bool retprobe, legacy;
11312 	int pfd, err;
11313 
11314 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11315 		return libbpf_err_ptr(-EINVAL);
11316 
11317 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11318 	retprobe = OPTS_GET(opts, retprobe, false);
11319 	offset = OPTS_GET(opts, offset, 0);
11320 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11321 
11322 	legacy = determine_kprobe_perf_type() < 0;
11323 	switch (attach_mode) {
11324 	case PROBE_ATTACH_MODE_LEGACY:
11325 		legacy = true;
11326 		pe_opts.force_ioctl_attach = true;
11327 		break;
11328 	case PROBE_ATTACH_MODE_PERF:
11329 		if (legacy)
11330 			return libbpf_err_ptr(-ENOTSUP);
11331 		pe_opts.force_ioctl_attach = true;
11332 		break;
11333 	case PROBE_ATTACH_MODE_LINK:
11334 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11335 			return libbpf_err_ptr(-ENOTSUP);
11336 		break;
11337 	case PROBE_ATTACH_MODE_DEFAULT:
11338 		break;
11339 	default:
11340 		return libbpf_err_ptr(-EINVAL);
11341 	}
11342 
11343 	if (!legacy) {
11344 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11345 					    func_name, offset,
11346 					    -1 /* pid */, 0 /* ref_ctr_off */);
11347 	} else {
11348 		char probe_name[MAX_EVENT_NAME_LEN];
11349 
11350 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11351 					    func_name, offset);
11352 
11353 		legacy_probe = strdup(probe_name);
11354 		if (!legacy_probe)
11355 			return libbpf_err_ptr(-ENOMEM);
11356 
11357 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11358 						    offset, -1 /* pid */);
11359 	}
11360 	if (pfd < 0) {
11361 		err = -errno;
11362 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11363 			prog->name, retprobe ? "kretprobe" : "kprobe",
11364 			func_name, offset,
11365 			errstr(err));
11366 		goto err_out;
11367 	}
11368 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11369 	err = libbpf_get_error(link);
11370 	if (err) {
11371 		close(pfd);
11372 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11373 			prog->name, retprobe ? "kretprobe" : "kprobe",
11374 			func_name, offset,
11375 			errstr(err));
11376 		goto err_clean_legacy;
11377 	}
11378 	if (legacy) {
11379 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11380 
11381 		perf_link->legacy_probe_name = legacy_probe;
11382 		perf_link->legacy_is_kprobe = true;
11383 		perf_link->legacy_is_retprobe = retprobe;
11384 	}
11385 
11386 	return link;
11387 
11388 err_clean_legacy:
11389 	if (legacy)
11390 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11391 err_out:
11392 	free(legacy_probe);
11393 	return libbpf_err_ptr(err);
11394 }
11395 
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)11396 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11397 					    bool retprobe,
11398 					    const char *func_name)
11399 {
11400 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11401 		.retprobe = retprobe,
11402 	);
11403 
11404 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11405 }
11406 
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)11407 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11408 					      const char *syscall_name,
11409 					      const struct bpf_ksyscall_opts *opts)
11410 {
11411 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11412 	char func_name[128];
11413 
11414 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11415 		return libbpf_err_ptr(-EINVAL);
11416 
11417 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11418 		/* arch_specific_syscall_pfx() should never return NULL here
11419 		 * because it is guarded by kernel_supports(). However, since
11420 		 * compiler does not know that we have an explicit conditional
11421 		 * as well.
11422 		 */
11423 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11424 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11425 	} else {
11426 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11427 	}
11428 
11429 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11430 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11431 
11432 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11433 }
11434 
11435 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)11436 bool glob_match(const char *str, const char *pat)
11437 {
11438 	while (*str && *pat && *pat != '*') {
11439 		if (*pat == '?') {      /* Matches any single character */
11440 			str++;
11441 			pat++;
11442 			continue;
11443 		}
11444 		if (*str != *pat)
11445 			return false;
11446 		str++;
11447 		pat++;
11448 	}
11449 	/* Check wild card */
11450 	if (*pat == '*') {
11451 		while (*pat == '*')
11452 			pat++;
11453 		if (!*pat) /* Tail wild card matches all */
11454 			return true;
11455 		while (*str)
11456 			if (glob_match(str++, pat))
11457 				return true;
11458 	}
11459 	return !*str && !*pat;
11460 }
11461 
11462 struct kprobe_multi_resolve {
11463 	const char *pattern;
11464 	unsigned long *addrs;
11465 	size_t cap;
11466 	size_t cnt;
11467 };
11468 
11469 struct avail_kallsyms_data {
11470 	char **syms;
11471 	size_t cnt;
11472 	struct kprobe_multi_resolve *res;
11473 };
11474 
avail_func_cmp(const void * a,const void * b)11475 static int avail_func_cmp(const void *a, const void *b)
11476 {
11477 	return strcmp(*(const char **)a, *(const char **)b);
11478 }
11479 
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)11480 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11481 			     const char *sym_name, void *ctx)
11482 {
11483 	struct avail_kallsyms_data *data = ctx;
11484 	struct kprobe_multi_resolve *res = data->res;
11485 	int err;
11486 
11487 	if (!glob_match(sym_name, res->pattern))
11488 		return 0;
11489 
11490 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11491 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11492 		 * function names reported in available_filter_functions, but
11493 		 * don't do so for kallsyms. While this is clearly a kernel
11494 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11495 		 * make multi-kprobe usability a bit better: if no match is
11496 		 * found, we will strip .llvm. suffix and try one more time.
11497 		 *
11498 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11499 		 */
11500 		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11501 
11502 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11503 			return 0;
11504 
11505 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11506 		 * coercion differences and get proper `const char **` pointer
11507 		 * which avail_func_cmp() expects
11508 		 */
11509 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11510 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11511 			return 0;
11512 	}
11513 
11514 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11515 	if (err)
11516 		return err;
11517 
11518 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11519 	return 0;
11520 }
11521 
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)11522 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11523 {
11524 	const char *available_functions_file = tracefs_available_filter_functions();
11525 	struct avail_kallsyms_data data;
11526 	char sym_name[500];
11527 	FILE *f;
11528 	int err = 0, ret, i;
11529 	char **syms = NULL;
11530 	size_t cap = 0, cnt = 0;
11531 
11532 	f = fopen(available_functions_file, "re");
11533 	if (!f) {
11534 		err = -errno;
11535 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11536 		return err;
11537 	}
11538 
11539 	while (true) {
11540 		char *name;
11541 
11542 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11543 		if (ret == EOF && feof(f))
11544 			break;
11545 
11546 		if (ret != 1) {
11547 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11548 			err = -EINVAL;
11549 			goto cleanup;
11550 		}
11551 
11552 		if (!glob_match(sym_name, res->pattern))
11553 			continue;
11554 
11555 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11556 		if (err)
11557 			goto cleanup;
11558 
11559 		name = strdup(sym_name);
11560 		if (!name) {
11561 			err = -errno;
11562 			goto cleanup;
11563 		}
11564 
11565 		syms[cnt++] = name;
11566 	}
11567 
11568 	/* no entries found, bail out */
11569 	if (cnt == 0) {
11570 		err = -ENOENT;
11571 		goto cleanup;
11572 	}
11573 
11574 	/* sort available functions */
11575 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11576 
11577 	data.syms = syms;
11578 	data.res = res;
11579 	data.cnt = cnt;
11580 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11581 
11582 	if (res->cnt == 0)
11583 		err = -ENOENT;
11584 
11585 cleanup:
11586 	for (i = 0; i < cnt; i++)
11587 		free((char *)syms[i]);
11588 	free(syms);
11589 
11590 	fclose(f);
11591 	return err;
11592 }
11593 
has_available_filter_functions_addrs(void)11594 static bool has_available_filter_functions_addrs(void)
11595 {
11596 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11597 }
11598 
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)11599 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11600 {
11601 	const char *available_path = tracefs_available_filter_functions_addrs();
11602 	char sym_name[500];
11603 	FILE *f;
11604 	int ret, err = 0;
11605 	unsigned long long sym_addr;
11606 
11607 	f = fopen(available_path, "re");
11608 	if (!f) {
11609 		err = -errno;
11610 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11611 		return err;
11612 	}
11613 
11614 	while (true) {
11615 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11616 		if (ret == EOF && feof(f))
11617 			break;
11618 
11619 		if (ret != 2) {
11620 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11621 				ret);
11622 			err = -EINVAL;
11623 			goto cleanup;
11624 		}
11625 
11626 		if (!glob_match(sym_name, res->pattern))
11627 			continue;
11628 
11629 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11630 					sizeof(*res->addrs), res->cnt + 1);
11631 		if (err)
11632 			goto cleanup;
11633 
11634 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11635 	}
11636 
11637 	if (res->cnt == 0)
11638 		err = -ENOENT;
11639 
11640 cleanup:
11641 	fclose(f);
11642 	return err;
11643 }
11644 
11645 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)11646 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11647 				      const char *pattern,
11648 				      const struct bpf_kprobe_multi_opts *opts)
11649 {
11650 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11651 	struct kprobe_multi_resolve res = {
11652 		.pattern = pattern,
11653 	};
11654 	enum bpf_attach_type attach_type;
11655 	struct bpf_link *link = NULL;
11656 	const unsigned long *addrs;
11657 	int err, link_fd, prog_fd;
11658 	bool retprobe, session, unique_match;
11659 	const __u64 *cookies;
11660 	const char **syms;
11661 	size_t cnt;
11662 
11663 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11664 		return libbpf_err_ptr(-EINVAL);
11665 
11666 	prog_fd = bpf_program__fd(prog);
11667 	if (prog_fd < 0) {
11668 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11669 			prog->name);
11670 		return libbpf_err_ptr(-EINVAL);
11671 	}
11672 
11673 	syms    = OPTS_GET(opts, syms, false);
11674 	addrs   = OPTS_GET(opts, addrs, false);
11675 	cnt     = OPTS_GET(opts, cnt, false);
11676 	cookies = OPTS_GET(opts, cookies, false);
11677 	unique_match = OPTS_GET(opts, unique_match, false);
11678 
11679 	if (!pattern && !addrs && !syms)
11680 		return libbpf_err_ptr(-EINVAL);
11681 	if (pattern && (addrs || syms || cookies || cnt))
11682 		return libbpf_err_ptr(-EINVAL);
11683 	if (!pattern && !cnt)
11684 		return libbpf_err_ptr(-EINVAL);
11685 	if (!pattern && unique_match)
11686 		return libbpf_err_ptr(-EINVAL);
11687 	if (addrs && syms)
11688 		return libbpf_err_ptr(-EINVAL);
11689 
11690 	if (pattern) {
11691 		if (has_available_filter_functions_addrs())
11692 			err = libbpf_available_kprobes_parse(&res);
11693 		else
11694 			err = libbpf_available_kallsyms_parse(&res);
11695 		if (err)
11696 			goto error;
11697 
11698 		if (unique_match && res.cnt != 1) {
11699 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11700 				prog->name, pattern, res.cnt);
11701 			err = -EINVAL;
11702 			goto error;
11703 		}
11704 
11705 		addrs = res.addrs;
11706 		cnt = res.cnt;
11707 	}
11708 
11709 	retprobe = OPTS_GET(opts, retprobe, false);
11710 	session  = OPTS_GET(opts, session, false);
11711 
11712 	if (retprobe && session)
11713 		return libbpf_err_ptr(-EINVAL);
11714 
11715 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11716 
11717 	lopts.kprobe_multi.syms = syms;
11718 	lopts.kprobe_multi.addrs = addrs;
11719 	lopts.kprobe_multi.cookies = cookies;
11720 	lopts.kprobe_multi.cnt = cnt;
11721 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11722 
11723 	link = calloc(1, sizeof(*link));
11724 	if (!link) {
11725 		err = -ENOMEM;
11726 		goto error;
11727 	}
11728 	link->detach = &bpf_link__detach_fd;
11729 
11730 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11731 	if (link_fd < 0) {
11732 		err = -errno;
11733 		pr_warn("prog '%s': failed to attach: %s\n",
11734 			prog->name, errstr(err));
11735 		goto error;
11736 	}
11737 	link->fd = link_fd;
11738 	free(res.addrs);
11739 	return link;
11740 
11741 error:
11742 	free(link);
11743 	free(res.addrs);
11744 	return libbpf_err_ptr(err);
11745 }
11746 
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11747 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11748 {
11749 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11750 	unsigned long offset = 0;
11751 	const char *func_name;
11752 	char *func;
11753 	int n;
11754 
11755 	*link = NULL;
11756 
11757 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11758 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11759 		return 0;
11760 
11761 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11762 	if (opts.retprobe)
11763 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11764 	else
11765 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11766 
11767 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11768 	if (n < 1) {
11769 		pr_warn("kprobe name is invalid: %s\n", func_name);
11770 		return -EINVAL;
11771 	}
11772 	if (opts.retprobe && offset != 0) {
11773 		free(func);
11774 		pr_warn("kretprobes do not support offset specification\n");
11775 		return -EINVAL;
11776 	}
11777 
11778 	opts.offset = offset;
11779 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11780 	free(func);
11781 	return libbpf_get_error(*link);
11782 }
11783 
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11784 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11785 {
11786 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11787 	const char *syscall_name;
11788 
11789 	*link = NULL;
11790 
11791 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11792 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11793 		return 0;
11794 
11795 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11796 	if (opts.retprobe)
11797 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11798 	else
11799 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11800 
11801 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11802 	return *link ? 0 : -errno;
11803 }
11804 
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11805 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11806 {
11807 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11808 	const char *spec;
11809 	char *pattern;
11810 	int n;
11811 
11812 	*link = NULL;
11813 
11814 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11815 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11816 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11817 		return 0;
11818 
11819 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11820 	if (opts.retprobe)
11821 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11822 	else
11823 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11824 
11825 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11826 	if (n < 1) {
11827 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11828 		return -EINVAL;
11829 	}
11830 
11831 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11832 	free(pattern);
11833 	return libbpf_get_error(*link);
11834 }
11835 
attach_kprobe_session(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11836 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11837 				 struct bpf_link **link)
11838 {
11839 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11840 	const char *spec;
11841 	char *pattern;
11842 	int n;
11843 
11844 	*link = NULL;
11845 
11846 	/* no auto-attach for SEC("kprobe.session") */
11847 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11848 		return 0;
11849 
11850 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11851 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11852 	if (n < 1) {
11853 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11854 		return -EINVAL;
11855 	}
11856 
11857 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11858 	free(pattern);
11859 	return *link ? 0 : -errno;
11860 }
11861 
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11862 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11863 {
11864 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11865 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11866 	int n, ret = -EINVAL;
11867 
11868 	*link = NULL;
11869 
11870 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11871 		   &probe_type, &binary_path, &func_name);
11872 	switch (n) {
11873 	case 1:
11874 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11875 		ret = 0;
11876 		break;
11877 	case 3:
11878 		opts.session = str_has_pfx(probe_type, "uprobe.session");
11879 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11880 
11881 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11882 		ret = libbpf_get_error(*link);
11883 		break;
11884 	default:
11885 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11886 			prog->sec_name);
11887 		break;
11888 	}
11889 	free(probe_type);
11890 	free(binary_path);
11891 	free(func_name);
11892 	return ret;
11893 }
11894 
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)11895 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11896 					  const char *binary_path, size_t offset)
11897 {
11898 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11899 			      retprobe ? 'r' : 'p',
11900 			      retprobe ? "uretprobes" : "uprobes",
11901 			      probe_name, binary_path, offset);
11902 }
11903 
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)11904 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11905 {
11906 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11907 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11908 }
11909 
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)11910 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11911 {
11912 	char file[512];
11913 
11914 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11915 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11916 
11917 	return parse_uint_from_file(file, "%d\n");
11918 }
11919 
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)11920 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11921 					 const char *binary_path, size_t offset, int pid)
11922 {
11923 	const size_t attr_sz = sizeof(struct perf_event_attr);
11924 	struct perf_event_attr attr;
11925 	int type, pfd, err;
11926 
11927 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11928 	if (err < 0) {
11929 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
11930 			binary_path, (size_t)offset, errstr(err));
11931 		return err;
11932 	}
11933 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11934 	if (type < 0) {
11935 		err = type;
11936 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
11937 			binary_path, offset, errstr(err));
11938 		goto err_clean_legacy;
11939 	}
11940 
11941 	memset(&attr, 0, attr_sz);
11942 	attr.size = attr_sz;
11943 	attr.config = type;
11944 	attr.type = PERF_TYPE_TRACEPOINT;
11945 
11946 	pfd = syscall(__NR_perf_event_open, &attr,
11947 		      pid < 0 ? -1 : pid, /* pid */
11948 		      pid == -1 ? 0 : -1, /* cpu */
11949 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11950 	if (pfd < 0) {
11951 		err = -errno;
11952 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
11953 		goto err_clean_legacy;
11954 	}
11955 	return pfd;
11956 
11957 err_clean_legacy:
11958 	/* Clear the newly added legacy uprobe_event */
11959 	remove_uprobe_event_legacy(probe_name, retprobe);
11960 	return err;
11961 }
11962 
11963 /* Find offset of function name in archive specified by path. Currently
11964  * supported are .zip files that do not compress their contents, as used on
11965  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11966  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11967  * library functions.
11968  *
11969  * An overview of the APK format specifically provided here:
11970  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11971  */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)11972 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11973 					      const char *func_name)
11974 {
11975 	struct zip_archive *archive;
11976 	struct zip_entry entry;
11977 	long ret;
11978 	Elf *elf;
11979 
11980 	archive = zip_archive_open(archive_path);
11981 	if (IS_ERR(archive)) {
11982 		ret = PTR_ERR(archive);
11983 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11984 		return ret;
11985 	}
11986 
11987 	ret = zip_archive_find_entry(archive, file_name, &entry);
11988 	if (ret) {
11989 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11990 			archive_path, ret);
11991 		goto out;
11992 	}
11993 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11994 		 (unsigned long)entry.data_offset);
11995 
11996 	if (entry.compression) {
11997 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11998 			archive_path);
11999 		ret = -LIBBPF_ERRNO__FORMAT;
12000 		goto out;
12001 	}
12002 
12003 	elf = elf_memory((void *)entry.data, entry.data_length);
12004 	if (!elf) {
12005 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12006 			elf_errmsg(-1));
12007 		ret = -LIBBPF_ERRNO__LIBELF;
12008 		goto out;
12009 	}
12010 
12011 	ret = elf_find_func_offset(elf, file_name, func_name);
12012 	if (ret > 0) {
12013 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12014 			 func_name, file_name, archive_path, entry.data_offset, ret,
12015 			 ret + entry.data_offset);
12016 		ret += entry.data_offset;
12017 	}
12018 	elf_end(elf);
12019 
12020 out:
12021 	zip_archive_close(archive);
12022 	return ret;
12023 }
12024 
arch_specific_lib_paths(void)12025 static const char *arch_specific_lib_paths(void)
12026 {
12027 	/*
12028 	 * Based on https://packages.debian.org/sid/libc6.
12029 	 *
12030 	 * Assume that the traced program is built for the same architecture
12031 	 * as libbpf, which should cover the vast majority of cases.
12032 	 */
12033 #if defined(__x86_64__)
12034 	return "/lib/x86_64-linux-gnu";
12035 #elif defined(__i386__)
12036 	return "/lib/i386-linux-gnu";
12037 #elif defined(__s390x__)
12038 	return "/lib/s390x-linux-gnu";
12039 #elif defined(__s390__)
12040 	return "/lib/s390-linux-gnu";
12041 #elif defined(__arm__) && defined(__SOFTFP__)
12042 	return "/lib/arm-linux-gnueabi";
12043 #elif defined(__arm__) && !defined(__SOFTFP__)
12044 	return "/lib/arm-linux-gnueabihf";
12045 #elif defined(__aarch64__)
12046 	return "/lib/aarch64-linux-gnu";
12047 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12048 	return "/lib/mips64el-linux-gnuabi64";
12049 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12050 	return "/lib/mipsel-linux-gnu";
12051 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12052 	return "/lib/powerpc64le-linux-gnu";
12053 #elif defined(__sparc__) && defined(__arch64__)
12054 	return "/lib/sparc64-linux-gnu";
12055 #elif defined(__riscv) && __riscv_xlen == 64
12056 	return "/lib/riscv64-linux-gnu";
12057 #else
12058 	return NULL;
12059 #endif
12060 }
12061 
12062 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)12063 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12064 {
12065 	const char *search_paths[3] = {};
12066 	int i, perm;
12067 
12068 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12069 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12070 		search_paths[1] = "/usr/lib64:/usr/lib";
12071 		search_paths[2] = arch_specific_lib_paths();
12072 		perm = R_OK;
12073 	} else {
12074 		search_paths[0] = getenv("PATH");
12075 		search_paths[1] = "/usr/bin:/usr/sbin";
12076 		perm = R_OK | X_OK;
12077 	}
12078 
12079 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12080 		const char *s;
12081 
12082 		if (!search_paths[i])
12083 			continue;
12084 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12085 			char *next_path;
12086 			int seg_len;
12087 
12088 			if (s[0] == ':')
12089 				s++;
12090 			next_path = strchr(s, ':');
12091 			seg_len = next_path ? next_path - s : strlen(s);
12092 			if (!seg_len)
12093 				continue;
12094 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12095 			/* ensure it has required permissions */
12096 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12097 				continue;
12098 			pr_debug("resolved '%s' to '%s'\n", file, result);
12099 			return 0;
12100 		}
12101 	}
12102 	return -ENOENT;
12103 }
12104 
12105 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)12106 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12107 				 pid_t pid,
12108 				 const char *path,
12109 				 const char *func_pattern,
12110 				 const struct bpf_uprobe_multi_opts *opts)
12111 {
12112 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12113 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12114 	unsigned long *resolved_offsets = NULL;
12115 	enum bpf_attach_type attach_type;
12116 	int err = 0, link_fd, prog_fd;
12117 	struct bpf_link *link = NULL;
12118 	char full_path[PATH_MAX];
12119 	bool retprobe, session;
12120 	const __u64 *cookies;
12121 	const char **syms;
12122 	size_t cnt;
12123 
12124 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12125 		return libbpf_err_ptr(-EINVAL);
12126 
12127 	prog_fd = bpf_program__fd(prog);
12128 	if (prog_fd < 0) {
12129 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12130 			prog->name);
12131 		return libbpf_err_ptr(-EINVAL);
12132 	}
12133 
12134 	syms = OPTS_GET(opts, syms, NULL);
12135 	offsets = OPTS_GET(opts, offsets, NULL);
12136 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12137 	cookies = OPTS_GET(opts, cookies, NULL);
12138 	cnt = OPTS_GET(opts, cnt, 0);
12139 	retprobe = OPTS_GET(opts, retprobe, false);
12140 	session  = OPTS_GET(opts, session, false);
12141 
12142 	/*
12143 	 * User can specify 2 mutually exclusive set of inputs:
12144 	 *
12145 	 * 1) use only path/func_pattern/pid arguments
12146 	 *
12147 	 * 2) use path/pid with allowed combinations of:
12148 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12149 	 *
12150 	 *    - syms and offsets are mutually exclusive
12151 	 *    - ref_ctr_offsets and cookies are optional
12152 	 *
12153 	 * Any other usage results in error.
12154 	 */
12155 
12156 	if (!path)
12157 		return libbpf_err_ptr(-EINVAL);
12158 	if (!func_pattern && cnt == 0)
12159 		return libbpf_err_ptr(-EINVAL);
12160 
12161 	if (func_pattern) {
12162 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12163 			return libbpf_err_ptr(-EINVAL);
12164 	} else {
12165 		if (!!syms == !!offsets)
12166 			return libbpf_err_ptr(-EINVAL);
12167 	}
12168 
12169 	if (retprobe && session)
12170 		return libbpf_err_ptr(-EINVAL);
12171 
12172 	if (func_pattern) {
12173 		if (!strchr(path, '/')) {
12174 			err = resolve_full_path(path, full_path, sizeof(full_path));
12175 			if (err) {
12176 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12177 					prog->name, path, errstr(err));
12178 				return libbpf_err_ptr(err);
12179 			}
12180 			path = full_path;
12181 		}
12182 
12183 		err = elf_resolve_pattern_offsets(path, func_pattern,
12184 						  &resolved_offsets, &cnt);
12185 		if (err < 0)
12186 			return libbpf_err_ptr(err);
12187 		offsets = resolved_offsets;
12188 	} else if (syms) {
12189 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12190 		if (err < 0)
12191 			return libbpf_err_ptr(err);
12192 		offsets = resolved_offsets;
12193 	}
12194 
12195 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12196 
12197 	lopts.uprobe_multi.path = path;
12198 	lopts.uprobe_multi.offsets = offsets;
12199 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12200 	lopts.uprobe_multi.cookies = cookies;
12201 	lopts.uprobe_multi.cnt = cnt;
12202 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12203 
12204 	if (pid == 0)
12205 		pid = getpid();
12206 	if (pid > 0)
12207 		lopts.uprobe_multi.pid = pid;
12208 
12209 	link = calloc(1, sizeof(*link));
12210 	if (!link) {
12211 		err = -ENOMEM;
12212 		goto error;
12213 	}
12214 	link->detach = &bpf_link__detach_fd;
12215 
12216 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12217 	if (link_fd < 0) {
12218 		err = -errno;
12219 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12220 			prog->name, errstr(err));
12221 		goto error;
12222 	}
12223 	link->fd = link_fd;
12224 	free(resolved_offsets);
12225 	return link;
12226 
12227 error:
12228 	free(resolved_offsets);
12229 	free(link);
12230 	return libbpf_err_ptr(err);
12231 }
12232 
12233 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)12234 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12235 				const char *binary_path, size_t func_offset,
12236 				const struct bpf_uprobe_opts *opts)
12237 {
12238 	const char *archive_path = NULL, *archive_sep = NULL;
12239 	char *legacy_probe = NULL;
12240 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12241 	enum probe_attach_mode attach_mode;
12242 	char full_path[PATH_MAX];
12243 	struct bpf_link *link;
12244 	size_t ref_ctr_off;
12245 	int pfd, err;
12246 	bool retprobe, legacy;
12247 	const char *func_name;
12248 
12249 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12250 		return libbpf_err_ptr(-EINVAL);
12251 
12252 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12253 	retprobe = OPTS_GET(opts, retprobe, false);
12254 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12255 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12256 
12257 	if (!binary_path)
12258 		return libbpf_err_ptr(-EINVAL);
12259 
12260 	/* Check if "binary_path" refers to an archive. */
12261 	archive_sep = strstr(binary_path, "!/");
12262 	if (archive_sep) {
12263 		full_path[0] = '\0';
12264 		libbpf_strlcpy(full_path, binary_path,
12265 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12266 		archive_path = full_path;
12267 		binary_path = archive_sep + 2;
12268 	} else if (!strchr(binary_path, '/')) {
12269 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12270 		if (err) {
12271 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12272 				prog->name, binary_path, errstr(err));
12273 			return libbpf_err_ptr(err);
12274 		}
12275 		binary_path = full_path;
12276 	}
12277 	func_name = OPTS_GET(opts, func_name, NULL);
12278 	if (func_name) {
12279 		long sym_off;
12280 
12281 		if (archive_path) {
12282 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12283 								    func_name);
12284 			binary_path = archive_path;
12285 		} else {
12286 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12287 		}
12288 		if (sym_off < 0)
12289 			return libbpf_err_ptr(sym_off);
12290 		func_offset += sym_off;
12291 	}
12292 
12293 	legacy = determine_uprobe_perf_type() < 0;
12294 	switch (attach_mode) {
12295 	case PROBE_ATTACH_MODE_LEGACY:
12296 		legacy = true;
12297 		pe_opts.force_ioctl_attach = true;
12298 		break;
12299 	case PROBE_ATTACH_MODE_PERF:
12300 		if (legacy)
12301 			return libbpf_err_ptr(-ENOTSUP);
12302 		pe_opts.force_ioctl_attach = true;
12303 		break;
12304 	case PROBE_ATTACH_MODE_LINK:
12305 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12306 			return libbpf_err_ptr(-ENOTSUP);
12307 		break;
12308 	case PROBE_ATTACH_MODE_DEFAULT:
12309 		break;
12310 	default:
12311 		return libbpf_err_ptr(-EINVAL);
12312 	}
12313 
12314 	if (!legacy) {
12315 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12316 					    func_offset, pid, ref_ctr_off);
12317 	} else {
12318 		char probe_name[MAX_EVENT_NAME_LEN];
12319 
12320 		if (ref_ctr_off)
12321 			return libbpf_err_ptr(-EINVAL);
12322 
12323 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12324 					    strrchr(binary_path, '/') ? : binary_path,
12325 					    func_offset);
12326 
12327 		legacy_probe = strdup(probe_name);
12328 		if (!legacy_probe)
12329 			return libbpf_err_ptr(-ENOMEM);
12330 
12331 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12332 						    binary_path, func_offset, pid);
12333 	}
12334 	if (pfd < 0) {
12335 		err = -errno;
12336 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12337 			prog->name, retprobe ? "uretprobe" : "uprobe",
12338 			binary_path, func_offset,
12339 			errstr(err));
12340 		goto err_out;
12341 	}
12342 
12343 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12344 	err = libbpf_get_error(link);
12345 	if (err) {
12346 		close(pfd);
12347 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12348 			prog->name, retprobe ? "uretprobe" : "uprobe",
12349 			binary_path, func_offset,
12350 			errstr(err));
12351 		goto err_clean_legacy;
12352 	}
12353 	if (legacy) {
12354 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12355 
12356 		perf_link->legacy_probe_name = legacy_probe;
12357 		perf_link->legacy_is_kprobe = false;
12358 		perf_link->legacy_is_retprobe = retprobe;
12359 	}
12360 	return link;
12361 
12362 err_clean_legacy:
12363 	if (legacy)
12364 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12365 err_out:
12366 	free(legacy_probe);
12367 	return libbpf_err_ptr(err);
12368 }
12369 
12370 /* Format of u[ret]probe section definition supporting auto-attach:
12371  * u[ret]probe/binary:function[+offset]
12372  *
12373  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12374  * full binary path via bpf_program__attach_uprobe_opts.
12375  *
12376  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12377  * specified (and auto-attach is not possible) or the above format is specified for
12378  * auto-attach.
12379  */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12380 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12381 {
12382 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12383 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12384 	int n, c, ret = -EINVAL;
12385 	long offset = 0;
12386 
12387 	*link = NULL;
12388 
12389 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12390 		   &probe_type, &binary_path, &func_name);
12391 	switch (n) {
12392 	case 1:
12393 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12394 		ret = 0;
12395 		break;
12396 	case 2:
12397 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12398 			prog->name, prog->sec_name);
12399 		break;
12400 	case 3:
12401 		/* check if user specifies `+offset`, if yes, this should be
12402 		 * the last part of the string, make sure sscanf read to EOL
12403 		 */
12404 		func_off = strrchr(func_name, '+');
12405 		if (func_off) {
12406 			n = sscanf(func_off, "+%li%n", &offset, &c);
12407 			if (n == 1 && *(func_off + c) == '\0')
12408 				func_off[0] = '\0';
12409 			else
12410 				offset = 0;
12411 		}
12412 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12413 				strcmp(probe_type, "uretprobe.s") == 0;
12414 		if (opts.retprobe && offset != 0) {
12415 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12416 				prog->name);
12417 			break;
12418 		}
12419 		opts.func_name = func_name;
12420 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12421 		ret = libbpf_get_error(*link);
12422 		break;
12423 	default:
12424 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12425 			prog->sec_name);
12426 		break;
12427 	}
12428 	free(probe_type);
12429 	free(binary_path);
12430 	free(func_name);
12431 
12432 	return ret;
12433 }
12434 
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)12435 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12436 					    bool retprobe, pid_t pid,
12437 					    const char *binary_path,
12438 					    size_t func_offset)
12439 {
12440 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12441 
12442 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12443 }
12444 
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)12445 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12446 					  pid_t pid, const char *binary_path,
12447 					  const char *usdt_provider, const char *usdt_name,
12448 					  const struct bpf_usdt_opts *opts)
12449 {
12450 	char resolved_path[512];
12451 	struct bpf_object *obj = prog->obj;
12452 	struct bpf_link *link;
12453 	__u64 usdt_cookie;
12454 	int err;
12455 
12456 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12457 		return libbpf_err_ptr(-EINVAL);
12458 
12459 	if (bpf_program__fd(prog) < 0) {
12460 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12461 			prog->name);
12462 		return libbpf_err_ptr(-EINVAL);
12463 	}
12464 
12465 	if (!binary_path)
12466 		return libbpf_err_ptr(-EINVAL);
12467 
12468 	if (!strchr(binary_path, '/')) {
12469 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12470 		if (err) {
12471 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12472 				prog->name, binary_path, errstr(err));
12473 			return libbpf_err_ptr(err);
12474 		}
12475 		binary_path = resolved_path;
12476 	}
12477 
12478 	/* USDT manager is instantiated lazily on first USDT attach. It will
12479 	 * be destroyed together with BPF object in bpf_object__close().
12480 	 */
12481 	if (IS_ERR(obj->usdt_man))
12482 		return libbpf_ptr(obj->usdt_man);
12483 	if (!obj->usdt_man) {
12484 		obj->usdt_man = usdt_manager_new(obj);
12485 		if (IS_ERR(obj->usdt_man))
12486 			return libbpf_ptr(obj->usdt_man);
12487 	}
12488 
12489 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12490 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12491 					usdt_provider, usdt_name, usdt_cookie);
12492 	err = libbpf_get_error(link);
12493 	if (err)
12494 		return libbpf_err_ptr(err);
12495 	return link;
12496 }
12497 
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12498 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12499 {
12500 	char *path = NULL, *provider = NULL, *name = NULL;
12501 	const char *sec_name;
12502 	int n, err;
12503 
12504 	sec_name = bpf_program__section_name(prog);
12505 	if (strcmp(sec_name, "usdt") == 0) {
12506 		/* no auto-attach for just SEC("usdt") */
12507 		*link = NULL;
12508 		return 0;
12509 	}
12510 
12511 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12512 	if (n != 3) {
12513 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12514 			sec_name);
12515 		err = -EINVAL;
12516 	} else {
12517 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12518 						 provider, name, NULL);
12519 		err = libbpf_get_error(*link);
12520 	}
12521 	free(path);
12522 	free(provider);
12523 	free(name);
12524 	return err;
12525 }
12526 
determine_tracepoint_id(const char * tp_category,const char * tp_name)12527 static int determine_tracepoint_id(const char *tp_category,
12528 				   const char *tp_name)
12529 {
12530 	char file[PATH_MAX];
12531 	int ret;
12532 
12533 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12534 		       tracefs_path(), tp_category, tp_name);
12535 	if (ret < 0)
12536 		return -errno;
12537 	if (ret >= sizeof(file)) {
12538 		pr_debug("tracepoint %s/%s path is too long\n",
12539 			 tp_category, tp_name);
12540 		return -E2BIG;
12541 	}
12542 	return parse_uint_from_file(file, "%d\n");
12543 }
12544 
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)12545 static int perf_event_open_tracepoint(const char *tp_category,
12546 				      const char *tp_name)
12547 {
12548 	const size_t attr_sz = sizeof(struct perf_event_attr);
12549 	struct perf_event_attr attr;
12550 	int tp_id, pfd, err;
12551 
12552 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12553 	if (tp_id < 0) {
12554 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12555 			tp_category, tp_name,
12556 			errstr(tp_id));
12557 		return tp_id;
12558 	}
12559 
12560 	memset(&attr, 0, attr_sz);
12561 	attr.type = PERF_TYPE_TRACEPOINT;
12562 	attr.size = attr_sz;
12563 	attr.config = tp_id;
12564 
12565 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12566 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12567 	if (pfd < 0) {
12568 		err = -errno;
12569 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12570 			tp_category, tp_name,
12571 			errstr(err));
12572 		return err;
12573 	}
12574 	return pfd;
12575 }
12576 
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)12577 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12578 						     const char *tp_category,
12579 						     const char *tp_name,
12580 						     const struct bpf_tracepoint_opts *opts)
12581 {
12582 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12583 	struct bpf_link *link;
12584 	int pfd, err;
12585 
12586 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12587 		return libbpf_err_ptr(-EINVAL);
12588 
12589 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12590 
12591 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12592 	if (pfd < 0) {
12593 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12594 			prog->name, tp_category, tp_name,
12595 			errstr(pfd));
12596 		return libbpf_err_ptr(pfd);
12597 	}
12598 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12599 	err = libbpf_get_error(link);
12600 	if (err) {
12601 		close(pfd);
12602 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12603 			prog->name, tp_category, tp_name,
12604 			errstr(err));
12605 		return libbpf_err_ptr(err);
12606 	}
12607 	return link;
12608 }
12609 
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)12610 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12611 						const char *tp_category,
12612 						const char *tp_name)
12613 {
12614 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12615 }
12616 
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12617 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12618 {
12619 	char *sec_name, *tp_cat, *tp_name;
12620 
12621 	*link = NULL;
12622 
12623 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12624 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12625 		return 0;
12626 
12627 	sec_name = strdup(prog->sec_name);
12628 	if (!sec_name)
12629 		return -ENOMEM;
12630 
12631 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12632 	if (str_has_pfx(prog->sec_name, "tp/"))
12633 		tp_cat = sec_name + sizeof("tp/") - 1;
12634 	else
12635 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12636 	tp_name = strchr(tp_cat, '/');
12637 	if (!tp_name) {
12638 		free(sec_name);
12639 		return -EINVAL;
12640 	}
12641 	*tp_name = '\0';
12642 	tp_name++;
12643 
12644 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12645 	free(sec_name);
12646 	return libbpf_get_error(*link);
12647 }
12648 
12649 struct bpf_link *
bpf_program__attach_raw_tracepoint_opts(const struct bpf_program * prog,const char * tp_name,struct bpf_raw_tracepoint_opts * opts)12650 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12651 					const char *tp_name,
12652 					struct bpf_raw_tracepoint_opts *opts)
12653 {
12654 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12655 	struct bpf_link *link;
12656 	int prog_fd, pfd;
12657 
12658 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12659 		return libbpf_err_ptr(-EINVAL);
12660 
12661 	prog_fd = bpf_program__fd(prog);
12662 	if (prog_fd < 0) {
12663 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12664 		return libbpf_err_ptr(-EINVAL);
12665 	}
12666 
12667 	link = calloc(1, sizeof(*link));
12668 	if (!link)
12669 		return libbpf_err_ptr(-ENOMEM);
12670 	link->detach = &bpf_link__detach_fd;
12671 
12672 	raw_opts.tp_name = tp_name;
12673 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12674 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12675 	if (pfd < 0) {
12676 		pfd = -errno;
12677 		free(link);
12678 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12679 			prog->name, tp_name, errstr(pfd));
12680 		return libbpf_err_ptr(pfd);
12681 	}
12682 	link->fd = pfd;
12683 	return link;
12684 }
12685 
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)12686 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12687 						    const char *tp_name)
12688 {
12689 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12690 }
12691 
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12692 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12693 {
12694 	static const char *const prefixes[] = {
12695 		"raw_tp",
12696 		"raw_tracepoint",
12697 		"raw_tp.w",
12698 		"raw_tracepoint.w",
12699 	};
12700 	size_t i;
12701 	const char *tp_name = NULL;
12702 
12703 	*link = NULL;
12704 
12705 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12706 		size_t pfx_len;
12707 
12708 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12709 			continue;
12710 
12711 		pfx_len = strlen(prefixes[i]);
12712 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12713 		if (prog->sec_name[pfx_len] == '\0')
12714 			return 0;
12715 
12716 		if (prog->sec_name[pfx_len] != '/')
12717 			continue;
12718 
12719 		tp_name = prog->sec_name + pfx_len + 1;
12720 		break;
12721 	}
12722 
12723 	if (!tp_name) {
12724 		pr_warn("prog '%s': invalid section name '%s'\n",
12725 			prog->name, prog->sec_name);
12726 		return -EINVAL;
12727 	}
12728 
12729 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12730 	return libbpf_get_error(*link);
12731 }
12732 
12733 /* 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)12734 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12735 						   const struct bpf_trace_opts *opts)
12736 {
12737 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12738 	struct bpf_link *link;
12739 	int prog_fd, pfd;
12740 
12741 	if (!OPTS_VALID(opts, bpf_trace_opts))
12742 		return libbpf_err_ptr(-EINVAL);
12743 
12744 	prog_fd = bpf_program__fd(prog);
12745 	if (prog_fd < 0) {
12746 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12747 		return libbpf_err_ptr(-EINVAL);
12748 	}
12749 
12750 	link = calloc(1, sizeof(*link));
12751 	if (!link)
12752 		return libbpf_err_ptr(-ENOMEM);
12753 	link->detach = &bpf_link__detach_fd;
12754 
12755 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12756 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12757 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12758 	if (pfd < 0) {
12759 		pfd = -errno;
12760 		free(link);
12761 		pr_warn("prog '%s': failed to attach: %s\n",
12762 			prog->name, errstr(pfd));
12763 		return libbpf_err_ptr(pfd);
12764 	}
12765 	link->fd = pfd;
12766 	return link;
12767 }
12768 
bpf_program__attach_trace(const struct bpf_program * prog)12769 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12770 {
12771 	return bpf_program__attach_btf_id(prog, NULL);
12772 }
12773 
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)12774 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12775 						const struct bpf_trace_opts *opts)
12776 {
12777 	return bpf_program__attach_btf_id(prog, opts);
12778 }
12779 
bpf_program__attach_lsm(const struct bpf_program * prog)12780 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12781 {
12782 	return bpf_program__attach_btf_id(prog, NULL);
12783 }
12784 
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12785 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12786 {
12787 	*link = bpf_program__attach_trace(prog);
12788 	return libbpf_get_error(*link);
12789 }
12790 
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12791 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12792 {
12793 	*link = bpf_program__attach_lsm(prog);
12794 	return libbpf_get_error(*link);
12795 }
12796 
12797 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)12798 bpf_program_attach_fd(const struct bpf_program *prog,
12799 		      int target_fd, const char *target_name,
12800 		      const struct bpf_link_create_opts *opts)
12801 {
12802 	enum bpf_attach_type attach_type;
12803 	struct bpf_link *link;
12804 	int prog_fd, link_fd;
12805 
12806 	prog_fd = bpf_program__fd(prog);
12807 	if (prog_fd < 0) {
12808 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12809 		return libbpf_err_ptr(-EINVAL);
12810 	}
12811 
12812 	link = calloc(1, sizeof(*link));
12813 	if (!link)
12814 		return libbpf_err_ptr(-ENOMEM);
12815 	link->detach = &bpf_link__detach_fd;
12816 
12817 	attach_type = bpf_program__expected_attach_type(prog);
12818 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12819 	if (link_fd < 0) {
12820 		link_fd = -errno;
12821 		free(link);
12822 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12823 			prog->name, target_name,
12824 			errstr(link_fd));
12825 		return libbpf_err_ptr(link_fd);
12826 	}
12827 	link->fd = link_fd;
12828 	return link;
12829 }
12830 
12831 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)12832 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12833 {
12834 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12835 }
12836 
12837 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)12838 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12839 {
12840 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12841 }
12842 
12843 struct bpf_link *
bpf_program__attach_sockmap(const struct bpf_program * prog,int map_fd)12844 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12845 {
12846 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12847 }
12848 
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)12849 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12850 {
12851 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12852 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12853 }
12854 
12855 struct bpf_link *
bpf_program__attach_cgroup_opts(const struct bpf_program * prog,int cgroup_fd,const struct bpf_cgroup_opts * opts)12856 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
12857 				const struct bpf_cgroup_opts *opts)
12858 {
12859 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12860 	__u32 relative_id;
12861 	int relative_fd;
12862 
12863 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
12864 		return libbpf_err_ptr(-EINVAL);
12865 
12866 	relative_id = OPTS_GET(opts, relative_id, 0);
12867 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12868 
12869 	if (relative_fd && relative_id) {
12870 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12871 			prog->name);
12872 		return libbpf_err_ptr(-EINVAL);
12873 	}
12874 
12875 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
12876 	link_create_opts.cgroup.relative_fd = relative_fd;
12877 	link_create_opts.cgroup.relative_id = relative_id;
12878 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12879 
12880 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
12881 }
12882 
12883 struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)12884 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12885 			const struct bpf_tcx_opts *opts)
12886 {
12887 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12888 	__u32 relative_id;
12889 	int relative_fd;
12890 
12891 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12892 		return libbpf_err_ptr(-EINVAL);
12893 
12894 	relative_id = OPTS_GET(opts, relative_id, 0);
12895 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12896 
12897 	/* validate we don't have unexpected combinations of non-zero fields */
12898 	if (!ifindex) {
12899 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12900 			prog->name);
12901 		return libbpf_err_ptr(-EINVAL);
12902 	}
12903 	if (relative_fd && relative_id) {
12904 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12905 			prog->name);
12906 		return libbpf_err_ptr(-EINVAL);
12907 	}
12908 
12909 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12910 	link_create_opts.tcx.relative_fd = relative_fd;
12911 	link_create_opts.tcx.relative_id = relative_id;
12912 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12913 
12914 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12915 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12916 }
12917 
12918 struct bpf_link *
bpf_program__attach_netkit(const struct bpf_program * prog,int ifindex,const struct bpf_netkit_opts * opts)12919 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12920 			   const struct bpf_netkit_opts *opts)
12921 {
12922 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12923 	__u32 relative_id;
12924 	int relative_fd;
12925 
12926 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12927 		return libbpf_err_ptr(-EINVAL);
12928 
12929 	relative_id = OPTS_GET(opts, relative_id, 0);
12930 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12931 
12932 	/* validate we don't have unexpected combinations of non-zero fields */
12933 	if (!ifindex) {
12934 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12935 			prog->name);
12936 		return libbpf_err_ptr(-EINVAL);
12937 	}
12938 	if (relative_fd && relative_id) {
12939 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12940 			prog->name);
12941 		return libbpf_err_ptr(-EINVAL);
12942 	}
12943 
12944 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12945 	link_create_opts.netkit.relative_fd = relative_fd;
12946 	link_create_opts.netkit.relative_id = relative_id;
12947 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12948 
12949 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12950 }
12951 
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)12952 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12953 					      int target_fd,
12954 					      const char *attach_func_name)
12955 {
12956 	int btf_id;
12957 
12958 	if (!!target_fd != !!attach_func_name) {
12959 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12960 			prog->name);
12961 		return libbpf_err_ptr(-EINVAL);
12962 	}
12963 
12964 	if (prog->type != BPF_PROG_TYPE_EXT) {
12965 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12966 			prog->name);
12967 		return libbpf_err_ptr(-EINVAL);
12968 	}
12969 
12970 	if (target_fd) {
12971 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12972 
12973 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
12974 		if (btf_id < 0)
12975 			return libbpf_err_ptr(btf_id);
12976 
12977 		target_opts.target_btf_id = btf_id;
12978 
12979 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12980 					     &target_opts);
12981 	} else {
12982 		/* no target, so use raw_tracepoint_open for compatibility
12983 		 * with old kernels
12984 		 */
12985 		return bpf_program__attach_trace(prog);
12986 	}
12987 }
12988 
12989 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)12990 bpf_program__attach_iter(const struct bpf_program *prog,
12991 			 const struct bpf_iter_attach_opts *opts)
12992 {
12993 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12994 	struct bpf_link *link;
12995 	int prog_fd, link_fd;
12996 	__u32 target_fd = 0;
12997 
12998 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12999 		return libbpf_err_ptr(-EINVAL);
13000 
13001 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13002 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13003 
13004 	prog_fd = bpf_program__fd(prog);
13005 	if (prog_fd < 0) {
13006 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13007 		return libbpf_err_ptr(-EINVAL);
13008 	}
13009 
13010 	link = calloc(1, sizeof(*link));
13011 	if (!link)
13012 		return libbpf_err_ptr(-ENOMEM);
13013 	link->detach = &bpf_link__detach_fd;
13014 
13015 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13016 				  &link_create_opts);
13017 	if (link_fd < 0) {
13018 		link_fd = -errno;
13019 		free(link);
13020 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13021 			prog->name, errstr(link_fd));
13022 		return libbpf_err_ptr(link_fd);
13023 	}
13024 	link->fd = link_fd;
13025 	return link;
13026 }
13027 
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)13028 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13029 {
13030 	*link = bpf_program__attach_iter(prog, NULL);
13031 	return libbpf_get_error(*link);
13032 }
13033 
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)13034 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13035 					       const struct bpf_netfilter_opts *opts)
13036 {
13037 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13038 	struct bpf_link *link;
13039 	int prog_fd, link_fd;
13040 
13041 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13042 		return libbpf_err_ptr(-EINVAL);
13043 
13044 	prog_fd = bpf_program__fd(prog);
13045 	if (prog_fd < 0) {
13046 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13047 		return libbpf_err_ptr(-EINVAL);
13048 	}
13049 
13050 	link = calloc(1, sizeof(*link));
13051 	if (!link)
13052 		return libbpf_err_ptr(-ENOMEM);
13053 
13054 	link->detach = &bpf_link__detach_fd;
13055 
13056 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13057 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13058 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13059 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13060 
13061 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13062 	if (link_fd < 0) {
13063 		link_fd = -errno;
13064 		free(link);
13065 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13066 			prog->name, errstr(link_fd));
13067 		return libbpf_err_ptr(link_fd);
13068 	}
13069 	link->fd = link_fd;
13070 
13071 	return link;
13072 }
13073 
bpf_program__attach(const struct bpf_program * prog)13074 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13075 {
13076 	struct bpf_link *link = NULL;
13077 	int err;
13078 
13079 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13080 		return libbpf_err_ptr(-EOPNOTSUPP);
13081 
13082 	if (bpf_program__fd(prog) < 0) {
13083 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13084 			prog->name);
13085 		return libbpf_err_ptr(-EINVAL);
13086 	}
13087 
13088 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13089 	if (err)
13090 		return libbpf_err_ptr(err);
13091 
13092 	/* When calling bpf_program__attach() explicitly, auto-attach support
13093 	 * is expected to work, so NULL returned link is considered an error.
13094 	 * This is different for skeleton's attach, see comment in
13095 	 * bpf_object__attach_skeleton().
13096 	 */
13097 	if (!link)
13098 		return libbpf_err_ptr(-EOPNOTSUPP);
13099 
13100 	return link;
13101 }
13102 
13103 struct bpf_link_struct_ops {
13104 	struct bpf_link link;
13105 	int map_fd;
13106 };
13107 
bpf_link__detach_struct_ops(struct bpf_link * link)13108 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13109 {
13110 	struct bpf_link_struct_ops *st_link;
13111 	__u32 zero = 0;
13112 
13113 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13114 
13115 	if (st_link->map_fd < 0)
13116 		/* w/o a real link */
13117 		return bpf_map_delete_elem(link->fd, &zero);
13118 
13119 	return close(link->fd);
13120 }
13121 
bpf_map__attach_struct_ops(const struct bpf_map * map)13122 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13123 {
13124 	struct bpf_link_struct_ops *link;
13125 	__u32 zero = 0;
13126 	int err, fd;
13127 
13128 	if (!bpf_map__is_struct_ops(map)) {
13129 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13130 		return libbpf_err_ptr(-EINVAL);
13131 	}
13132 
13133 	if (map->fd < 0) {
13134 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13135 		return libbpf_err_ptr(-EINVAL);
13136 	}
13137 
13138 	link = calloc(1, sizeof(*link));
13139 	if (!link)
13140 		return libbpf_err_ptr(-EINVAL);
13141 
13142 	/* kern_vdata should be prepared during the loading phase. */
13143 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13144 	/* It can be EBUSY if the map has been used to create or
13145 	 * update a link before.  We don't allow updating the value of
13146 	 * a struct_ops once it is set.  That ensures that the value
13147 	 * never changed.  So, it is safe to skip EBUSY.
13148 	 */
13149 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13150 		free(link);
13151 		return libbpf_err_ptr(err);
13152 	}
13153 
13154 	link->link.detach = bpf_link__detach_struct_ops;
13155 
13156 	if (!(map->def.map_flags & BPF_F_LINK)) {
13157 		/* w/o a real link */
13158 		link->link.fd = map->fd;
13159 		link->map_fd = -1;
13160 		return &link->link;
13161 	}
13162 
13163 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13164 	if (fd < 0) {
13165 		free(link);
13166 		return libbpf_err_ptr(fd);
13167 	}
13168 
13169 	link->link.fd = fd;
13170 	link->map_fd = map->fd;
13171 
13172 	return &link->link;
13173 }
13174 
13175 /*
13176  * Swap the back struct_ops of a link with a new struct_ops map.
13177  */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)13178 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13179 {
13180 	struct bpf_link_struct_ops *st_ops_link;
13181 	__u32 zero = 0;
13182 	int err;
13183 
13184 	if (!bpf_map__is_struct_ops(map))
13185 		return libbpf_err(-EINVAL);
13186 
13187 	if (map->fd < 0) {
13188 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13189 		return libbpf_err(-EINVAL);
13190 	}
13191 
13192 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13193 	/* Ensure the type of a link is correct */
13194 	if (st_ops_link->map_fd < 0)
13195 		return libbpf_err(-EINVAL);
13196 
13197 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13198 	/* It can be EBUSY if the map has been used to create or
13199 	 * update a link before.  We don't allow updating the value of
13200 	 * a struct_ops once it is set.  That ensures that the value
13201 	 * never changed.  So, it is safe to skip EBUSY.
13202 	 */
13203 	if (err && err != -EBUSY)
13204 		return err;
13205 
13206 	err = bpf_link_update(link->fd, map->fd, NULL);
13207 	if (err < 0)
13208 		return err;
13209 
13210 	st_ops_link->map_fd = map->fd;
13211 
13212 	return 0;
13213 }
13214 
13215 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13216 							  void *private_data);
13217 
13218 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)13219 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13220 		       void **copy_mem, size_t *copy_size,
13221 		       bpf_perf_event_print_t fn, void *private_data)
13222 {
13223 	struct perf_event_mmap_page *header = mmap_mem;
13224 	__u64 data_head = ring_buffer_read_head(header);
13225 	__u64 data_tail = header->data_tail;
13226 	void *base = ((__u8 *)header) + page_size;
13227 	int ret = LIBBPF_PERF_EVENT_CONT;
13228 	struct perf_event_header *ehdr;
13229 	size_t ehdr_size;
13230 
13231 	while (data_head != data_tail) {
13232 		ehdr = base + (data_tail & (mmap_size - 1));
13233 		ehdr_size = ehdr->size;
13234 
13235 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13236 			void *copy_start = ehdr;
13237 			size_t len_first = base + mmap_size - copy_start;
13238 			size_t len_secnd = ehdr_size - len_first;
13239 
13240 			if (*copy_size < ehdr_size) {
13241 				free(*copy_mem);
13242 				*copy_mem = malloc(ehdr_size);
13243 				if (!*copy_mem) {
13244 					*copy_size = 0;
13245 					ret = LIBBPF_PERF_EVENT_ERROR;
13246 					break;
13247 				}
13248 				*copy_size = ehdr_size;
13249 			}
13250 
13251 			memcpy(*copy_mem, copy_start, len_first);
13252 			memcpy(*copy_mem + len_first, base, len_secnd);
13253 			ehdr = *copy_mem;
13254 		}
13255 
13256 		ret = fn(ehdr, private_data);
13257 		data_tail += ehdr_size;
13258 		if (ret != LIBBPF_PERF_EVENT_CONT)
13259 			break;
13260 	}
13261 
13262 	ring_buffer_write_tail(header, data_tail);
13263 	return libbpf_err(ret);
13264 }
13265 
13266 struct perf_buffer;
13267 
13268 struct perf_buffer_params {
13269 	struct perf_event_attr *attr;
13270 	/* if event_cb is specified, it takes precendence */
13271 	perf_buffer_event_fn event_cb;
13272 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13273 	perf_buffer_sample_fn sample_cb;
13274 	perf_buffer_lost_fn lost_cb;
13275 	void *ctx;
13276 	int cpu_cnt;
13277 	int *cpus;
13278 	int *map_keys;
13279 };
13280 
13281 struct perf_cpu_buf {
13282 	struct perf_buffer *pb;
13283 	void *base; /* mmap()'ed memory */
13284 	void *buf; /* for reconstructing segmented data */
13285 	size_t buf_size;
13286 	int fd;
13287 	int cpu;
13288 	int map_key;
13289 };
13290 
13291 struct perf_buffer {
13292 	perf_buffer_event_fn event_cb;
13293 	perf_buffer_sample_fn sample_cb;
13294 	perf_buffer_lost_fn lost_cb;
13295 	void *ctx; /* passed into callbacks */
13296 
13297 	size_t page_size;
13298 	size_t mmap_size;
13299 	struct perf_cpu_buf **cpu_bufs;
13300 	struct epoll_event *events;
13301 	int cpu_cnt; /* number of allocated CPU buffers */
13302 	int epoll_fd; /* perf event FD */
13303 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13304 };
13305 
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)13306 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13307 				      struct perf_cpu_buf *cpu_buf)
13308 {
13309 	if (!cpu_buf)
13310 		return;
13311 	if (cpu_buf->base &&
13312 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13313 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13314 	if (cpu_buf->fd >= 0) {
13315 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13316 		close(cpu_buf->fd);
13317 	}
13318 	free(cpu_buf->buf);
13319 	free(cpu_buf);
13320 }
13321 
perf_buffer__free(struct perf_buffer * pb)13322 void perf_buffer__free(struct perf_buffer *pb)
13323 {
13324 	int i;
13325 
13326 	if (IS_ERR_OR_NULL(pb))
13327 		return;
13328 	if (pb->cpu_bufs) {
13329 		for (i = 0; i < pb->cpu_cnt; i++) {
13330 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13331 
13332 			if (!cpu_buf)
13333 				continue;
13334 
13335 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13336 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13337 		}
13338 		free(pb->cpu_bufs);
13339 	}
13340 	if (pb->epoll_fd >= 0)
13341 		close(pb->epoll_fd);
13342 	free(pb->events);
13343 	free(pb);
13344 }
13345 
13346 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)13347 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13348 			  int cpu, int map_key)
13349 {
13350 	struct perf_cpu_buf *cpu_buf;
13351 	int err;
13352 
13353 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13354 	if (!cpu_buf)
13355 		return ERR_PTR(-ENOMEM);
13356 
13357 	cpu_buf->pb = pb;
13358 	cpu_buf->cpu = cpu;
13359 	cpu_buf->map_key = map_key;
13360 
13361 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13362 			      -1, PERF_FLAG_FD_CLOEXEC);
13363 	if (cpu_buf->fd < 0) {
13364 		err = -errno;
13365 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13366 			cpu, errstr(err));
13367 		goto error;
13368 	}
13369 
13370 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13371 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13372 			     cpu_buf->fd, 0);
13373 	if (cpu_buf->base == MAP_FAILED) {
13374 		cpu_buf->base = NULL;
13375 		err = -errno;
13376 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13377 			cpu, errstr(err));
13378 		goto error;
13379 	}
13380 
13381 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13382 		err = -errno;
13383 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13384 			cpu, errstr(err));
13385 		goto error;
13386 	}
13387 
13388 	return cpu_buf;
13389 
13390 error:
13391 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13392 	return (struct perf_cpu_buf *)ERR_PTR(err);
13393 }
13394 
13395 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13396 					      struct perf_buffer_params *p);
13397 
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)13398 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13399 				     perf_buffer_sample_fn sample_cb,
13400 				     perf_buffer_lost_fn lost_cb,
13401 				     void *ctx,
13402 				     const struct perf_buffer_opts *opts)
13403 {
13404 	const size_t attr_sz = sizeof(struct perf_event_attr);
13405 	struct perf_buffer_params p = {};
13406 	struct perf_event_attr attr;
13407 	__u32 sample_period;
13408 
13409 	if (!OPTS_VALID(opts, perf_buffer_opts))
13410 		return libbpf_err_ptr(-EINVAL);
13411 
13412 	sample_period = OPTS_GET(opts, sample_period, 1);
13413 	if (!sample_period)
13414 		sample_period = 1;
13415 
13416 	memset(&attr, 0, attr_sz);
13417 	attr.size = attr_sz;
13418 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13419 	attr.type = PERF_TYPE_SOFTWARE;
13420 	attr.sample_type = PERF_SAMPLE_RAW;
13421 	attr.wakeup_events = sample_period;
13422 
13423 	p.attr = &attr;
13424 	p.sample_cb = sample_cb;
13425 	p.lost_cb = lost_cb;
13426 	p.ctx = ctx;
13427 
13428 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13429 }
13430 
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)13431 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13432 					 struct perf_event_attr *attr,
13433 					 perf_buffer_event_fn event_cb, void *ctx,
13434 					 const struct perf_buffer_raw_opts *opts)
13435 {
13436 	struct perf_buffer_params p = {};
13437 
13438 	if (!attr)
13439 		return libbpf_err_ptr(-EINVAL);
13440 
13441 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13442 		return libbpf_err_ptr(-EINVAL);
13443 
13444 	p.attr = attr;
13445 	p.event_cb = event_cb;
13446 	p.ctx = ctx;
13447 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13448 	p.cpus = OPTS_GET(opts, cpus, NULL);
13449 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13450 
13451 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13452 }
13453 
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)13454 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13455 					      struct perf_buffer_params *p)
13456 {
13457 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13458 	struct bpf_map_info map;
13459 	struct perf_buffer *pb;
13460 	bool *online = NULL;
13461 	__u32 map_info_len;
13462 	int err, i, j, n;
13463 
13464 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13465 		pr_warn("page count should be power of two, but is %zu\n",
13466 			page_cnt);
13467 		return ERR_PTR(-EINVAL);
13468 	}
13469 
13470 	/* best-effort sanity checks */
13471 	memset(&map, 0, sizeof(map));
13472 	map_info_len = sizeof(map);
13473 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13474 	if (err) {
13475 		err = -errno;
13476 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13477 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13478 		 */
13479 		if (err != -EINVAL) {
13480 			pr_warn("failed to get map info for map FD %d: %s\n",
13481 				map_fd, errstr(err));
13482 			return ERR_PTR(err);
13483 		}
13484 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13485 			 map_fd);
13486 	} else {
13487 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13488 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13489 				map.name);
13490 			return ERR_PTR(-EINVAL);
13491 		}
13492 	}
13493 
13494 	pb = calloc(1, sizeof(*pb));
13495 	if (!pb)
13496 		return ERR_PTR(-ENOMEM);
13497 
13498 	pb->event_cb = p->event_cb;
13499 	pb->sample_cb = p->sample_cb;
13500 	pb->lost_cb = p->lost_cb;
13501 	pb->ctx = p->ctx;
13502 
13503 	pb->page_size = getpagesize();
13504 	pb->mmap_size = pb->page_size * page_cnt;
13505 	pb->map_fd = map_fd;
13506 
13507 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13508 	if (pb->epoll_fd < 0) {
13509 		err = -errno;
13510 		pr_warn("failed to create epoll instance: %s\n",
13511 			errstr(err));
13512 		goto error;
13513 	}
13514 
13515 	if (p->cpu_cnt > 0) {
13516 		pb->cpu_cnt = p->cpu_cnt;
13517 	} else {
13518 		pb->cpu_cnt = libbpf_num_possible_cpus();
13519 		if (pb->cpu_cnt < 0) {
13520 			err = pb->cpu_cnt;
13521 			goto error;
13522 		}
13523 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13524 			pb->cpu_cnt = map.max_entries;
13525 	}
13526 
13527 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13528 	if (!pb->events) {
13529 		err = -ENOMEM;
13530 		pr_warn("failed to allocate events: out of memory\n");
13531 		goto error;
13532 	}
13533 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13534 	if (!pb->cpu_bufs) {
13535 		err = -ENOMEM;
13536 		pr_warn("failed to allocate buffers: out of memory\n");
13537 		goto error;
13538 	}
13539 
13540 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13541 	if (err) {
13542 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13543 		goto error;
13544 	}
13545 
13546 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13547 		struct perf_cpu_buf *cpu_buf;
13548 		int cpu, map_key;
13549 
13550 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13551 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13552 
13553 		/* in case user didn't explicitly requested particular CPUs to
13554 		 * be attached to, skip offline/not present CPUs
13555 		 */
13556 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13557 			continue;
13558 
13559 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13560 		if (IS_ERR(cpu_buf)) {
13561 			err = PTR_ERR(cpu_buf);
13562 			goto error;
13563 		}
13564 
13565 		pb->cpu_bufs[j] = cpu_buf;
13566 
13567 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13568 					  &cpu_buf->fd, 0);
13569 		if (err) {
13570 			err = -errno;
13571 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13572 				cpu, map_key, cpu_buf->fd,
13573 				errstr(err));
13574 			goto error;
13575 		}
13576 
13577 		pb->events[j].events = EPOLLIN;
13578 		pb->events[j].data.ptr = cpu_buf;
13579 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13580 			      &pb->events[j]) < 0) {
13581 			err = -errno;
13582 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13583 				cpu, cpu_buf->fd,
13584 				errstr(err));
13585 			goto error;
13586 		}
13587 		j++;
13588 	}
13589 	pb->cpu_cnt = j;
13590 	free(online);
13591 
13592 	return pb;
13593 
13594 error:
13595 	free(online);
13596 	if (pb)
13597 		perf_buffer__free(pb);
13598 	return ERR_PTR(err);
13599 }
13600 
13601 struct perf_sample_raw {
13602 	struct perf_event_header header;
13603 	uint32_t size;
13604 	char data[];
13605 };
13606 
13607 struct perf_sample_lost {
13608 	struct perf_event_header header;
13609 	uint64_t id;
13610 	uint64_t lost;
13611 	uint64_t sample_id;
13612 };
13613 
13614 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)13615 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13616 {
13617 	struct perf_cpu_buf *cpu_buf = ctx;
13618 	struct perf_buffer *pb = cpu_buf->pb;
13619 	void *data = e;
13620 
13621 	/* user wants full control over parsing perf event */
13622 	if (pb->event_cb)
13623 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13624 
13625 	switch (e->type) {
13626 	case PERF_RECORD_SAMPLE: {
13627 		struct perf_sample_raw *s = data;
13628 
13629 		if (pb->sample_cb)
13630 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13631 		break;
13632 	}
13633 	case PERF_RECORD_LOST: {
13634 		struct perf_sample_lost *s = data;
13635 
13636 		if (pb->lost_cb)
13637 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13638 		break;
13639 	}
13640 	default:
13641 		pr_warn("unknown perf sample type %d\n", e->type);
13642 		return LIBBPF_PERF_EVENT_ERROR;
13643 	}
13644 	return LIBBPF_PERF_EVENT_CONT;
13645 }
13646 
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)13647 static int perf_buffer__process_records(struct perf_buffer *pb,
13648 					struct perf_cpu_buf *cpu_buf)
13649 {
13650 	enum bpf_perf_event_ret ret;
13651 
13652 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13653 				     pb->page_size, &cpu_buf->buf,
13654 				     &cpu_buf->buf_size,
13655 				     perf_buffer__process_record, cpu_buf);
13656 	if (ret != LIBBPF_PERF_EVENT_CONT)
13657 		return ret;
13658 	return 0;
13659 }
13660 
perf_buffer__epoll_fd(const struct perf_buffer * pb)13661 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13662 {
13663 	return pb->epoll_fd;
13664 }
13665 
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)13666 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13667 {
13668 	int i, cnt, err;
13669 
13670 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13671 	if (cnt < 0)
13672 		return -errno;
13673 
13674 	for (i = 0; i < cnt; i++) {
13675 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13676 
13677 		err = perf_buffer__process_records(pb, cpu_buf);
13678 		if (err) {
13679 			pr_warn("error while processing records: %s\n", errstr(err));
13680 			return libbpf_err(err);
13681 		}
13682 	}
13683 	return cnt;
13684 }
13685 
13686 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13687  * manager.
13688  */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)13689 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13690 {
13691 	return pb->cpu_cnt;
13692 }
13693 
13694 /*
13695  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13696  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13697  * select()/poll()/epoll() Linux syscalls.
13698  */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)13699 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13700 {
13701 	struct perf_cpu_buf *cpu_buf;
13702 
13703 	if (buf_idx >= pb->cpu_cnt)
13704 		return libbpf_err(-EINVAL);
13705 
13706 	cpu_buf = pb->cpu_bufs[buf_idx];
13707 	if (!cpu_buf)
13708 		return libbpf_err(-ENOENT);
13709 
13710 	return cpu_buf->fd;
13711 }
13712 
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)13713 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13714 {
13715 	struct perf_cpu_buf *cpu_buf;
13716 
13717 	if (buf_idx >= pb->cpu_cnt)
13718 		return libbpf_err(-EINVAL);
13719 
13720 	cpu_buf = pb->cpu_bufs[buf_idx];
13721 	if (!cpu_buf)
13722 		return libbpf_err(-ENOENT);
13723 
13724 	*buf = cpu_buf->base;
13725 	*buf_size = pb->mmap_size;
13726 	return 0;
13727 }
13728 
13729 /*
13730  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13731  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13732  * consume, do nothing and return success.
13733  * Returns:
13734  *   - 0 on success;
13735  *   - <0 on failure.
13736  */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)13737 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13738 {
13739 	struct perf_cpu_buf *cpu_buf;
13740 
13741 	if (buf_idx >= pb->cpu_cnt)
13742 		return libbpf_err(-EINVAL);
13743 
13744 	cpu_buf = pb->cpu_bufs[buf_idx];
13745 	if (!cpu_buf)
13746 		return libbpf_err(-ENOENT);
13747 
13748 	return perf_buffer__process_records(pb, cpu_buf);
13749 }
13750 
perf_buffer__consume(struct perf_buffer * pb)13751 int perf_buffer__consume(struct perf_buffer *pb)
13752 {
13753 	int i, err;
13754 
13755 	for (i = 0; i < pb->cpu_cnt; i++) {
13756 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13757 
13758 		if (!cpu_buf)
13759 			continue;
13760 
13761 		err = perf_buffer__process_records(pb, cpu_buf);
13762 		if (err) {
13763 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13764 				i, errstr(err));
13765 			return libbpf_err(err);
13766 		}
13767 	}
13768 	return 0;
13769 }
13770 
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)13771 int bpf_program__set_attach_target(struct bpf_program *prog,
13772 				   int attach_prog_fd,
13773 				   const char *attach_func_name)
13774 {
13775 	int btf_obj_fd = 0, btf_id = 0, err;
13776 
13777 	if (!prog || attach_prog_fd < 0)
13778 		return libbpf_err(-EINVAL);
13779 
13780 	if (prog->obj->state >= OBJ_LOADED)
13781 		return libbpf_err(-EINVAL);
13782 
13783 	if (attach_prog_fd && !attach_func_name) {
13784 		/* remember attach_prog_fd and let bpf_program__load() find
13785 		 * BTF ID during the program load
13786 		 */
13787 		prog->attach_prog_fd = attach_prog_fd;
13788 		return 0;
13789 	}
13790 
13791 	if (attach_prog_fd) {
13792 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13793 						 attach_prog_fd, prog->obj->token_fd);
13794 		if (btf_id < 0)
13795 			return libbpf_err(btf_id);
13796 	} else {
13797 		if (!attach_func_name)
13798 			return libbpf_err(-EINVAL);
13799 
13800 		/* load btf_vmlinux, if not yet */
13801 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13802 		if (err)
13803 			return libbpf_err(err);
13804 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13805 					 prog->expected_attach_type,
13806 					 &btf_obj_fd, &btf_id);
13807 		if (err)
13808 			return libbpf_err(err);
13809 	}
13810 
13811 	prog->attach_btf_id = btf_id;
13812 	prog->attach_btf_obj_fd = btf_obj_fd;
13813 	prog->attach_prog_fd = attach_prog_fd;
13814 	return 0;
13815 }
13816 
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)13817 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13818 {
13819 	int err = 0, n, len, start, end = -1;
13820 	bool *tmp;
13821 
13822 	*mask = NULL;
13823 	*mask_sz = 0;
13824 
13825 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13826 	while (*s) {
13827 		if (*s == ',' || *s == '\n') {
13828 			s++;
13829 			continue;
13830 		}
13831 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13832 		if (n <= 0 || n > 2) {
13833 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13834 			err = -EINVAL;
13835 			goto cleanup;
13836 		} else if (n == 1) {
13837 			end = start;
13838 		}
13839 		if (start < 0 || start > end) {
13840 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13841 				start, end, s);
13842 			err = -EINVAL;
13843 			goto cleanup;
13844 		}
13845 		tmp = realloc(*mask, end + 1);
13846 		if (!tmp) {
13847 			err = -ENOMEM;
13848 			goto cleanup;
13849 		}
13850 		*mask = tmp;
13851 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13852 		memset(tmp + start, 1, end - start + 1);
13853 		*mask_sz = end + 1;
13854 		s += len;
13855 	}
13856 	if (!*mask_sz) {
13857 		pr_warn("Empty CPU range\n");
13858 		return -EINVAL;
13859 	}
13860 	return 0;
13861 cleanup:
13862 	free(*mask);
13863 	*mask = NULL;
13864 	return err;
13865 }
13866 
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)13867 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13868 {
13869 	int fd, err = 0, len;
13870 	char buf[128];
13871 
13872 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13873 	if (fd < 0) {
13874 		err = -errno;
13875 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13876 		return err;
13877 	}
13878 	len = read(fd, buf, sizeof(buf));
13879 	close(fd);
13880 	if (len <= 0) {
13881 		err = len ? -errno : -EINVAL;
13882 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13883 		return err;
13884 	}
13885 	if (len >= sizeof(buf)) {
13886 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13887 		return -E2BIG;
13888 	}
13889 	buf[len] = '\0';
13890 
13891 	return parse_cpu_mask_str(buf, mask, mask_sz);
13892 }
13893 
libbpf_num_possible_cpus(void)13894 int libbpf_num_possible_cpus(void)
13895 {
13896 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13897 	static int cpus;
13898 	int err, n, i, tmp_cpus;
13899 	bool *mask;
13900 
13901 	tmp_cpus = READ_ONCE(cpus);
13902 	if (tmp_cpus > 0)
13903 		return tmp_cpus;
13904 
13905 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13906 	if (err)
13907 		return libbpf_err(err);
13908 
13909 	tmp_cpus = 0;
13910 	for (i = 0; i < n; i++) {
13911 		if (mask[i])
13912 			tmp_cpus++;
13913 	}
13914 	free(mask);
13915 
13916 	WRITE_ONCE(cpus, tmp_cpus);
13917 	return tmp_cpus;
13918 }
13919 
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt,size_t map_skel_sz)13920 static int populate_skeleton_maps(const struct bpf_object *obj,
13921 				  struct bpf_map_skeleton *maps,
13922 				  size_t map_cnt, size_t map_skel_sz)
13923 {
13924 	int i;
13925 
13926 	for (i = 0; i < map_cnt; i++) {
13927 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13928 		struct bpf_map **map = map_skel->map;
13929 		const char *name = map_skel->name;
13930 		void **mmaped = map_skel->mmaped;
13931 
13932 		*map = bpf_object__find_map_by_name(obj, name);
13933 		if (!*map) {
13934 			pr_warn("failed to find skeleton map '%s'\n", name);
13935 			return -ESRCH;
13936 		}
13937 
13938 		/* externs shouldn't be pre-setup from user code */
13939 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13940 			*mmaped = (*map)->mmaped;
13941 	}
13942 	return 0;
13943 }
13944 
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt,size_t prog_skel_sz)13945 static int populate_skeleton_progs(const struct bpf_object *obj,
13946 				   struct bpf_prog_skeleton *progs,
13947 				   size_t prog_cnt, size_t prog_skel_sz)
13948 {
13949 	int i;
13950 
13951 	for (i = 0; i < prog_cnt; i++) {
13952 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13953 		struct bpf_program **prog = prog_skel->prog;
13954 		const char *name = prog_skel->name;
13955 
13956 		*prog = bpf_object__find_program_by_name(obj, name);
13957 		if (!*prog) {
13958 			pr_warn("failed to find skeleton program '%s'\n", name);
13959 			return -ESRCH;
13960 		}
13961 	}
13962 	return 0;
13963 }
13964 
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)13965 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13966 			      const struct bpf_object_open_opts *opts)
13967 {
13968 	struct bpf_object *obj;
13969 	int err;
13970 
13971 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13972 	if (IS_ERR(obj)) {
13973 		err = PTR_ERR(obj);
13974 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
13975 			s->name, errstr(err));
13976 		return libbpf_err(err);
13977 	}
13978 
13979 	*s->obj = obj;
13980 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13981 	if (err) {
13982 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
13983 		return libbpf_err(err);
13984 	}
13985 
13986 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13987 	if (err) {
13988 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
13989 		return libbpf_err(err);
13990 	}
13991 
13992 	return 0;
13993 }
13994 
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13995 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13996 {
13997 	int err, len, var_idx, i;
13998 	const char *var_name;
13999 	const struct bpf_map *map;
14000 	struct btf *btf;
14001 	__u32 map_type_id;
14002 	const struct btf_type *map_type, *var_type;
14003 	const struct bpf_var_skeleton *var_skel;
14004 	struct btf_var_secinfo *var;
14005 
14006 	if (!s->obj)
14007 		return libbpf_err(-EINVAL);
14008 
14009 	btf = bpf_object__btf(s->obj);
14010 	if (!btf) {
14011 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14012 			bpf_object__name(s->obj));
14013 		return libbpf_err(-errno);
14014 	}
14015 
14016 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14017 	if (err) {
14018 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14019 		return libbpf_err(err);
14020 	}
14021 
14022 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14023 	if (err) {
14024 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14025 		return libbpf_err(err);
14026 	}
14027 
14028 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14029 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14030 		map = *var_skel->map;
14031 		map_type_id = bpf_map__btf_value_type_id(map);
14032 		map_type = btf__type_by_id(btf, map_type_id);
14033 
14034 		if (!btf_is_datasec(map_type)) {
14035 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14036 				bpf_map__name(map),
14037 				__btf_kind_str(btf_kind(map_type)));
14038 			return libbpf_err(-EINVAL);
14039 		}
14040 
14041 		len = btf_vlen(map_type);
14042 		var = btf_var_secinfos(map_type);
14043 		for (i = 0; i < len; i++, var++) {
14044 			var_type = btf__type_by_id(btf, var->type);
14045 			var_name = btf__name_by_offset(btf, var_type->name_off);
14046 			if (strcmp(var_name, var_skel->name) == 0) {
14047 				*var_skel->addr = map->mmaped + var->offset;
14048 				break;
14049 			}
14050 		}
14051 	}
14052 	return 0;
14053 }
14054 
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)14055 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14056 {
14057 	if (!s)
14058 		return;
14059 	free(s->maps);
14060 	free(s->progs);
14061 	free(s->vars);
14062 	free(s);
14063 }
14064 
bpf_object__load_skeleton(struct bpf_object_skeleton * s)14065 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14066 {
14067 	int i, err;
14068 
14069 	err = bpf_object__load(*s->obj);
14070 	if (err) {
14071 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14072 		return libbpf_err(err);
14073 	}
14074 
14075 	for (i = 0; i < s->map_cnt; i++) {
14076 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14077 		struct bpf_map *map = *map_skel->map;
14078 
14079 		if (!map_skel->mmaped)
14080 			continue;
14081 
14082 		*map_skel->mmaped = map->mmaped;
14083 	}
14084 
14085 	return 0;
14086 }
14087 
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)14088 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14089 {
14090 	int i, err;
14091 
14092 	for (i = 0; i < s->prog_cnt; i++) {
14093 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14094 		struct bpf_program *prog = *prog_skel->prog;
14095 		struct bpf_link **link = prog_skel->link;
14096 
14097 		if (!prog->autoload || !prog->autoattach)
14098 			continue;
14099 
14100 		/* auto-attaching not supported for this program */
14101 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14102 			continue;
14103 
14104 		/* if user already set the link manually, don't attempt auto-attach */
14105 		if (*link)
14106 			continue;
14107 
14108 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14109 		if (err) {
14110 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14111 				bpf_program__name(prog), errstr(err));
14112 			return libbpf_err(err);
14113 		}
14114 
14115 		/* It's possible that for some SEC() definitions auto-attach
14116 		 * is supported in some cases (e.g., if definition completely
14117 		 * specifies target information), but is not in other cases.
14118 		 * SEC("uprobe") is one such case. If user specified target
14119 		 * binary and function name, such BPF program can be
14120 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14121 		 * attach to fail. It should just be skipped.
14122 		 * attach_fn signals such case with returning 0 (no error) and
14123 		 * setting link to NULL.
14124 		 */
14125 	}
14126 
14127 
14128 	for (i = 0; i < s->map_cnt; i++) {
14129 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14130 		struct bpf_map *map = *map_skel->map;
14131 		struct bpf_link **link;
14132 
14133 		if (!map->autocreate || !map->autoattach)
14134 			continue;
14135 
14136 		/* only struct_ops maps can be attached */
14137 		if (!bpf_map__is_struct_ops(map))
14138 			continue;
14139 
14140 		/* skeleton is created with earlier version of bpftool, notify user */
14141 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14142 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14143 				bpf_map__name(map));
14144 			continue;
14145 		}
14146 
14147 		link = map_skel->link;
14148 		if (!link) {
14149 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14150 				bpf_map__name(map));
14151 			continue;
14152 		}
14153 
14154 		if (*link)
14155 			continue;
14156 
14157 		*link = bpf_map__attach_struct_ops(map);
14158 		if (!*link) {
14159 			err = -errno;
14160 			pr_warn("map '%s': failed to auto-attach: %s\n",
14161 				bpf_map__name(map), errstr(err));
14162 			return libbpf_err(err);
14163 		}
14164 	}
14165 
14166 	return 0;
14167 }
14168 
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)14169 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14170 {
14171 	int i;
14172 
14173 	for (i = 0; i < s->prog_cnt; i++) {
14174 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14175 		struct bpf_link **link = prog_skel->link;
14176 
14177 		bpf_link__destroy(*link);
14178 		*link = NULL;
14179 	}
14180 
14181 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14182 		return;
14183 
14184 	for (i = 0; i < s->map_cnt; i++) {
14185 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14186 		struct bpf_link **link = map_skel->link;
14187 
14188 		if (link) {
14189 			bpf_link__destroy(*link);
14190 			*link = NULL;
14191 		}
14192 	}
14193 }
14194 
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)14195 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14196 {
14197 	if (!s)
14198 		return;
14199 
14200 	bpf_object__detach_skeleton(s);
14201 	if (s->obj)
14202 		bpf_object__close(*s->obj);
14203 	free(s->maps);
14204 	free(s->progs);
14205 	free(s);
14206 }
14207