xref: /linux/tools/lib/bpf/libbpf.c (revision ee88bddf7f2f5d1f1da87dd7bedc734048b70e88)
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 	struct bpf_map *arena_map;
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 
1521 	obj->kern_version = get_kernel_version();
1522 	obj->state  = OBJ_OPEN;
1523 
1524 	return obj;
1525 }
1526 
bpf_object__elf_finish(struct bpf_object * obj)1527 static void bpf_object__elf_finish(struct bpf_object *obj)
1528 {
1529 	if (!obj->efile.elf)
1530 		return;
1531 
1532 	elf_end(obj->efile.elf);
1533 	obj->efile.elf = NULL;
1534 	obj->efile.ehdr = NULL;
1535 	obj->efile.symbols = NULL;
1536 	obj->efile.arena_data = NULL;
1537 
1538 	zfree(&obj->efile.secs);
1539 	obj->efile.sec_cnt = 0;
1540 	zclose(obj->efile.fd);
1541 	obj->efile.obj_buf = NULL;
1542 	obj->efile.obj_buf_sz = 0;
1543 }
1544 
bpf_object__elf_init(struct bpf_object * obj)1545 static int bpf_object__elf_init(struct bpf_object *obj)
1546 {
1547 	Elf64_Ehdr *ehdr;
1548 	int err = 0;
1549 	Elf *elf;
1550 
1551 	if (obj->efile.elf) {
1552 		pr_warn("elf: init internal error\n");
1553 		return -LIBBPF_ERRNO__LIBELF;
1554 	}
1555 
1556 	if (obj->efile.obj_buf_sz > 0) {
1557 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1558 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1559 	} else {
1560 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1561 		if (obj->efile.fd < 0) {
1562 			err = -errno;
1563 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1564 			return err;
1565 		}
1566 
1567 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1568 	}
1569 
1570 	if (!elf) {
1571 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1572 		err = -LIBBPF_ERRNO__LIBELF;
1573 		goto errout;
1574 	}
1575 
1576 	obj->efile.elf = elf;
1577 
1578 	if (elf_kind(elf) != ELF_K_ELF) {
1579 		err = -LIBBPF_ERRNO__FORMAT;
1580 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1581 		goto errout;
1582 	}
1583 
1584 	if (gelf_getclass(elf) != ELFCLASS64) {
1585 		err = -LIBBPF_ERRNO__FORMAT;
1586 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1587 		goto errout;
1588 	}
1589 
1590 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1591 	if (!obj->efile.ehdr) {
1592 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1593 		err = -LIBBPF_ERRNO__FORMAT;
1594 		goto errout;
1595 	}
1596 
1597 	/* Validate ELF object endianness... */
1598 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1599 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1600 		err = -LIBBPF_ERRNO__ENDIAN;
1601 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1602 		goto errout;
1603 	}
1604 	/* and save after bpf_object_open() frees ELF data */
1605 	obj->byteorder = ehdr->e_ident[EI_DATA];
1606 
1607 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1608 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1609 			obj->path, elf_errmsg(-1));
1610 		err = -LIBBPF_ERRNO__FORMAT;
1611 		goto errout;
1612 	}
1613 
1614 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1615 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1616 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1617 			obj->path, elf_errmsg(-1));
1618 		err = -LIBBPF_ERRNO__FORMAT;
1619 		goto errout;
1620 	}
1621 
1622 	/* Old LLVM set e_machine to EM_NONE */
1623 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1624 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1625 		err = -LIBBPF_ERRNO__FORMAT;
1626 		goto errout;
1627 	}
1628 
1629 	return 0;
1630 errout:
1631 	bpf_object__elf_finish(obj);
1632 	return err;
1633 }
1634 
is_native_endianness(struct bpf_object * obj)1635 static bool is_native_endianness(struct bpf_object *obj)
1636 {
1637 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1638 	return obj->byteorder == ELFDATA2LSB;
1639 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1640 	return obj->byteorder == ELFDATA2MSB;
1641 #else
1642 # error "Unrecognized __BYTE_ORDER__"
1643 #endif
1644 }
1645 
1646 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1647 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1648 {
1649 	if (!data) {
1650 		pr_warn("invalid license section in %s\n", obj->path);
1651 		return -LIBBPF_ERRNO__FORMAT;
1652 	}
1653 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1654 	 * go over allowed ELF data section buffer
1655 	 */
1656 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1657 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1658 	return 0;
1659 }
1660 
1661 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1662 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1663 {
1664 	__u32 kver;
1665 
1666 	if (!data || size != sizeof(kver)) {
1667 		pr_warn("invalid kver section in %s\n", obj->path);
1668 		return -LIBBPF_ERRNO__FORMAT;
1669 	}
1670 	memcpy(&kver, data, sizeof(kver));
1671 	obj->kern_version = kver;
1672 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1673 	return 0;
1674 }
1675 
bpf_map_type__is_map_in_map(enum bpf_map_type type)1676 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1677 {
1678 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1679 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1680 		return true;
1681 	return false;
1682 }
1683 
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1684 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1685 {
1686 	Elf_Data *data;
1687 	Elf_Scn *scn;
1688 
1689 	if (!name)
1690 		return -EINVAL;
1691 
1692 	scn = elf_sec_by_name(obj, name);
1693 	data = elf_sec_data(obj, scn);
1694 	if (data) {
1695 		*size = data->d_size;
1696 		return 0; /* found it */
1697 	}
1698 
1699 	return -ENOENT;
1700 }
1701 
find_elf_var_sym(const struct bpf_object * obj,const char * name)1702 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1703 {
1704 	Elf_Data *symbols = obj->efile.symbols;
1705 	const char *sname;
1706 	size_t si;
1707 
1708 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1709 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1710 
1711 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1712 			continue;
1713 
1714 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1715 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1716 			continue;
1717 
1718 		sname = elf_sym_str(obj, sym->st_name);
1719 		if (!sname) {
1720 			pr_warn("failed to get sym name string for var %s\n", name);
1721 			return ERR_PTR(-EIO);
1722 		}
1723 		if (strcmp(name, sname) == 0)
1724 			return sym;
1725 	}
1726 
1727 	return ERR_PTR(-ENOENT);
1728 }
1729 
1730 #ifndef MFD_CLOEXEC
1731 #define MFD_CLOEXEC 0x0001U
1732 #endif
1733 #ifndef MFD_NOEXEC_SEAL
1734 #define MFD_NOEXEC_SEAL 0x0008U
1735 #endif
1736 
create_placeholder_fd(void)1737 static int create_placeholder_fd(void)
1738 {
1739 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1740 	const char *name = "libbpf-placeholder-fd";
1741 	int fd;
1742 
1743 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1744 	if (fd >= 0)
1745 		return fd;
1746 	else if (errno != EINVAL)
1747 		return -errno;
1748 
1749 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1750 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1751 	if (fd < 0)
1752 		return -errno;
1753 	return fd;
1754 }
1755 
bpf_object__add_map(struct bpf_object * obj)1756 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1757 {
1758 	struct bpf_map *map;
1759 	int err;
1760 
1761 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1762 				sizeof(*obj->maps), obj->nr_maps + 1);
1763 	if (err)
1764 		return ERR_PTR(err);
1765 
1766 	map = &obj->maps[obj->nr_maps++];
1767 	map->obj = obj;
1768 	/* Preallocate map FD without actually creating BPF map just yet.
1769 	 * These map FD "placeholders" will be reused later without changing
1770 	 * FD value when map is actually created in the kernel.
1771 	 *
1772 	 * This is useful to be able to perform BPF program relocations
1773 	 * without having to create BPF maps before that step. This allows us
1774 	 * to finalize and load BTF very late in BPF object's loading phase,
1775 	 * right before BPF maps have to be created and BPF programs have to
1776 	 * be loaded. By having these map FD placeholders we can perform all
1777 	 * the sanitizations, relocations, and any other adjustments before we
1778 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1779 	 */
1780 	map->fd = create_placeholder_fd();
1781 	if (map->fd < 0)
1782 		return ERR_PTR(map->fd);
1783 	map->inner_map_fd = -1;
1784 	map->autocreate = true;
1785 
1786 	return map;
1787 }
1788 
array_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1789 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1790 {
1791 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1792 	size_t map_sz;
1793 
1794 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1795 	map_sz = roundup(map_sz, page_sz);
1796 	return map_sz;
1797 }
1798 
bpf_map_mmap_sz(const struct bpf_map * map)1799 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1800 {
1801 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1802 
1803 	switch (map->def.type) {
1804 	case BPF_MAP_TYPE_ARRAY:
1805 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1806 	case BPF_MAP_TYPE_ARENA:
1807 		return page_sz * map->def.max_entries;
1808 	default:
1809 		return 0; /* not supported */
1810 	}
1811 }
1812 
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1813 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1814 {
1815 	void *mmaped;
1816 
1817 	if (!map->mmaped)
1818 		return -EINVAL;
1819 
1820 	if (old_sz == new_sz)
1821 		return 0;
1822 
1823 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1824 	if (mmaped == MAP_FAILED)
1825 		return -errno;
1826 
1827 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1828 	munmap(map->mmaped, old_sz);
1829 	map->mmaped = mmaped;
1830 	return 0;
1831 }
1832 
internal_map_name(struct bpf_object * obj,const char * real_name)1833 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1834 {
1835 	char map_name[BPF_OBJ_NAME_LEN], *p;
1836 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1837 
1838 	/* This is one of the more confusing parts of libbpf for various
1839 	 * reasons, some of which are historical. The original idea for naming
1840 	 * internal names was to include as much of BPF object name prefix as
1841 	 * possible, so that it can be distinguished from similar internal
1842 	 * maps of a different BPF object.
1843 	 * As an example, let's say we have bpf_object named 'my_object_name'
1844 	 * and internal map corresponding to '.rodata' ELF section. The final
1845 	 * map name advertised to user and to the kernel will be
1846 	 * 'my_objec.rodata', taking first 8 characters of object name and
1847 	 * entire 7 characters of '.rodata'.
1848 	 * Somewhat confusingly, if internal map ELF section name is shorter
1849 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1850 	 * for the suffix, even though we only have 4 actual characters, and
1851 	 * resulting map will be called 'my_objec.bss', not even using all 15
1852 	 * characters allowed by the kernel. Oh well, at least the truncated
1853 	 * object name is somewhat consistent in this case. But if the map
1854 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1855 	 * (8 chars) and thus will be left with only first 7 characters of the
1856 	 * object name ('my_obje'). Happy guessing, user, that the final map
1857 	 * name will be "my_obje.kconfig".
1858 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1859 	 * and .data.* data sections, it's possible that ELF section name is
1860 	 * longer than allowed 15 chars, so we now need to be careful to take
1861 	 * only up to 15 first characters of ELF name, taking no BPF object
1862 	 * name characters at all. So '.rodata.abracadabra' will result in
1863 	 * '.rodata.abracad' kernel and user-visible name.
1864 	 * We need to keep this convoluted logic intact for .data, .bss and
1865 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1866 	 * maps we use their ELF names as is, not prepending bpf_object name
1867 	 * in front. We still need to truncate them to 15 characters for the
1868 	 * kernel. Full name can be recovered for such maps by using DATASEC
1869 	 * BTF type associated with such map's value type, though.
1870 	 */
1871 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1872 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1873 
1874 	/* if there are two or more dots in map name, it's a custom dot map */
1875 	if (strchr(real_name + 1, '.') != NULL)
1876 		pfx_len = 0;
1877 	else
1878 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1879 
1880 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1881 		 sfx_len, real_name);
1882 
1883 	/* sanities map name to characters allowed by kernel */
1884 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1885 		if (!isalnum(*p) && *p != '_' && *p != '.')
1886 			*p = '_';
1887 
1888 	return strdup(map_name);
1889 }
1890 
1891 static int
1892 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1893 
1894 /* Internal BPF map is mmap()'able only if at least one of corresponding
1895  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1896  * variable and it's not marked as __hidden (which turns it into, effectively,
1897  * a STATIC variable).
1898  */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1899 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1900 {
1901 	const struct btf_type *t, *vt;
1902 	struct btf_var_secinfo *vsi;
1903 	int i, n;
1904 
1905 	if (!map->btf_value_type_id)
1906 		return false;
1907 
1908 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1909 	if (!btf_is_datasec(t))
1910 		return false;
1911 
1912 	vsi = btf_var_secinfos(t);
1913 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1914 		vt = btf__type_by_id(obj->btf, vsi->type);
1915 		if (!btf_is_var(vt))
1916 			continue;
1917 
1918 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1919 			return true;
1920 	}
1921 
1922 	return false;
1923 }
1924 
1925 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)1926 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1927 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1928 {
1929 	struct bpf_map_def *def;
1930 	struct bpf_map *map;
1931 	size_t mmap_sz;
1932 	int err;
1933 
1934 	map = bpf_object__add_map(obj);
1935 	if (IS_ERR(map))
1936 		return PTR_ERR(map);
1937 
1938 	map->libbpf_type = type;
1939 	map->sec_idx = sec_idx;
1940 	map->sec_offset = 0;
1941 	map->real_name = strdup(real_name);
1942 	map->name = internal_map_name(obj, real_name);
1943 	if (!map->real_name || !map->name) {
1944 		zfree(&map->real_name);
1945 		zfree(&map->name);
1946 		return -ENOMEM;
1947 	}
1948 
1949 	def = &map->def;
1950 	def->type = BPF_MAP_TYPE_ARRAY;
1951 	def->key_size = sizeof(int);
1952 	def->value_size = data_sz;
1953 	def->max_entries = 1;
1954 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1955 		? BPF_F_RDONLY_PROG : 0;
1956 
1957 	/* failures are fine because of maps like .rodata.str1.1 */
1958 	(void) map_fill_btf_type_info(obj, map);
1959 
1960 	if (map_is_mmapable(obj, map))
1961 		def->map_flags |= BPF_F_MMAPABLE;
1962 
1963 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1964 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1965 
1966 	mmap_sz = bpf_map_mmap_sz(map);
1967 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1968 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1969 	if (map->mmaped == MAP_FAILED) {
1970 		err = -errno;
1971 		map->mmaped = NULL;
1972 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
1973 		zfree(&map->real_name);
1974 		zfree(&map->name);
1975 		return err;
1976 	}
1977 
1978 	if (data)
1979 		memcpy(map->mmaped, data, data_sz);
1980 
1981 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1982 	return 0;
1983 }
1984 
bpf_object__init_global_data_maps(struct bpf_object * obj)1985 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1986 {
1987 	struct elf_sec_desc *sec_desc;
1988 	const char *sec_name;
1989 	int err = 0, sec_idx;
1990 
1991 	/*
1992 	 * Populate obj->maps with libbpf internal maps.
1993 	 */
1994 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1995 		sec_desc = &obj->efile.secs[sec_idx];
1996 
1997 		/* Skip recognized sections with size 0. */
1998 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1999 			continue;
2000 
2001 		switch (sec_desc->sec_type) {
2002 		case SEC_DATA:
2003 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2004 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2005 							    sec_name, sec_idx,
2006 							    sec_desc->data->d_buf,
2007 							    sec_desc->data->d_size);
2008 			break;
2009 		case SEC_RODATA:
2010 			obj->has_rodata = true;
2011 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2012 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2013 							    sec_name, sec_idx,
2014 							    sec_desc->data->d_buf,
2015 							    sec_desc->data->d_size);
2016 			break;
2017 		case SEC_BSS:
2018 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2019 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2020 							    sec_name, sec_idx,
2021 							    NULL,
2022 							    sec_desc->data->d_size);
2023 			break;
2024 		default:
2025 			/* skip */
2026 			break;
2027 		}
2028 		if (err)
2029 			return err;
2030 	}
2031 	return 0;
2032 }
2033 
2034 
find_extern_by_name(const struct bpf_object * obj,const void * name)2035 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2036 					       const void *name)
2037 {
2038 	int i;
2039 
2040 	for (i = 0; i < obj->nr_extern; i++) {
2041 		if (strcmp(obj->externs[i].name, name) == 0)
2042 			return &obj->externs[i];
2043 	}
2044 	return NULL;
2045 }
2046 
find_extern_by_name_with_len(const struct bpf_object * obj,const void * name,int len)2047 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2048 							const void *name, int len)
2049 {
2050 	const char *ext_name;
2051 	int i;
2052 
2053 	for (i = 0; i < obj->nr_extern; i++) {
2054 		ext_name = obj->externs[i].name;
2055 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2056 			return &obj->externs[i];
2057 	}
2058 	return NULL;
2059 }
2060 
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)2061 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2062 			      char value)
2063 {
2064 	switch (ext->kcfg.type) {
2065 	case KCFG_BOOL:
2066 		if (value == 'm') {
2067 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2068 				ext->name, value);
2069 			return -EINVAL;
2070 		}
2071 		*(bool *)ext_val = value == 'y' ? true : false;
2072 		break;
2073 	case KCFG_TRISTATE:
2074 		if (value == 'y')
2075 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2076 		else if (value == 'm')
2077 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2078 		else /* value == 'n' */
2079 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2080 		break;
2081 	case KCFG_CHAR:
2082 		*(char *)ext_val = value;
2083 		break;
2084 	case KCFG_UNKNOWN:
2085 	case KCFG_INT:
2086 	case KCFG_CHAR_ARR:
2087 	default:
2088 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2089 			ext->name, value);
2090 		return -EINVAL;
2091 	}
2092 	ext->is_set = true;
2093 	return 0;
2094 }
2095 
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)2096 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2097 			      const char *value)
2098 {
2099 	size_t len;
2100 
2101 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2102 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2103 			ext->name, value);
2104 		return -EINVAL;
2105 	}
2106 
2107 	len = strlen(value);
2108 	if (len < 2 || value[len - 1] != '"') {
2109 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2110 			ext->name, value);
2111 		return -EINVAL;
2112 	}
2113 
2114 	/* strip quotes */
2115 	len -= 2;
2116 	if (len >= ext->kcfg.sz) {
2117 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2118 			ext->name, value, len, ext->kcfg.sz - 1);
2119 		len = ext->kcfg.sz - 1;
2120 	}
2121 	memcpy(ext_val, value + 1, len);
2122 	ext_val[len] = '\0';
2123 	ext->is_set = true;
2124 	return 0;
2125 }
2126 
parse_u64(const char * value,__u64 * res)2127 static int parse_u64(const char *value, __u64 *res)
2128 {
2129 	char *value_end;
2130 	int err;
2131 
2132 	errno = 0;
2133 	*res = strtoull(value, &value_end, 0);
2134 	if (errno) {
2135 		err = -errno;
2136 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2137 		return err;
2138 	}
2139 	if (*value_end) {
2140 		pr_warn("failed to parse '%s' as integer completely\n", value);
2141 		return -EINVAL;
2142 	}
2143 	return 0;
2144 }
2145 
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)2146 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2147 {
2148 	int bit_sz = ext->kcfg.sz * 8;
2149 
2150 	if (ext->kcfg.sz == 8)
2151 		return true;
2152 
2153 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2154 	 * bytes size without any loss of information. If the target integer
2155 	 * is signed, we rely on the following limits of integer type of
2156 	 * Y bits and subsequent transformation:
2157 	 *
2158 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2159 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2160 	 *            0 <= X + 2^(Y-1) <  2^Y
2161 	 *
2162 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2163 	 *  zero.
2164 	 */
2165 	if (ext->kcfg.is_signed)
2166 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2167 	else
2168 		return (v >> bit_sz) == 0;
2169 }
2170 
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)2171 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2172 			      __u64 value)
2173 {
2174 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2175 	    ext->kcfg.type != KCFG_BOOL) {
2176 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2177 			ext->name, (unsigned long long)value);
2178 		return -EINVAL;
2179 	}
2180 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2181 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2182 			ext->name, (unsigned long long)value);
2183 		return -EINVAL;
2184 
2185 	}
2186 	if (!is_kcfg_value_in_range(ext, value)) {
2187 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2188 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2189 		return -ERANGE;
2190 	}
2191 	switch (ext->kcfg.sz) {
2192 	case 1:
2193 		*(__u8 *)ext_val = value;
2194 		break;
2195 	case 2:
2196 		*(__u16 *)ext_val = value;
2197 		break;
2198 	case 4:
2199 		*(__u32 *)ext_val = value;
2200 		break;
2201 	case 8:
2202 		*(__u64 *)ext_val = value;
2203 		break;
2204 	default:
2205 		return -EINVAL;
2206 	}
2207 	ext->is_set = true;
2208 	return 0;
2209 }
2210 
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)2211 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2212 					    char *buf, void *data)
2213 {
2214 	struct extern_desc *ext;
2215 	char *sep, *value;
2216 	int len, err = 0;
2217 	void *ext_val;
2218 	__u64 num;
2219 
2220 	if (!str_has_pfx(buf, "CONFIG_"))
2221 		return 0;
2222 
2223 	sep = strchr(buf, '=');
2224 	if (!sep) {
2225 		pr_warn("failed to parse '%s': no separator\n", buf);
2226 		return -EINVAL;
2227 	}
2228 
2229 	/* Trim ending '\n' */
2230 	len = strlen(buf);
2231 	if (buf[len - 1] == '\n')
2232 		buf[len - 1] = '\0';
2233 	/* Split on '=' and ensure that a value is present. */
2234 	*sep = '\0';
2235 	if (!sep[1]) {
2236 		*sep = '=';
2237 		pr_warn("failed to parse '%s': no value\n", buf);
2238 		return -EINVAL;
2239 	}
2240 
2241 	ext = find_extern_by_name(obj, buf);
2242 	if (!ext || ext->is_set)
2243 		return 0;
2244 
2245 	ext_val = data + ext->kcfg.data_off;
2246 	value = sep + 1;
2247 
2248 	switch (*value) {
2249 	case 'y': case 'n': case 'm':
2250 		err = set_kcfg_value_tri(ext, ext_val, *value);
2251 		break;
2252 	case '"':
2253 		err = set_kcfg_value_str(ext, ext_val, value);
2254 		break;
2255 	default:
2256 		/* assume integer */
2257 		err = parse_u64(value, &num);
2258 		if (err) {
2259 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2260 			return err;
2261 		}
2262 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2263 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2264 			return -EINVAL;
2265 		}
2266 		err = set_kcfg_value_num(ext, ext_val, num);
2267 		break;
2268 	}
2269 	if (err)
2270 		return err;
2271 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2272 	return 0;
2273 }
2274 
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)2275 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2276 {
2277 	char buf[PATH_MAX];
2278 	struct utsname uts;
2279 	int len, err = 0;
2280 	gzFile file;
2281 
2282 	uname(&uts);
2283 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2284 	if (len < 0)
2285 		return -EINVAL;
2286 	else if (len >= PATH_MAX)
2287 		return -ENAMETOOLONG;
2288 
2289 	/* gzopen also accepts uncompressed files. */
2290 	file = gzopen(buf, "re");
2291 	if (!file)
2292 		file = gzopen("/proc/config.gz", "re");
2293 
2294 	if (!file) {
2295 		pr_warn("failed to open system Kconfig\n");
2296 		return -ENOENT;
2297 	}
2298 
2299 	while (gzgets(file, buf, sizeof(buf))) {
2300 		err = bpf_object__process_kconfig_line(obj, buf, data);
2301 		if (err) {
2302 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2303 				buf, errstr(err));
2304 			goto out;
2305 		}
2306 	}
2307 
2308 out:
2309 	gzclose(file);
2310 	return err;
2311 }
2312 
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2313 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2314 					const char *config, void *data)
2315 {
2316 	char buf[PATH_MAX];
2317 	int err = 0;
2318 	FILE *file;
2319 
2320 	file = fmemopen((void *)config, strlen(config), "r");
2321 	if (!file) {
2322 		err = -errno;
2323 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2324 		return err;
2325 	}
2326 
2327 	while (fgets(buf, sizeof(buf), file)) {
2328 		err = bpf_object__process_kconfig_line(obj, buf, data);
2329 		if (err) {
2330 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2331 				buf, errstr(err));
2332 			break;
2333 		}
2334 	}
2335 
2336 	fclose(file);
2337 	return err;
2338 }
2339 
bpf_object__init_kconfig_map(struct bpf_object * obj)2340 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2341 {
2342 	struct extern_desc *last_ext = NULL, *ext;
2343 	size_t map_sz;
2344 	int i, err;
2345 
2346 	for (i = 0; i < obj->nr_extern; i++) {
2347 		ext = &obj->externs[i];
2348 		if (ext->type == EXT_KCFG)
2349 			last_ext = ext;
2350 	}
2351 
2352 	if (!last_ext)
2353 		return 0;
2354 
2355 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2356 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2357 					    ".kconfig", obj->efile.symbols_shndx,
2358 					    NULL, map_sz);
2359 	if (err)
2360 		return err;
2361 
2362 	obj->kconfig_map_idx = obj->nr_maps - 1;
2363 
2364 	return 0;
2365 }
2366 
2367 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2368 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2369 {
2370 	const struct btf_type *t = btf__type_by_id(btf, id);
2371 
2372 	if (res_id)
2373 		*res_id = id;
2374 
2375 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2376 		if (res_id)
2377 			*res_id = t->type;
2378 		t = btf__type_by_id(btf, t->type);
2379 	}
2380 
2381 	return t;
2382 }
2383 
2384 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2385 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2386 {
2387 	const struct btf_type *t;
2388 
2389 	t = skip_mods_and_typedefs(btf, id, NULL);
2390 	if (!btf_is_ptr(t))
2391 		return NULL;
2392 
2393 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2394 
2395 	return btf_is_func_proto(t) ? t : NULL;
2396 }
2397 
__btf_kind_str(__u16 kind)2398 static const char *__btf_kind_str(__u16 kind)
2399 {
2400 	switch (kind) {
2401 	case BTF_KIND_UNKN: return "void";
2402 	case BTF_KIND_INT: return "int";
2403 	case BTF_KIND_PTR: return "ptr";
2404 	case BTF_KIND_ARRAY: return "array";
2405 	case BTF_KIND_STRUCT: return "struct";
2406 	case BTF_KIND_UNION: return "union";
2407 	case BTF_KIND_ENUM: return "enum";
2408 	case BTF_KIND_FWD: return "fwd";
2409 	case BTF_KIND_TYPEDEF: return "typedef";
2410 	case BTF_KIND_VOLATILE: return "volatile";
2411 	case BTF_KIND_CONST: return "const";
2412 	case BTF_KIND_RESTRICT: return "restrict";
2413 	case BTF_KIND_FUNC: return "func";
2414 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2415 	case BTF_KIND_VAR: return "var";
2416 	case BTF_KIND_DATASEC: return "datasec";
2417 	case BTF_KIND_FLOAT: return "float";
2418 	case BTF_KIND_DECL_TAG: return "decl_tag";
2419 	case BTF_KIND_TYPE_TAG: return "type_tag";
2420 	case BTF_KIND_ENUM64: return "enum64";
2421 	default: return "unknown";
2422 	}
2423 }
2424 
btf_kind_str(const struct btf_type * t)2425 const char *btf_kind_str(const struct btf_type *t)
2426 {
2427 	return __btf_kind_str(btf_kind(t));
2428 }
2429 
2430 /*
2431  * Fetch integer attribute of BTF map definition. Such attributes are
2432  * represented using a pointer to an array, in which dimensionality of array
2433  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2434  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2435  * type definition, while using only sizeof(void *) space in ELF data section.
2436  */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2437 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2438 			      const struct btf_member *m, __u32 *res)
2439 {
2440 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2441 	const char *name = btf__name_by_offset(btf, m->name_off);
2442 	const struct btf_array *arr_info;
2443 	const struct btf_type *arr_t;
2444 
2445 	if (!btf_is_ptr(t)) {
2446 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2447 			map_name, name, btf_kind_str(t));
2448 		return false;
2449 	}
2450 
2451 	arr_t = btf__type_by_id(btf, t->type);
2452 	if (!arr_t) {
2453 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2454 			map_name, name, t->type);
2455 		return false;
2456 	}
2457 	if (!btf_is_array(arr_t)) {
2458 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2459 			map_name, name, btf_kind_str(arr_t));
2460 		return false;
2461 	}
2462 	arr_info = btf_array(arr_t);
2463 	*res = arr_info->nelems;
2464 	return true;
2465 }
2466 
get_map_field_long(const char * map_name,const struct btf * btf,const struct btf_member * m,__u64 * res)2467 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2468 			       const struct btf_member *m, __u64 *res)
2469 {
2470 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2471 	const char *name = btf__name_by_offset(btf, m->name_off);
2472 
2473 	if (btf_is_ptr(t)) {
2474 		__u32 res32;
2475 		bool ret;
2476 
2477 		ret = get_map_field_int(map_name, btf, m, &res32);
2478 		if (ret)
2479 			*res = (__u64)res32;
2480 		return ret;
2481 	}
2482 
2483 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2484 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2485 			map_name, name, btf_kind_str(t));
2486 		return false;
2487 	}
2488 
2489 	if (btf_vlen(t) != 1) {
2490 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2491 			map_name, name);
2492 		return false;
2493 	}
2494 
2495 	if (btf_is_enum(t)) {
2496 		const struct btf_enum *e = btf_enum(t);
2497 
2498 		*res = e->val;
2499 	} else {
2500 		const struct btf_enum64 *e = btf_enum64(t);
2501 
2502 		*res = btf_enum64_value(e);
2503 	}
2504 	return true;
2505 }
2506 
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2507 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2508 {
2509 	int len;
2510 
2511 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2512 	if (len < 0)
2513 		return -EINVAL;
2514 	if (len >= buf_sz)
2515 		return -ENAMETOOLONG;
2516 
2517 	return 0;
2518 }
2519 
build_map_pin_path(struct bpf_map * map,const char * path)2520 static int build_map_pin_path(struct bpf_map *map, const char *path)
2521 {
2522 	char buf[PATH_MAX];
2523 	int err;
2524 
2525 	if (!path)
2526 		path = BPF_FS_DEFAULT_PATH;
2527 
2528 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2529 	if (err)
2530 		return err;
2531 
2532 	return bpf_map__set_pin_path(map, buf);
2533 }
2534 
2535 /* should match definition in bpf_helpers.h */
2536 enum libbpf_pin_type {
2537 	LIBBPF_PIN_NONE,
2538 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2539 	LIBBPF_PIN_BY_NAME,
2540 };
2541 
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)2542 int parse_btf_map_def(const char *map_name, struct btf *btf,
2543 		      const struct btf_type *def_t, bool strict,
2544 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2545 {
2546 	const struct btf_type *t;
2547 	const struct btf_member *m;
2548 	bool is_inner = inner_def == NULL;
2549 	int vlen, i;
2550 
2551 	vlen = btf_vlen(def_t);
2552 	m = btf_members(def_t);
2553 	for (i = 0; i < vlen; i++, m++) {
2554 		const char *name = btf__name_by_offset(btf, m->name_off);
2555 
2556 		if (!name) {
2557 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2558 			return -EINVAL;
2559 		}
2560 		if (strcmp(name, "type") == 0) {
2561 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2562 				return -EINVAL;
2563 			map_def->parts |= MAP_DEF_MAP_TYPE;
2564 		} else if (strcmp(name, "max_entries") == 0) {
2565 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2566 				return -EINVAL;
2567 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2568 		} else if (strcmp(name, "map_flags") == 0) {
2569 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2570 				return -EINVAL;
2571 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2572 		} else if (strcmp(name, "numa_node") == 0) {
2573 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2574 				return -EINVAL;
2575 			map_def->parts |= MAP_DEF_NUMA_NODE;
2576 		} else if (strcmp(name, "key_size") == 0) {
2577 			__u32 sz;
2578 
2579 			if (!get_map_field_int(map_name, btf, m, &sz))
2580 				return -EINVAL;
2581 			if (map_def->key_size && map_def->key_size != sz) {
2582 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2583 					map_name, map_def->key_size, sz);
2584 				return -EINVAL;
2585 			}
2586 			map_def->key_size = sz;
2587 			map_def->parts |= MAP_DEF_KEY_SIZE;
2588 		} else if (strcmp(name, "key") == 0) {
2589 			__s64 sz;
2590 
2591 			t = btf__type_by_id(btf, m->type);
2592 			if (!t) {
2593 				pr_warn("map '%s': key type [%d] not found.\n",
2594 					map_name, m->type);
2595 				return -EINVAL;
2596 			}
2597 			if (!btf_is_ptr(t)) {
2598 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2599 					map_name, btf_kind_str(t));
2600 				return -EINVAL;
2601 			}
2602 			sz = btf__resolve_size(btf, t->type);
2603 			if (sz < 0) {
2604 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2605 					map_name, t->type, (ssize_t)sz);
2606 				return sz;
2607 			}
2608 			if (map_def->key_size && map_def->key_size != sz) {
2609 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2610 					map_name, map_def->key_size, (ssize_t)sz);
2611 				return -EINVAL;
2612 			}
2613 			map_def->key_size = sz;
2614 			map_def->key_type_id = t->type;
2615 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2616 		} else if (strcmp(name, "value_size") == 0) {
2617 			__u32 sz;
2618 
2619 			if (!get_map_field_int(map_name, btf, m, &sz))
2620 				return -EINVAL;
2621 			if (map_def->value_size && map_def->value_size != sz) {
2622 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2623 					map_name, map_def->value_size, sz);
2624 				return -EINVAL;
2625 			}
2626 			map_def->value_size = sz;
2627 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2628 		} else if (strcmp(name, "value") == 0) {
2629 			__s64 sz;
2630 
2631 			t = btf__type_by_id(btf, m->type);
2632 			if (!t) {
2633 				pr_warn("map '%s': value type [%d] not found.\n",
2634 					map_name, m->type);
2635 				return -EINVAL;
2636 			}
2637 			if (!btf_is_ptr(t)) {
2638 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2639 					map_name, btf_kind_str(t));
2640 				return -EINVAL;
2641 			}
2642 			sz = btf__resolve_size(btf, t->type);
2643 			if (sz < 0) {
2644 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2645 					map_name, t->type, (ssize_t)sz);
2646 				return sz;
2647 			}
2648 			if (map_def->value_size && map_def->value_size != sz) {
2649 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2650 					map_name, map_def->value_size, (ssize_t)sz);
2651 				return -EINVAL;
2652 			}
2653 			map_def->value_size = sz;
2654 			map_def->value_type_id = t->type;
2655 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2656 		}
2657 		else if (strcmp(name, "values") == 0) {
2658 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2659 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2660 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2661 			char inner_map_name[128];
2662 			int err;
2663 
2664 			if (is_inner) {
2665 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2666 					map_name);
2667 				return -ENOTSUP;
2668 			}
2669 			if (i != vlen - 1) {
2670 				pr_warn("map '%s': '%s' member should be last.\n",
2671 					map_name, name);
2672 				return -EINVAL;
2673 			}
2674 			if (!is_map_in_map && !is_prog_array) {
2675 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2676 					map_name);
2677 				return -ENOTSUP;
2678 			}
2679 			if (map_def->value_size && map_def->value_size != 4) {
2680 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2681 					map_name, map_def->value_size);
2682 				return -EINVAL;
2683 			}
2684 			map_def->value_size = 4;
2685 			t = btf__type_by_id(btf, m->type);
2686 			if (!t) {
2687 				pr_warn("map '%s': %s type [%d] not found.\n",
2688 					map_name, desc, m->type);
2689 				return -EINVAL;
2690 			}
2691 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2692 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2693 					map_name, desc);
2694 				return -EINVAL;
2695 			}
2696 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2697 			if (!btf_is_ptr(t)) {
2698 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2699 					map_name, desc, btf_kind_str(t));
2700 				return -EINVAL;
2701 			}
2702 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2703 			if (is_prog_array) {
2704 				if (!btf_is_func_proto(t)) {
2705 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2706 						map_name, btf_kind_str(t));
2707 					return -EINVAL;
2708 				}
2709 				continue;
2710 			}
2711 			if (!btf_is_struct(t)) {
2712 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2713 					map_name, btf_kind_str(t));
2714 				return -EINVAL;
2715 			}
2716 
2717 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2718 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2719 			if (err)
2720 				return err;
2721 
2722 			map_def->parts |= MAP_DEF_INNER_MAP;
2723 		} else if (strcmp(name, "pinning") == 0) {
2724 			__u32 val;
2725 
2726 			if (is_inner) {
2727 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2728 				return -EINVAL;
2729 			}
2730 			if (!get_map_field_int(map_name, btf, m, &val))
2731 				return -EINVAL;
2732 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2733 				pr_warn("map '%s': invalid pinning value %u.\n",
2734 					map_name, val);
2735 				return -EINVAL;
2736 			}
2737 			map_def->pinning = val;
2738 			map_def->parts |= MAP_DEF_PINNING;
2739 		} else if (strcmp(name, "map_extra") == 0) {
2740 			__u64 map_extra;
2741 
2742 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2743 				return -EINVAL;
2744 			map_def->map_extra = map_extra;
2745 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2746 		} else {
2747 			if (strict) {
2748 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2749 				return -ENOTSUP;
2750 			}
2751 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2752 		}
2753 	}
2754 
2755 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2756 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2757 		return -EINVAL;
2758 	}
2759 
2760 	return 0;
2761 }
2762 
adjust_ringbuf_sz(size_t sz)2763 static size_t adjust_ringbuf_sz(size_t sz)
2764 {
2765 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2766 	__u32 mul;
2767 
2768 	/* if user forgot to set any size, make sure they see error */
2769 	if (sz == 0)
2770 		return 0;
2771 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2772 	 * a power-of-2 multiple of kernel's page size. If user diligently
2773 	 * satisified these conditions, pass the size through.
2774 	 */
2775 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2776 		return sz;
2777 
2778 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2779 	 * user-set size to satisfy both user size request and kernel
2780 	 * requirements and substitute correct max_entries for map creation.
2781 	 */
2782 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2783 		if (mul * page_sz > sz)
2784 			return mul * page_sz;
2785 	}
2786 
2787 	/* if it's impossible to satisfy the conditions (i.e., user size is
2788 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2789 	 * page_size) then just return original size and let kernel reject it
2790 	 */
2791 	return sz;
2792 }
2793 
map_is_ringbuf(const struct bpf_map * map)2794 static bool map_is_ringbuf(const struct bpf_map *map)
2795 {
2796 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2797 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2798 }
2799 
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2800 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2801 {
2802 	map->def.type = def->map_type;
2803 	map->def.key_size = def->key_size;
2804 	map->def.value_size = def->value_size;
2805 	map->def.max_entries = def->max_entries;
2806 	map->def.map_flags = def->map_flags;
2807 	map->map_extra = def->map_extra;
2808 
2809 	map->numa_node = def->numa_node;
2810 	map->btf_key_type_id = def->key_type_id;
2811 	map->btf_value_type_id = def->value_type_id;
2812 
2813 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2814 	if (map_is_ringbuf(map))
2815 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2816 
2817 	if (def->parts & MAP_DEF_MAP_TYPE)
2818 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2819 
2820 	if (def->parts & MAP_DEF_KEY_TYPE)
2821 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2822 			 map->name, def->key_type_id, def->key_size);
2823 	else if (def->parts & MAP_DEF_KEY_SIZE)
2824 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2825 
2826 	if (def->parts & MAP_DEF_VALUE_TYPE)
2827 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2828 			 map->name, def->value_type_id, def->value_size);
2829 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2830 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2831 
2832 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2833 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2834 	if (def->parts & MAP_DEF_MAP_FLAGS)
2835 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2836 	if (def->parts & MAP_DEF_MAP_EXTRA)
2837 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2838 			 (unsigned long long)def->map_extra);
2839 	if (def->parts & MAP_DEF_PINNING)
2840 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2841 	if (def->parts & MAP_DEF_NUMA_NODE)
2842 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2843 
2844 	if (def->parts & MAP_DEF_INNER_MAP)
2845 		pr_debug("map '%s': found inner map definition.\n", map->name);
2846 }
2847 
btf_var_linkage_str(__u32 linkage)2848 static const char *btf_var_linkage_str(__u32 linkage)
2849 {
2850 	switch (linkage) {
2851 	case BTF_VAR_STATIC: return "static";
2852 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2853 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2854 	default: return "unknown";
2855 	}
2856 }
2857 
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)2858 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2859 					 const struct btf_type *sec,
2860 					 int var_idx, int sec_idx,
2861 					 const Elf_Data *data, bool strict,
2862 					 const char *pin_root_path)
2863 {
2864 	struct btf_map_def map_def = {}, inner_def = {};
2865 	const struct btf_type *var, *def;
2866 	const struct btf_var_secinfo *vi;
2867 	const struct btf_var *var_extra;
2868 	const char *map_name;
2869 	struct bpf_map *map;
2870 	int err;
2871 
2872 	vi = btf_var_secinfos(sec) + var_idx;
2873 	var = btf__type_by_id(obj->btf, vi->type);
2874 	var_extra = btf_var(var);
2875 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2876 
2877 	if (map_name == NULL || map_name[0] == '\0') {
2878 		pr_warn("map #%d: empty name.\n", var_idx);
2879 		return -EINVAL;
2880 	}
2881 	if ((__u64)vi->offset + vi->size > data->d_size) {
2882 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2883 		return -EINVAL;
2884 	}
2885 	if (!btf_is_var(var)) {
2886 		pr_warn("map '%s': unexpected var kind %s.\n",
2887 			map_name, btf_kind_str(var));
2888 		return -EINVAL;
2889 	}
2890 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2891 		pr_warn("map '%s': unsupported map linkage %s.\n",
2892 			map_name, btf_var_linkage_str(var_extra->linkage));
2893 		return -EOPNOTSUPP;
2894 	}
2895 
2896 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2897 	if (!btf_is_struct(def)) {
2898 		pr_warn("map '%s': unexpected def kind %s.\n",
2899 			map_name, btf_kind_str(var));
2900 		return -EINVAL;
2901 	}
2902 	if (def->size > vi->size) {
2903 		pr_warn("map '%s': invalid def size.\n", map_name);
2904 		return -EINVAL;
2905 	}
2906 
2907 	map = bpf_object__add_map(obj);
2908 	if (IS_ERR(map))
2909 		return PTR_ERR(map);
2910 	map->name = strdup(map_name);
2911 	if (!map->name) {
2912 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2913 		return -ENOMEM;
2914 	}
2915 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2916 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2917 	map->sec_idx = sec_idx;
2918 	map->sec_offset = vi->offset;
2919 	map->btf_var_idx = var_idx;
2920 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2921 		 map_name, map->sec_idx, map->sec_offset);
2922 
2923 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2924 	if (err)
2925 		return err;
2926 
2927 	fill_map_from_def(map, &map_def);
2928 
2929 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2930 		err = build_map_pin_path(map, pin_root_path);
2931 		if (err) {
2932 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2933 			return err;
2934 		}
2935 	}
2936 
2937 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2938 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2939 		if (!map->inner_map)
2940 			return -ENOMEM;
2941 		map->inner_map->fd = create_placeholder_fd();
2942 		if (map->inner_map->fd < 0)
2943 			return map->inner_map->fd;
2944 		map->inner_map->sec_idx = sec_idx;
2945 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2946 		if (!map->inner_map->name)
2947 			return -ENOMEM;
2948 		sprintf(map->inner_map->name, "%s.inner", map_name);
2949 
2950 		fill_map_from_def(map->inner_map, &inner_def);
2951 	}
2952 
2953 	err = map_fill_btf_type_info(obj, map);
2954 	if (err)
2955 		return err;
2956 
2957 	return 0;
2958 }
2959 
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)2960 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2961 			       const char *sec_name, int sec_idx,
2962 			       void *data, size_t data_sz)
2963 {
2964 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2965 	size_t mmap_sz;
2966 
2967 	mmap_sz = bpf_map_mmap_sz(obj->arena_map);
2968 	if (roundup(data_sz, page_sz) > mmap_sz) {
2969 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2970 			sec_name, mmap_sz, data_sz);
2971 		return -E2BIG;
2972 	}
2973 
2974 	obj->arena_data = malloc(data_sz);
2975 	if (!obj->arena_data)
2976 		return -ENOMEM;
2977 	memcpy(obj->arena_data, data, data_sz);
2978 	obj->arena_data_sz = data_sz;
2979 
2980 	/* make bpf_map__init_value() work for ARENA maps */
2981 	map->mmaped = obj->arena_data;
2982 
2983 	return 0;
2984 }
2985 
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2986 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2987 					  const char *pin_root_path)
2988 {
2989 	const struct btf_type *sec = NULL;
2990 	int nr_types, i, vlen, err;
2991 	const struct btf_type *t;
2992 	const char *name;
2993 	Elf_Data *data;
2994 	Elf_Scn *scn;
2995 
2996 	if (obj->efile.btf_maps_shndx < 0)
2997 		return 0;
2998 
2999 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3000 	data = elf_sec_data(obj, scn);
3001 	if (!scn || !data) {
3002 		pr_warn("elf: failed to get %s map definitions for %s\n",
3003 			MAPS_ELF_SEC, obj->path);
3004 		return -EINVAL;
3005 	}
3006 
3007 	nr_types = btf__type_cnt(obj->btf);
3008 	for (i = 1; i < nr_types; i++) {
3009 		t = btf__type_by_id(obj->btf, i);
3010 		if (!btf_is_datasec(t))
3011 			continue;
3012 		name = btf__name_by_offset(obj->btf, t->name_off);
3013 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3014 			sec = t;
3015 			obj->efile.btf_maps_sec_btf_id = i;
3016 			break;
3017 		}
3018 	}
3019 
3020 	if (!sec) {
3021 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3022 		return -ENOENT;
3023 	}
3024 
3025 	vlen = btf_vlen(sec);
3026 	for (i = 0; i < vlen; i++) {
3027 		err = bpf_object__init_user_btf_map(obj, sec, i,
3028 						    obj->efile.btf_maps_shndx,
3029 						    data, strict,
3030 						    pin_root_path);
3031 		if (err)
3032 			return err;
3033 	}
3034 
3035 	for (i = 0; i < obj->nr_maps; i++) {
3036 		struct bpf_map *map = &obj->maps[i];
3037 
3038 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3039 			continue;
3040 
3041 		if (obj->arena_map) {
3042 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3043 				map->name, obj->arena_map->name);
3044 			return -EINVAL;
3045 		}
3046 		obj->arena_map = map;
3047 
3048 		if (obj->efile.arena_data) {
3049 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3050 						  obj->efile.arena_data->d_buf,
3051 						  obj->efile.arena_data->d_size);
3052 			if (err)
3053 				return err;
3054 		}
3055 	}
3056 	if (obj->efile.arena_data && !obj->arena_map) {
3057 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3058 			ARENA_SEC);
3059 		return -ENOENT;
3060 	}
3061 
3062 	return 0;
3063 }
3064 
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)3065 static int bpf_object__init_maps(struct bpf_object *obj,
3066 				 const struct bpf_object_open_opts *opts)
3067 {
3068 	const char *pin_root_path;
3069 	bool strict;
3070 	int err = 0;
3071 
3072 	strict = !OPTS_GET(opts, relaxed_maps, false);
3073 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3074 
3075 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3076 	err = err ?: bpf_object__init_global_data_maps(obj);
3077 	err = err ?: bpf_object__init_kconfig_map(obj);
3078 	err = err ?: bpf_object_init_struct_ops(obj);
3079 
3080 	return err;
3081 }
3082 
section_have_execinstr(struct bpf_object * obj,int idx)3083 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3084 {
3085 	Elf64_Shdr *sh;
3086 
3087 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3088 	if (!sh)
3089 		return false;
3090 
3091 	return sh->sh_flags & SHF_EXECINSTR;
3092 }
3093 
starts_with_qmark(const char * s)3094 static bool starts_with_qmark(const char *s)
3095 {
3096 	return s && s[0] == '?';
3097 }
3098 
btf_needs_sanitization(struct bpf_object * obj)3099 static bool btf_needs_sanitization(struct bpf_object *obj)
3100 {
3101 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3102 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3103 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3104 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3105 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3106 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3107 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3108 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3109 
3110 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3111 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3112 }
3113 
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)3114 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3115 {
3116 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3117 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3118 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3119 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3120 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3121 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3122 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3123 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3124 	int enum64_placeholder_id = 0;
3125 	struct btf_type *t;
3126 	int i, j, vlen;
3127 
3128 	for (i = 1; i < btf__type_cnt(btf); i++) {
3129 		t = (struct btf_type *)btf__type_by_id(btf, i);
3130 
3131 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3132 			/* replace VAR/DECL_TAG with INT */
3133 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3134 			/*
3135 			 * using size = 1 is the safest choice, 4 will be too
3136 			 * big and cause kernel BTF validation failure if
3137 			 * original variable took less than 4 bytes
3138 			 */
3139 			t->size = 1;
3140 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3141 		} else if (!has_datasec && btf_is_datasec(t)) {
3142 			/* replace DATASEC with STRUCT */
3143 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3144 			struct btf_member *m = btf_members(t);
3145 			struct btf_type *vt;
3146 			char *name;
3147 
3148 			name = (char *)btf__name_by_offset(btf, t->name_off);
3149 			while (*name) {
3150 				if (*name == '.' || *name == '?')
3151 					*name = '_';
3152 				name++;
3153 			}
3154 
3155 			vlen = btf_vlen(t);
3156 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3157 			for (j = 0; j < vlen; j++, v++, m++) {
3158 				/* order of field assignments is important */
3159 				m->offset = v->offset * 8;
3160 				m->type = v->type;
3161 				/* preserve variable name as member name */
3162 				vt = (void *)btf__type_by_id(btf, v->type);
3163 				m->name_off = vt->name_off;
3164 			}
3165 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3166 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3167 			/* replace '?' prefix with '_' for DATASEC names */
3168 			char *name;
3169 
3170 			name = (char *)btf__name_by_offset(btf, t->name_off);
3171 			if (name[0] == '?')
3172 				name[0] = '_';
3173 		} else if (!has_func && btf_is_func_proto(t)) {
3174 			/* replace FUNC_PROTO with ENUM */
3175 			vlen = btf_vlen(t);
3176 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3177 			t->size = sizeof(__u32); /* kernel enforced */
3178 		} else if (!has_func && btf_is_func(t)) {
3179 			/* replace FUNC with TYPEDEF */
3180 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3181 		} else if (!has_func_global && btf_is_func(t)) {
3182 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3183 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3184 		} else if (!has_float && btf_is_float(t)) {
3185 			/* replace FLOAT with an equally-sized empty STRUCT;
3186 			 * since C compilers do not accept e.g. "float" as a
3187 			 * valid struct name, make it anonymous
3188 			 */
3189 			t->name_off = 0;
3190 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3191 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3192 			/* replace TYPE_TAG with a CONST */
3193 			t->name_off = 0;
3194 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3195 		} else if (!has_enum64 && btf_is_enum(t)) {
3196 			/* clear the kflag */
3197 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3198 		} else if (!has_enum64 && btf_is_enum64(t)) {
3199 			/* replace ENUM64 with a union */
3200 			struct btf_member *m;
3201 
3202 			if (enum64_placeholder_id == 0) {
3203 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3204 				if (enum64_placeholder_id < 0)
3205 					return enum64_placeholder_id;
3206 
3207 				t = (struct btf_type *)btf__type_by_id(btf, i);
3208 			}
3209 
3210 			m = btf_members(t);
3211 			vlen = btf_vlen(t);
3212 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3213 			for (j = 0; j < vlen; j++, m++) {
3214 				m->type = enum64_placeholder_id;
3215 				m->offset = 0;
3216 			}
3217 		}
3218 	}
3219 
3220 	return 0;
3221 }
3222 
libbpf_needs_btf(const struct bpf_object * obj)3223 static bool libbpf_needs_btf(const struct bpf_object *obj)
3224 {
3225 	return obj->efile.btf_maps_shndx >= 0 ||
3226 	       obj->efile.has_st_ops ||
3227 	       obj->nr_extern > 0;
3228 }
3229 
kernel_needs_btf(const struct bpf_object * obj)3230 static bool kernel_needs_btf(const struct bpf_object *obj)
3231 {
3232 	return obj->efile.has_st_ops;
3233 }
3234 
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)3235 static int bpf_object__init_btf(struct bpf_object *obj,
3236 				Elf_Data *btf_data,
3237 				Elf_Data *btf_ext_data)
3238 {
3239 	int err = -ENOENT;
3240 
3241 	if (btf_data) {
3242 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3243 		err = libbpf_get_error(obj->btf);
3244 		if (err) {
3245 			obj->btf = NULL;
3246 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3247 			goto out;
3248 		}
3249 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3250 		btf__set_pointer_size(obj->btf, 8);
3251 	}
3252 	if (btf_ext_data) {
3253 		struct btf_ext_info *ext_segs[3];
3254 		int seg_num, sec_num;
3255 
3256 		if (!obj->btf) {
3257 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3258 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3259 			goto out;
3260 		}
3261 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3262 		err = libbpf_get_error(obj->btf_ext);
3263 		if (err) {
3264 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3265 				BTF_EXT_ELF_SEC, errstr(err));
3266 			obj->btf_ext = NULL;
3267 			goto out;
3268 		}
3269 
3270 		/* setup .BTF.ext to ELF section mapping */
3271 		ext_segs[0] = &obj->btf_ext->func_info;
3272 		ext_segs[1] = &obj->btf_ext->line_info;
3273 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3274 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3275 			struct btf_ext_info *seg = ext_segs[seg_num];
3276 			const struct btf_ext_info_sec *sec;
3277 			const char *sec_name;
3278 			Elf_Scn *scn;
3279 
3280 			if (seg->sec_cnt == 0)
3281 				continue;
3282 
3283 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3284 			if (!seg->sec_idxs) {
3285 				err = -ENOMEM;
3286 				goto out;
3287 			}
3288 
3289 			sec_num = 0;
3290 			for_each_btf_ext_sec(seg, sec) {
3291 				/* preventively increment index to avoid doing
3292 				 * this before every continue below
3293 				 */
3294 				sec_num++;
3295 
3296 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3297 				if (str_is_empty(sec_name))
3298 					continue;
3299 				scn = elf_sec_by_name(obj, sec_name);
3300 				if (!scn)
3301 					continue;
3302 
3303 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3304 			}
3305 		}
3306 	}
3307 out:
3308 	if (err && libbpf_needs_btf(obj)) {
3309 		pr_warn("BTF is required, but is missing or corrupted.\n");
3310 		return err;
3311 	}
3312 	return 0;
3313 }
3314 
compare_vsi_off(const void * _a,const void * _b)3315 static int compare_vsi_off(const void *_a, const void *_b)
3316 {
3317 	const struct btf_var_secinfo *a = _a;
3318 	const struct btf_var_secinfo *b = _b;
3319 
3320 	return a->offset - b->offset;
3321 }
3322 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)3323 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3324 			     struct btf_type *t)
3325 {
3326 	__u32 size = 0, i, vars = btf_vlen(t);
3327 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3328 	struct btf_var_secinfo *vsi;
3329 	bool fixup_offsets = false;
3330 	int err;
3331 
3332 	if (!sec_name) {
3333 		pr_debug("No name found in string section for DATASEC kind.\n");
3334 		return -ENOENT;
3335 	}
3336 
3337 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3338 	 * variable offsets set at the previous step. Further, not every
3339 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3340 	 * all fixups altogether for such sections and go straight to sorting
3341 	 * VARs within their DATASEC.
3342 	 */
3343 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3344 		goto sort_vars;
3345 
3346 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3347 	 * fix this up. But BPF static linker already fixes this up and fills
3348 	 * all the sizes and offsets during static linking. So this step has
3349 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3350 	 * non-extern DATASEC, so the variable fixup loop below handles both
3351 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3352 	 * symbol matching just once.
3353 	 */
3354 	if (t->size == 0) {
3355 		err = find_elf_sec_sz(obj, sec_name, &size);
3356 		if (err || !size) {
3357 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3358 				 sec_name, size, errstr(err));
3359 			return -ENOENT;
3360 		}
3361 
3362 		t->size = size;
3363 		fixup_offsets = true;
3364 	}
3365 
3366 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3367 		const struct btf_type *t_var;
3368 		struct btf_var *var;
3369 		const char *var_name;
3370 		Elf64_Sym *sym;
3371 
3372 		t_var = btf__type_by_id(btf, vsi->type);
3373 		if (!t_var || !btf_is_var(t_var)) {
3374 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3375 			return -EINVAL;
3376 		}
3377 
3378 		var = btf_var(t_var);
3379 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3380 			continue;
3381 
3382 		var_name = btf__name_by_offset(btf, t_var->name_off);
3383 		if (!var_name) {
3384 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3385 				 sec_name, i);
3386 			return -ENOENT;
3387 		}
3388 
3389 		sym = find_elf_var_sym(obj, var_name);
3390 		if (IS_ERR(sym)) {
3391 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3392 				 sec_name, var_name);
3393 			return -ENOENT;
3394 		}
3395 
3396 		if (fixup_offsets)
3397 			vsi->offset = sym->st_value;
3398 
3399 		/* if variable is a global/weak symbol, but has restricted
3400 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3401 		 * as static. This follows similar logic for functions (BPF
3402 		 * subprogs) and influences libbpf's further decisions about
3403 		 * whether to make global data BPF array maps as
3404 		 * BPF_F_MMAPABLE.
3405 		 */
3406 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3407 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3408 			var->linkage = BTF_VAR_STATIC;
3409 	}
3410 
3411 sort_vars:
3412 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3413 	return 0;
3414 }
3415 
bpf_object_fixup_btf(struct bpf_object * obj)3416 static int bpf_object_fixup_btf(struct bpf_object *obj)
3417 {
3418 	int i, n, err = 0;
3419 
3420 	if (!obj->btf)
3421 		return 0;
3422 
3423 	n = btf__type_cnt(obj->btf);
3424 	for (i = 1; i < n; i++) {
3425 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3426 
3427 		/* Loader needs to fix up some of the things compiler
3428 		 * couldn't get its hands on while emitting BTF. This
3429 		 * is section size and global variable offset. We use
3430 		 * the info from the ELF itself for this purpose.
3431 		 */
3432 		if (btf_is_datasec(t)) {
3433 			err = btf_fixup_datasec(obj, obj->btf, t);
3434 			if (err)
3435 				return err;
3436 		}
3437 	}
3438 
3439 	return 0;
3440 }
3441 
prog_needs_vmlinux_btf(struct bpf_program * prog)3442 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3443 {
3444 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3445 	    prog->type == BPF_PROG_TYPE_LSM)
3446 		return true;
3447 
3448 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3449 	 * also need vmlinux BTF
3450 	 */
3451 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3452 		return true;
3453 
3454 	return false;
3455 }
3456 
map_needs_vmlinux_btf(struct bpf_map * map)3457 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3458 {
3459 	return bpf_map__is_struct_ops(map);
3460 }
3461 
obj_needs_vmlinux_btf(const struct bpf_object * obj)3462 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3463 {
3464 	struct bpf_program *prog;
3465 	struct bpf_map *map;
3466 	int i;
3467 
3468 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3469 	 * is not specified
3470 	 */
3471 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3472 		return true;
3473 
3474 	/* Support for typed ksyms needs kernel BTF */
3475 	for (i = 0; i < obj->nr_extern; i++) {
3476 		const struct extern_desc *ext;
3477 
3478 		ext = &obj->externs[i];
3479 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3480 			return true;
3481 	}
3482 
3483 	bpf_object__for_each_program(prog, obj) {
3484 		if (!prog->autoload)
3485 			continue;
3486 		if (prog_needs_vmlinux_btf(prog))
3487 			return true;
3488 	}
3489 
3490 	bpf_object__for_each_map(map, obj) {
3491 		if (map_needs_vmlinux_btf(map))
3492 			return true;
3493 	}
3494 
3495 	return false;
3496 }
3497 
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3498 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3499 {
3500 	int err;
3501 
3502 	/* btf_vmlinux could be loaded earlier */
3503 	if (obj->btf_vmlinux || obj->gen_loader)
3504 		return 0;
3505 
3506 	if (!force && !obj_needs_vmlinux_btf(obj))
3507 		return 0;
3508 
3509 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3510 	err = libbpf_get_error(obj->btf_vmlinux);
3511 	if (err) {
3512 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3513 		obj->btf_vmlinux = NULL;
3514 		return err;
3515 	}
3516 	return 0;
3517 }
3518 
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3519 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3520 {
3521 	struct btf *kern_btf = obj->btf;
3522 	bool btf_mandatory, sanitize;
3523 	int i, err = 0;
3524 
3525 	if (!obj->btf)
3526 		return 0;
3527 
3528 	if (!kernel_supports(obj, FEAT_BTF)) {
3529 		if (kernel_needs_btf(obj)) {
3530 			err = -EOPNOTSUPP;
3531 			goto report;
3532 		}
3533 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3534 		return 0;
3535 	}
3536 
3537 	/* Even though some subprogs are global/weak, user might prefer more
3538 	 * permissive BPF verification process that BPF verifier performs for
3539 	 * static functions, taking into account more context from the caller
3540 	 * functions. In such case, they need to mark such subprogs with
3541 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3542 	 * corresponding FUNC BTF type to be marked as static and trigger more
3543 	 * involved BPF verification process.
3544 	 */
3545 	for (i = 0; i < obj->nr_programs; i++) {
3546 		struct bpf_program *prog = &obj->programs[i];
3547 		struct btf_type *t;
3548 		const char *name;
3549 		int j, n;
3550 
3551 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3552 			continue;
3553 
3554 		n = btf__type_cnt(obj->btf);
3555 		for (j = 1; j < n; j++) {
3556 			t = btf_type_by_id(obj->btf, j);
3557 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3558 				continue;
3559 
3560 			name = btf__str_by_offset(obj->btf, t->name_off);
3561 			if (strcmp(name, prog->name) != 0)
3562 				continue;
3563 
3564 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3565 			break;
3566 		}
3567 	}
3568 
3569 	sanitize = btf_needs_sanitization(obj);
3570 	if (sanitize) {
3571 		const void *raw_data;
3572 		__u32 sz;
3573 
3574 		/* clone BTF to sanitize a copy and leave the original intact */
3575 		raw_data = btf__raw_data(obj->btf, &sz);
3576 		kern_btf = btf__new(raw_data, sz);
3577 		err = libbpf_get_error(kern_btf);
3578 		if (err)
3579 			return err;
3580 
3581 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3582 		btf__set_pointer_size(obj->btf, 8);
3583 		err = bpf_object__sanitize_btf(obj, kern_btf);
3584 		if (err)
3585 			return err;
3586 	}
3587 
3588 	if (obj->gen_loader) {
3589 		__u32 raw_size = 0;
3590 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3591 
3592 		if (!raw_data)
3593 			return -ENOMEM;
3594 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3595 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3596 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3597 		 */
3598 		btf__set_fd(kern_btf, 0);
3599 	} else {
3600 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3601 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3602 					   obj->log_level ? 1 : 0, obj->token_fd);
3603 	}
3604 	if (sanitize) {
3605 		if (!err) {
3606 			/* move fd to libbpf's BTF */
3607 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3608 			btf__set_fd(kern_btf, -1);
3609 		}
3610 		btf__free(kern_btf);
3611 	}
3612 report:
3613 	if (err) {
3614 		btf_mandatory = kernel_needs_btf(obj);
3615 		if (btf_mandatory) {
3616 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3617 				errstr(err));
3618 		} else {
3619 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3620 				errstr(err));
3621 			err = 0;
3622 		}
3623 	}
3624 	return err;
3625 }
3626 
elf_sym_str(const struct bpf_object * obj,size_t off)3627 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3628 {
3629 	const char *name;
3630 
3631 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3632 	if (!name) {
3633 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3634 			off, obj->path, elf_errmsg(-1));
3635 		return NULL;
3636 	}
3637 
3638 	return name;
3639 }
3640 
elf_sec_str(const struct bpf_object * obj,size_t off)3641 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3642 {
3643 	const char *name;
3644 
3645 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3646 	if (!name) {
3647 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3648 			off, obj->path, elf_errmsg(-1));
3649 		return NULL;
3650 	}
3651 
3652 	return name;
3653 }
3654 
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3655 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3656 {
3657 	Elf_Scn *scn;
3658 
3659 	scn = elf_getscn(obj->efile.elf, idx);
3660 	if (!scn) {
3661 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3662 			idx, obj->path, elf_errmsg(-1));
3663 		return NULL;
3664 	}
3665 	return scn;
3666 }
3667 
elf_sec_by_name(const struct bpf_object * obj,const char * name)3668 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3669 {
3670 	Elf_Scn *scn = NULL;
3671 	Elf *elf = obj->efile.elf;
3672 	const char *sec_name;
3673 
3674 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3675 		sec_name = elf_sec_name(obj, scn);
3676 		if (!sec_name)
3677 			return NULL;
3678 
3679 		if (strcmp(sec_name, name) != 0)
3680 			continue;
3681 
3682 		return scn;
3683 	}
3684 	return NULL;
3685 }
3686 
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3687 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3688 {
3689 	Elf64_Shdr *shdr;
3690 
3691 	if (!scn)
3692 		return NULL;
3693 
3694 	shdr = elf64_getshdr(scn);
3695 	if (!shdr) {
3696 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3697 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3698 		return NULL;
3699 	}
3700 
3701 	return shdr;
3702 }
3703 
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3704 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3705 {
3706 	const char *name;
3707 	Elf64_Shdr *sh;
3708 
3709 	if (!scn)
3710 		return NULL;
3711 
3712 	sh = elf_sec_hdr(obj, scn);
3713 	if (!sh)
3714 		return NULL;
3715 
3716 	name = elf_sec_str(obj, sh->sh_name);
3717 	if (!name) {
3718 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3719 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3720 		return NULL;
3721 	}
3722 
3723 	return name;
3724 }
3725 
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3726 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3727 {
3728 	Elf_Data *data;
3729 
3730 	if (!scn)
3731 		return NULL;
3732 
3733 	data = elf_getdata(scn, 0);
3734 	if (!data) {
3735 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3736 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3737 			obj->path, elf_errmsg(-1));
3738 		return NULL;
3739 	}
3740 
3741 	return data;
3742 }
3743 
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3744 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3745 {
3746 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3747 		return NULL;
3748 
3749 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3750 }
3751 
elf_rel_by_idx(Elf_Data * data,size_t idx)3752 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3753 {
3754 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3755 		return NULL;
3756 
3757 	return (Elf64_Rel *)data->d_buf + idx;
3758 }
3759 
is_sec_name_dwarf(const char * name)3760 static bool is_sec_name_dwarf(const char *name)
3761 {
3762 	/* approximation, but the actual list is too long */
3763 	return str_has_pfx(name, ".debug_");
3764 }
3765 
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3766 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3767 {
3768 	/* no special handling of .strtab */
3769 	if (hdr->sh_type == SHT_STRTAB)
3770 		return true;
3771 
3772 	/* ignore .llvm_addrsig section as well */
3773 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3774 		return true;
3775 
3776 	/* no subprograms will lead to an empty .text section, ignore it */
3777 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3778 	    strcmp(name, ".text") == 0)
3779 		return true;
3780 
3781 	/* DWARF sections */
3782 	if (is_sec_name_dwarf(name))
3783 		return true;
3784 
3785 	if (str_has_pfx(name, ".rel")) {
3786 		name += sizeof(".rel") - 1;
3787 		/* DWARF section relocations */
3788 		if (is_sec_name_dwarf(name))
3789 			return true;
3790 
3791 		/* .BTF and .BTF.ext don't need relocations */
3792 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3793 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3794 			return true;
3795 	}
3796 
3797 	return false;
3798 }
3799 
cmp_progs(const void * _a,const void * _b)3800 static int cmp_progs(const void *_a, const void *_b)
3801 {
3802 	const struct bpf_program *a = _a;
3803 	const struct bpf_program *b = _b;
3804 
3805 	if (a->sec_idx != b->sec_idx)
3806 		return a->sec_idx < b->sec_idx ? -1 : 1;
3807 
3808 	/* sec_insn_off can't be the same within the section */
3809 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3810 }
3811 
bpf_object__elf_collect(struct bpf_object * obj)3812 static int bpf_object__elf_collect(struct bpf_object *obj)
3813 {
3814 	struct elf_sec_desc *sec_desc;
3815 	Elf *elf = obj->efile.elf;
3816 	Elf_Data *btf_ext_data = NULL;
3817 	Elf_Data *btf_data = NULL;
3818 	int idx = 0, err = 0;
3819 	const char *name;
3820 	Elf_Data *data;
3821 	Elf_Scn *scn;
3822 	Elf64_Shdr *sh;
3823 
3824 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3825 	 * section. Since section count retrieved by elf_getshdrnum() does
3826 	 * include sec #0, it is already the necessary size of an array to keep
3827 	 * all the sections.
3828 	 */
3829 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3830 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3831 			obj->path, elf_errmsg(-1));
3832 		return -LIBBPF_ERRNO__FORMAT;
3833 	}
3834 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3835 	if (!obj->efile.secs)
3836 		return -ENOMEM;
3837 
3838 	/* a bunch of ELF parsing functionality depends on processing symbols,
3839 	 * so do the first pass and find the symbol table
3840 	 */
3841 	scn = NULL;
3842 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3843 		sh = elf_sec_hdr(obj, scn);
3844 		if (!sh)
3845 			return -LIBBPF_ERRNO__FORMAT;
3846 
3847 		if (sh->sh_type == SHT_SYMTAB) {
3848 			if (obj->efile.symbols) {
3849 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3850 				return -LIBBPF_ERRNO__FORMAT;
3851 			}
3852 
3853 			data = elf_sec_data(obj, scn);
3854 			if (!data)
3855 				return -LIBBPF_ERRNO__FORMAT;
3856 
3857 			idx = elf_ndxscn(scn);
3858 
3859 			obj->efile.symbols = data;
3860 			obj->efile.symbols_shndx = idx;
3861 			obj->efile.strtabidx = sh->sh_link;
3862 		}
3863 	}
3864 
3865 	if (!obj->efile.symbols) {
3866 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3867 			obj->path);
3868 		return -ENOENT;
3869 	}
3870 
3871 	scn = NULL;
3872 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3873 		idx = elf_ndxscn(scn);
3874 		sec_desc = &obj->efile.secs[idx];
3875 
3876 		sh = elf_sec_hdr(obj, scn);
3877 		if (!sh)
3878 			return -LIBBPF_ERRNO__FORMAT;
3879 
3880 		name = elf_sec_str(obj, sh->sh_name);
3881 		if (!name)
3882 			return -LIBBPF_ERRNO__FORMAT;
3883 
3884 		if (ignore_elf_section(sh, name))
3885 			continue;
3886 
3887 		data = elf_sec_data(obj, scn);
3888 		if (!data)
3889 			return -LIBBPF_ERRNO__FORMAT;
3890 
3891 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3892 			 idx, name, (unsigned long)data->d_size,
3893 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3894 			 (int)sh->sh_type);
3895 
3896 		if (strcmp(name, "license") == 0) {
3897 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3898 			if (err)
3899 				return err;
3900 		} else if (strcmp(name, "version") == 0) {
3901 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3902 			if (err)
3903 				return err;
3904 		} else if (strcmp(name, "maps") == 0) {
3905 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3906 			return -ENOTSUP;
3907 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3908 			obj->efile.btf_maps_shndx = idx;
3909 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3910 			if (sh->sh_type != SHT_PROGBITS)
3911 				return -LIBBPF_ERRNO__FORMAT;
3912 			btf_data = data;
3913 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3914 			if (sh->sh_type != SHT_PROGBITS)
3915 				return -LIBBPF_ERRNO__FORMAT;
3916 			btf_ext_data = data;
3917 		} else if (sh->sh_type == SHT_SYMTAB) {
3918 			/* already processed during the first pass above */
3919 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3920 			if (sh->sh_flags & SHF_EXECINSTR) {
3921 				if (strcmp(name, ".text") == 0)
3922 					obj->efile.text_shndx = idx;
3923 				err = bpf_object__add_programs(obj, data, name, idx);
3924 				if (err)
3925 					return err;
3926 			} else if (strcmp(name, DATA_SEC) == 0 ||
3927 				   str_has_pfx(name, DATA_SEC ".")) {
3928 				sec_desc->sec_type = SEC_DATA;
3929 				sec_desc->shdr = sh;
3930 				sec_desc->data = data;
3931 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3932 				   str_has_pfx(name, RODATA_SEC ".")) {
3933 				sec_desc->sec_type = SEC_RODATA;
3934 				sec_desc->shdr = sh;
3935 				sec_desc->data = data;
3936 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3937 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3938 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3939 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3940 				sec_desc->sec_type = SEC_ST_OPS;
3941 				sec_desc->shdr = sh;
3942 				sec_desc->data = data;
3943 				obj->efile.has_st_ops = true;
3944 			} else if (strcmp(name, ARENA_SEC) == 0) {
3945 				obj->efile.arena_data = data;
3946 				obj->efile.arena_data_shndx = idx;
3947 			} else {
3948 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3949 					idx, name);
3950 			}
3951 		} else if (sh->sh_type == SHT_REL) {
3952 			int targ_sec_idx = sh->sh_info; /* points to other section */
3953 
3954 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3955 			    targ_sec_idx >= obj->efile.sec_cnt)
3956 				return -LIBBPF_ERRNO__FORMAT;
3957 
3958 			/* Only do relo for section with exec instructions */
3959 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3960 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3961 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3962 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3963 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3964 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3965 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3966 					idx, name, targ_sec_idx,
3967 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3968 				continue;
3969 			}
3970 
3971 			sec_desc->sec_type = SEC_RELO;
3972 			sec_desc->shdr = sh;
3973 			sec_desc->data = data;
3974 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3975 							 str_has_pfx(name, BSS_SEC "."))) {
3976 			sec_desc->sec_type = SEC_BSS;
3977 			sec_desc->shdr = sh;
3978 			sec_desc->data = data;
3979 		} else {
3980 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3981 				(size_t)sh->sh_size);
3982 		}
3983 	}
3984 
3985 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3986 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3987 		return -LIBBPF_ERRNO__FORMAT;
3988 	}
3989 
3990 	/* change BPF program insns to native endianness for introspection */
3991 	if (!is_native_endianness(obj))
3992 		bpf_object_bswap_progs(obj);
3993 
3994 	/* sort BPF programs by section name and in-section instruction offset
3995 	 * for faster search
3996 	 */
3997 	if (obj->nr_programs)
3998 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3999 
4000 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4001 }
4002 
sym_is_extern(const Elf64_Sym * sym)4003 static bool sym_is_extern(const Elf64_Sym *sym)
4004 {
4005 	int bind = ELF64_ST_BIND(sym->st_info);
4006 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4007 	return sym->st_shndx == SHN_UNDEF &&
4008 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4009 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4010 }
4011 
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)4012 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4013 {
4014 	int bind = ELF64_ST_BIND(sym->st_info);
4015 	int type = ELF64_ST_TYPE(sym->st_info);
4016 
4017 	/* in .text section */
4018 	if (sym->st_shndx != text_shndx)
4019 		return false;
4020 
4021 	/* local function */
4022 	if (bind == STB_LOCAL && type == STT_SECTION)
4023 		return true;
4024 
4025 	/* global function */
4026 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4027 }
4028 
find_extern_btf_id(const struct btf * btf,const char * ext_name)4029 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4030 {
4031 	const struct btf_type *t;
4032 	const char *tname;
4033 	int i, n;
4034 
4035 	if (!btf)
4036 		return -ESRCH;
4037 
4038 	n = btf__type_cnt(btf);
4039 	for (i = 1; i < n; i++) {
4040 		t = btf__type_by_id(btf, i);
4041 
4042 		if (!btf_is_var(t) && !btf_is_func(t))
4043 			continue;
4044 
4045 		tname = btf__name_by_offset(btf, t->name_off);
4046 		if (strcmp(tname, ext_name))
4047 			continue;
4048 
4049 		if (btf_is_var(t) &&
4050 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4051 			return -EINVAL;
4052 
4053 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4054 			return -EINVAL;
4055 
4056 		return i;
4057 	}
4058 
4059 	return -ENOENT;
4060 }
4061 
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)4062 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4063 	const struct btf_var_secinfo *vs;
4064 	const struct btf_type *t;
4065 	int i, j, n;
4066 
4067 	if (!btf)
4068 		return -ESRCH;
4069 
4070 	n = btf__type_cnt(btf);
4071 	for (i = 1; i < n; i++) {
4072 		t = btf__type_by_id(btf, i);
4073 
4074 		if (!btf_is_datasec(t))
4075 			continue;
4076 
4077 		vs = btf_var_secinfos(t);
4078 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4079 			if (vs->type == ext_btf_id)
4080 				return i;
4081 		}
4082 	}
4083 
4084 	return -ENOENT;
4085 }
4086 
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)4087 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4088 				     bool *is_signed)
4089 {
4090 	const struct btf_type *t;
4091 	const char *name;
4092 
4093 	t = skip_mods_and_typedefs(btf, id, NULL);
4094 	name = btf__name_by_offset(btf, t->name_off);
4095 
4096 	if (is_signed)
4097 		*is_signed = false;
4098 	switch (btf_kind(t)) {
4099 	case BTF_KIND_INT: {
4100 		int enc = btf_int_encoding(t);
4101 
4102 		if (enc & BTF_INT_BOOL)
4103 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4104 		if (is_signed)
4105 			*is_signed = enc & BTF_INT_SIGNED;
4106 		if (t->size == 1)
4107 			return KCFG_CHAR;
4108 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4109 			return KCFG_UNKNOWN;
4110 		return KCFG_INT;
4111 	}
4112 	case BTF_KIND_ENUM:
4113 		if (t->size != 4)
4114 			return KCFG_UNKNOWN;
4115 		if (strcmp(name, "libbpf_tristate"))
4116 			return KCFG_UNKNOWN;
4117 		return KCFG_TRISTATE;
4118 	case BTF_KIND_ENUM64:
4119 		if (strcmp(name, "libbpf_tristate"))
4120 			return KCFG_UNKNOWN;
4121 		return KCFG_TRISTATE;
4122 	case BTF_KIND_ARRAY:
4123 		if (btf_array(t)->nelems == 0)
4124 			return KCFG_UNKNOWN;
4125 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4126 			return KCFG_UNKNOWN;
4127 		return KCFG_CHAR_ARR;
4128 	default:
4129 		return KCFG_UNKNOWN;
4130 	}
4131 }
4132 
cmp_externs(const void * _a,const void * _b)4133 static int cmp_externs(const void *_a, const void *_b)
4134 {
4135 	const struct extern_desc *a = _a;
4136 	const struct extern_desc *b = _b;
4137 
4138 	if (a->type != b->type)
4139 		return a->type < b->type ? -1 : 1;
4140 
4141 	if (a->type == EXT_KCFG) {
4142 		/* descending order by alignment requirements */
4143 		if (a->kcfg.align != b->kcfg.align)
4144 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4145 		/* ascending order by size, within same alignment class */
4146 		if (a->kcfg.sz != b->kcfg.sz)
4147 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4148 	}
4149 
4150 	/* resolve ties by name */
4151 	return strcmp(a->name, b->name);
4152 }
4153 
find_int_btf_id(const struct btf * btf)4154 static int find_int_btf_id(const struct btf *btf)
4155 {
4156 	const struct btf_type *t;
4157 	int i, n;
4158 
4159 	n = btf__type_cnt(btf);
4160 	for (i = 1; i < n; i++) {
4161 		t = btf__type_by_id(btf, i);
4162 
4163 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4164 			return i;
4165 	}
4166 
4167 	return 0;
4168 }
4169 
add_dummy_ksym_var(struct btf * btf)4170 static int add_dummy_ksym_var(struct btf *btf)
4171 {
4172 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4173 	const struct btf_var_secinfo *vs;
4174 	const struct btf_type *sec;
4175 
4176 	if (!btf)
4177 		return 0;
4178 
4179 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4180 					    BTF_KIND_DATASEC);
4181 	if (sec_btf_id < 0)
4182 		return 0;
4183 
4184 	sec = btf__type_by_id(btf, sec_btf_id);
4185 	vs = btf_var_secinfos(sec);
4186 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4187 		const struct btf_type *vt;
4188 
4189 		vt = btf__type_by_id(btf, vs->type);
4190 		if (btf_is_func(vt))
4191 			break;
4192 	}
4193 
4194 	/* No func in ksyms sec.  No need to add dummy var. */
4195 	if (i == btf_vlen(sec))
4196 		return 0;
4197 
4198 	int_btf_id = find_int_btf_id(btf);
4199 	dummy_var_btf_id = btf__add_var(btf,
4200 					"dummy_ksym",
4201 					BTF_VAR_GLOBAL_ALLOCATED,
4202 					int_btf_id);
4203 	if (dummy_var_btf_id < 0)
4204 		pr_warn("cannot create a dummy_ksym var\n");
4205 
4206 	return dummy_var_btf_id;
4207 }
4208 
bpf_object__collect_externs(struct bpf_object * obj)4209 static int bpf_object__collect_externs(struct bpf_object *obj)
4210 {
4211 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4212 	const struct btf_type *t;
4213 	struct extern_desc *ext;
4214 	int i, n, off, dummy_var_btf_id;
4215 	const char *ext_name, *sec_name;
4216 	size_t ext_essent_len;
4217 	Elf_Scn *scn;
4218 	Elf64_Shdr *sh;
4219 
4220 	if (!obj->efile.symbols)
4221 		return 0;
4222 
4223 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4224 	sh = elf_sec_hdr(obj, scn);
4225 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4226 		return -LIBBPF_ERRNO__FORMAT;
4227 
4228 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4229 	if (dummy_var_btf_id < 0)
4230 		return dummy_var_btf_id;
4231 
4232 	n = sh->sh_size / sh->sh_entsize;
4233 	pr_debug("looking for externs among %d symbols...\n", n);
4234 
4235 	for (i = 0; i < n; i++) {
4236 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4237 
4238 		if (!sym)
4239 			return -LIBBPF_ERRNO__FORMAT;
4240 		if (!sym_is_extern(sym))
4241 			continue;
4242 		ext_name = elf_sym_str(obj, sym->st_name);
4243 		if (!ext_name || !ext_name[0])
4244 			continue;
4245 
4246 		ext = obj->externs;
4247 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4248 		if (!ext)
4249 			return -ENOMEM;
4250 		obj->externs = ext;
4251 		ext = &ext[obj->nr_extern];
4252 		memset(ext, 0, sizeof(*ext));
4253 		obj->nr_extern++;
4254 
4255 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4256 		if (ext->btf_id <= 0) {
4257 			pr_warn("failed to find BTF for extern '%s': %d\n",
4258 				ext_name, ext->btf_id);
4259 			return ext->btf_id;
4260 		}
4261 		t = btf__type_by_id(obj->btf, ext->btf_id);
4262 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4263 		if (!ext->name)
4264 			return -ENOMEM;
4265 		ext->sym_idx = i;
4266 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4267 
4268 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4269 		ext->essent_name = NULL;
4270 		if (ext_essent_len != strlen(ext->name)) {
4271 			ext->essent_name = strndup(ext->name, ext_essent_len);
4272 			if (!ext->essent_name)
4273 				return -ENOMEM;
4274 		}
4275 
4276 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4277 		if (ext->sec_btf_id <= 0) {
4278 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4279 				ext_name, ext->btf_id, ext->sec_btf_id);
4280 			return ext->sec_btf_id;
4281 		}
4282 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4283 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4284 
4285 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4286 			if (btf_is_func(t)) {
4287 				pr_warn("extern function %s is unsupported under %s section\n",
4288 					ext->name, KCONFIG_SEC);
4289 				return -ENOTSUP;
4290 			}
4291 			kcfg_sec = sec;
4292 			ext->type = EXT_KCFG;
4293 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4294 			if (ext->kcfg.sz <= 0) {
4295 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4296 					ext_name, ext->kcfg.sz);
4297 				return ext->kcfg.sz;
4298 			}
4299 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4300 			if (ext->kcfg.align <= 0) {
4301 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4302 					ext_name, ext->kcfg.align);
4303 				return -EINVAL;
4304 			}
4305 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4306 							&ext->kcfg.is_signed);
4307 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4308 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4309 				return -ENOTSUP;
4310 			}
4311 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4312 			ksym_sec = sec;
4313 			ext->type = EXT_KSYM;
4314 			skip_mods_and_typedefs(obj->btf, t->type,
4315 					       &ext->ksym.type_id);
4316 		} else {
4317 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4318 			return -ENOTSUP;
4319 		}
4320 	}
4321 	pr_debug("collected %d externs total\n", obj->nr_extern);
4322 
4323 	if (!obj->nr_extern)
4324 		return 0;
4325 
4326 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4327 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4328 
4329 	/* for .ksyms section, we need to turn all externs into allocated
4330 	 * variables in BTF to pass kernel verification; we do this by
4331 	 * pretending that each extern is a 8-byte variable
4332 	 */
4333 	if (ksym_sec) {
4334 		/* find existing 4-byte integer type in BTF to use for fake
4335 		 * extern variables in DATASEC
4336 		 */
4337 		int int_btf_id = find_int_btf_id(obj->btf);
4338 		/* For extern function, a dummy_var added earlier
4339 		 * will be used to replace the vs->type and
4340 		 * its name string will be used to refill
4341 		 * the missing param's name.
4342 		 */
4343 		const struct btf_type *dummy_var;
4344 
4345 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4346 		for (i = 0; i < obj->nr_extern; i++) {
4347 			ext = &obj->externs[i];
4348 			if (ext->type != EXT_KSYM)
4349 				continue;
4350 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4351 				 i, ext->sym_idx, ext->name);
4352 		}
4353 
4354 		sec = ksym_sec;
4355 		n = btf_vlen(sec);
4356 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4357 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4358 			struct btf_type *vt;
4359 
4360 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4361 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4362 			ext = find_extern_by_name(obj, ext_name);
4363 			if (!ext) {
4364 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4365 					btf_kind_str(vt), ext_name);
4366 				return -ESRCH;
4367 			}
4368 			if (btf_is_func(vt)) {
4369 				const struct btf_type *func_proto;
4370 				struct btf_param *param;
4371 				int j;
4372 
4373 				func_proto = btf__type_by_id(obj->btf,
4374 							     vt->type);
4375 				param = btf_params(func_proto);
4376 				/* Reuse the dummy_var string if the
4377 				 * func proto does not have param name.
4378 				 */
4379 				for (j = 0; j < btf_vlen(func_proto); j++)
4380 					if (param[j].type && !param[j].name_off)
4381 						param[j].name_off =
4382 							dummy_var->name_off;
4383 				vs->type = dummy_var_btf_id;
4384 				vt->info &= ~0xffff;
4385 				vt->info |= BTF_FUNC_GLOBAL;
4386 			} else {
4387 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4388 				vt->type = int_btf_id;
4389 			}
4390 			vs->offset = off;
4391 			vs->size = sizeof(int);
4392 		}
4393 		sec->size = off;
4394 	}
4395 
4396 	if (kcfg_sec) {
4397 		sec = kcfg_sec;
4398 		/* for kcfg externs calculate their offsets within a .kconfig map */
4399 		off = 0;
4400 		for (i = 0; i < obj->nr_extern; i++) {
4401 			ext = &obj->externs[i];
4402 			if (ext->type != EXT_KCFG)
4403 				continue;
4404 
4405 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4406 			off = ext->kcfg.data_off + ext->kcfg.sz;
4407 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4408 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4409 		}
4410 		sec->size = off;
4411 		n = btf_vlen(sec);
4412 		for (i = 0; i < n; i++) {
4413 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4414 
4415 			t = btf__type_by_id(obj->btf, vs->type);
4416 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4417 			ext = find_extern_by_name(obj, ext_name);
4418 			if (!ext) {
4419 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4420 					ext_name);
4421 				return -ESRCH;
4422 			}
4423 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4424 			vs->offset = ext->kcfg.data_off;
4425 		}
4426 	}
4427 	return 0;
4428 }
4429 
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)4430 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4431 {
4432 	return prog->sec_idx == obj->efile.text_shndx;
4433 }
4434 
4435 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)4436 bpf_object__find_program_by_name(const struct bpf_object *obj,
4437 				 const char *name)
4438 {
4439 	struct bpf_program *prog;
4440 
4441 	bpf_object__for_each_program(prog, obj) {
4442 		if (prog_is_subprog(obj, prog))
4443 			continue;
4444 		if (!strcmp(prog->name, name))
4445 			return prog;
4446 	}
4447 	return errno = ENOENT, NULL;
4448 }
4449 
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4450 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4451 				      int shndx)
4452 {
4453 	switch (obj->efile.secs[shndx].sec_type) {
4454 	case SEC_BSS:
4455 	case SEC_DATA:
4456 	case SEC_RODATA:
4457 		return true;
4458 	default:
4459 		return false;
4460 	}
4461 }
4462 
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4463 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4464 				      int shndx)
4465 {
4466 	return shndx == obj->efile.btf_maps_shndx;
4467 }
4468 
4469 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4470 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4471 {
4472 	if (shndx == obj->efile.symbols_shndx)
4473 		return LIBBPF_MAP_KCONFIG;
4474 
4475 	switch (obj->efile.secs[shndx].sec_type) {
4476 	case SEC_BSS:
4477 		return LIBBPF_MAP_BSS;
4478 	case SEC_DATA:
4479 		return LIBBPF_MAP_DATA;
4480 	case SEC_RODATA:
4481 		return LIBBPF_MAP_RODATA;
4482 	default:
4483 		return LIBBPF_MAP_UNSPEC;
4484 	}
4485 }
4486 
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)4487 static int bpf_program__record_reloc(struct bpf_program *prog,
4488 				     struct reloc_desc *reloc_desc,
4489 				     __u32 insn_idx, const char *sym_name,
4490 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4491 {
4492 	struct bpf_insn *insn = &prog->insns[insn_idx];
4493 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4494 	struct bpf_object *obj = prog->obj;
4495 	__u32 shdr_idx = sym->st_shndx;
4496 	enum libbpf_map_type type;
4497 	const char *sym_sec_name;
4498 	struct bpf_map *map;
4499 
4500 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4501 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4502 			prog->name, sym_name, insn_idx, insn->code);
4503 		return -LIBBPF_ERRNO__RELOC;
4504 	}
4505 
4506 	if (sym_is_extern(sym)) {
4507 		int sym_idx = ELF64_R_SYM(rel->r_info);
4508 		int i, n = obj->nr_extern;
4509 		struct extern_desc *ext;
4510 
4511 		for (i = 0; i < n; i++) {
4512 			ext = &obj->externs[i];
4513 			if (ext->sym_idx == sym_idx)
4514 				break;
4515 		}
4516 		if (i >= n) {
4517 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4518 				prog->name, sym_name, sym_idx);
4519 			return -LIBBPF_ERRNO__RELOC;
4520 		}
4521 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4522 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4523 		if (insn->code == (BPF_JMP | BPF_CALL))
4524 			reloc_desc->type = RELO_EXTERN_CALL;
4525 		else
4526 			reloc_desc->type = RELO_EXTERN_LD64;
4527 		reloc_desc->insn_idx = insn_idx;
4528 		reloc_desc->ext_idx = i;
4529 		return 0;
4530 	}
4531 
4532 	/* sub-program call relocation */
4533 	if (is_call_insn(insn)) {
4534 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4535 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4536 			return -LIBBPF_ERRNO__RELOC;
4537 		}
4538 		/* text_shndx can be 0, if no default "main" program exists */
4539 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4540 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4541 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4542 				prog->name, sym_name, sym_sec_name);
4543 			return -LIBBPF_ERRNO__RELOC;
4544 		}
4545 		if (sym->st_value % BPF_INSN_SZ) {
4546 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4547 				prog->name, sym_name, (size_t)sym->st_value);
4548 			return -LIBBPF_ERRNO__RELOC;
4549 		}
4550 		reloc_desc->type = RELO_CALL;
4551 		reloc_desc->insn_idx = insn_idx;
4552 		reloc_desc->sym_off = sym->st_value;
4553 		return 0;
4554 	}
4555 
4556 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4557 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4558 			prog->name, sym_name, shdr_idx);
4559 		return -LIBBPF_ERRNO__RELOC;
4560 	}
4561 
4562 	/* loading subprog addresses */
4563 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4564 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4565 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4566 		 */
4567 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4568 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4569 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4570 			return -LIBBPF_ERRNO__RELOC;
4571 		}
4572 
4573 		reloc_desc->type = RELO_SUBPROG_ADDR;
4574 		reloc_desc->insn_idx = insn_idx;
4575 		reloc_desc->sym_off = sym->st_value;
4576 		return 0;
4577 	}
4578 
4579 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4580 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4581 
4582 	/* arena data relocation */
4583 	if (shdr_idx == obj->efile.arena_data_shndx) {
4584 		reloc_desc->type = RELO_DATA;
4585 		reloc_desc->insn_idx = insn_idx;
4586 		reloc_desc->map_idx = obj->arena_map - obj->maps;
4587 		reloc_desc->sym_off = sym->st_value;
4588 		return 0;
4589 	}
4590 
4591 	/* generic map reference relocation */
4592 	if (type == LIBBPF_MAP_UNSPEC) {
4593 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4594 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4595 				prog->name, sym_name, sym_sec_name);
4596 			return -LIBBPF_ERRNO__RELOC;
4597 		}
4598 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4599 			map = &obj->maps[map_idx];
4600 			if (map->libbpf_type != type ||
4601 			    map->sec_idx != sym->st_shndx ||
4602 			    map->sec_offset != sym->st_value)
4603 				continue;
4604 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4605 				 prog->name, map_idx, map->name, map->sec_idx,
4606 				 map->sec_offset, insn_idx);
4607 			break;
4608 		}
4609 		if (map_idx >= nr_maps) {
4610 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4611 				prog->name, sym_sec_name, (size_t)sym->st_value);
4612 			return -LIBBPF_ERRNO__RELOC;
4613 		}
4614 		reloc_desc->type = RELO_LD64;
4615 		reloc_desc->insn_idx = insn_idx;
4616 		reloc_desc->map_idx = map_idx;
4617 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4618 		return 0;
4619 	}
4620 
4621 	/* global data map relocation */
4622 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4623 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4624 			prog->name, sym_sec_name);
4625 		return -LIBBPF_ERRNO__RELOC;
4626 	}
4627 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4628 		map = &obj->maps[map_idx];
4629 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4630 			continue;
4631 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4632 			 prog->name, map_idx, map->name, map->sec_idx,
4633 			 map->sec_offset, insn_idx);
4634 		break;
4635 	}
4636 	if (map_idx >= nr_maps) {
4637 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4638 			prog->name, sym_sec_name);
4639 		return -LIBBPF_ERRNO__RELOC;
4640 	}
4641 
4642 	reloc_desc->type = RELO_DATA;
4643 	reloc_desc->insn_idx = insn_idx;
4644 	reloc_desc->map_idx = map_idx;
4645 	reloc_desc->sym_off = sym->st_value;
4646 	return 0;
4647 }
4648 
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4649 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4650 {
4651 	return insn_idx >= prog->sec_insn_off &&
4652 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4653 }
4654 
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4655 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4656 						 size_t sec_idx, size_t insn_idx)
4657 {
4658 	int l = 0, r = obj->nr_programs - 1, m;
4659 	struct bpf_program *prog;
4660 
4661 	if (!obj->nr_programs)
4662 		return NULL;
4663 
4664 	while (l < r) {
4665 		m = l + (r - l + 1) / 2;
4666 		prog = &obj->programs[m];
4667 
4668 		if (prog->sec_idx < sec_idx ||
4669 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4670 			l = m;
4671 		else
4672 			r = m - 1;
4673 	}
4674 	/* matching program could be at index l, but it still might be the
4675 	 * wrong one, so we need to double check conditions for the last time
4676 	 */
4677 	prog = &obj->programs[l];
4678 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4679 		return prog;
4680 	return NULL;
4681 }
4682 
4683 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4684 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4685 {
4686 	const char *relo_sec_name, *sec_name;
4687 	size_t sec_idx = shdr->sh_info, sym_idx;
4688 	struct bpf_program *prog;
4689 	struct reloc_desc *relos;
4690 	int err, i, nrels;
4691 	const char *sym_name;
4692 	__u32 insn_idx;
4693 	Elf_Scn *scn;
4694 	Elf_Data *scn_data;
4695 	Elf64_Sym *sym;
4696 	Elf64_Rel *rel;
4697 
4698 	if (sec_idx >= obj->efile.sec_cnt)
4699 		return -EINVAL;
4700 
4701 	scn = elf_sec_by_idx(obj, sec_idx);
4702 	scn_data = elf_sec_data(obj, scn);
4703 	if (!scn_data)
4704 		return -LIBBPF_ERRNO__FORMAT;
4705 
4706 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4707 	sec_name = elf_sec_name(obj, scn);
4708 	if (!relo_sec_name || !sec_name)
4709 		return -EINVAL;
4710 
4711 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4712 		 relo_sec_name, sec_idx, sec_name);
4713 	nrels = shdr->sh_size / shdr->sh_entsize;
4714 
4715 	for (i = 0; i < nrels; i++) {
4716 		rel = elf_rel_by_idx(data, i);
4717 		if (!rel) {
4718 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4719 			return -LIBBPF_ERRNO__FORMAT;
4720 		}
4721 
4722 		sym_idx = ELF64_R_SYM(rel->r_info);
4723 		sym = elf_sym_by_idx(obj, sym_idx);
4724 		if (!sym) {
4725 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4726 				relo_sec_name, sym_idx, i);
4727 			return -LIBBPF_ERRNO__FORMAT;
4728 		}
4729 
4730 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4731 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4732 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4733 			return -LIBBPF_ERRNO__FORMAT;
4734 		}
4735 
4736 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4737 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4738 				relo_sec_name, (size_t)rel->r_offset, i);
4739 			return -LIBBPF_ERRNO__FORMAT;
4740 		}
4741 
4742 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4743 		/* relocations against static functions are recorded as
4744 		 * relocations against the section that contains a function;
4745 		 * in such case, symbol will be STT_SECTION and sym.st_name
4746 		 * will point to empty string (0), so fetch section name
4747 		 * instead
4748 		 */
4749 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4750 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4751 		else
4752 			sym_name = elf_sym_str(obj, sym->st_name);
4753 		sym_name = sym_name ?: "<?";
4754 
4755 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4756 			 relo_sec_name, i, insn_idx, sym_name);
4757 
4758 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4759 		if (!prog) {
4760 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4761 				relo_sec_name, i, sec_name, insn_idx);
4762 			continue;
4763 		}
4764 
4765 		relos = libbpf_reallocarray(prog->reloc_desc,
4766 					    prog->nr_reloc + 1, sizeof(*relos));
4767 		if (!relos)
4768 			return -ENOMEM;
4769 		prog->reloc_desc = relos;
4770 
4771 		/* adjust insn_idx to local BPF program frame of reference */
4772 		insn_idx -= prog->sec_insn_off;
4773 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4774 						insn_idx, sym_name, sym, rel);
4775 		if (err)
4776 			return err;
4777 
4778 		prog->nr_reloc++;
4779 	}
4780 	return 0;
4781 }
4782 
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4783 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4784 {
4785 	int id;
4786 
4787 	if (!obj->btf)
4788 		return -ENOENT;
4789 
4790 	/* if it's BTF-defined map, we don't need to search for type IDs.
4791 	 * For struct_ops map, it does not need btf_key_type_id and
4792 	 * btf_value_type_id.
4793 	 */
4794 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4795 		return 0;
4796 
4797 	/*
4798 	 * LLVM annotates global data differently in BTF, that is,
4799 	 * only as '.data', '.bss' or '.rodata'.
4800 	 */
4801 	if (!bpf_map__is_internal(map))
4802 		return -ENOENT;
4803 
4804 	id = btf__find_by_name(obj->btf, map->real_name);
4805 	if (id < 0)
4806 		return id;
4807 
4808 	map->btf_key_type_id = 0;
4809 	map->btf_value_type_id = id;
4810 	return 0;
4811 }
4812 
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4813 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4814 {
4815 	char file[PATH_MAX], buff[4096];
4816 	FILE *fp;
4817 	__u32 val;
4818 	int err;
4819 
4820 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4821 	memset(info, 0, sizeof(*info));
4822 
4823 	fp = fopen(file, "re");
4824 	if (!fp) {
4825 		err = -errno;
4826 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4827 			errstr(err));
4828 		return err;
4829 	}
4830 
4831 	while (fgets(buff, sizeof(buff), fp)) {
4832 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4833 			info->type = val;
4834 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4835 			info->key_size = val;
4836 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4837 			info->value_size = val;
4838 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4839 			info->max_entries = val;
4840 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4841 			info->map_flags = val;
4842 	}
4843 
4844 	fclose(fp);
4845 
4846 	return 0;
4847 }
4848 
map_is_created(const struct bpf_map * map)4849 static bool map_is_created(const struct bpf_map *map)
4850 {
4851 	return map->obj->state >= OBJ_PREPARED || map->reused;
4852 }
4853 
bpf_map__autocreate(const struct bpf_map * map)4854 bool bpf_map__autocreate(const struct bpf_map *map)
4855 {
4856 	return map->autocreate;
4857 }
4858 
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4859 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4860 {
4861 	if (map_is_created(map))
4862 		return libbpf_err(-EBUSY);
4863 
4864 	map->autocreate = autocreate;
4865 	return 0;
4866 }
4867 
bpf_map__set_autoattach(struct bpf_map * map,bool autoattach)4868 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4869 {
4870 	if (!bpf_map__is_struct_ops(map))
4871 		return libbpf_err(-EINVAL);
4872 
4873 	map->autoattach = autoattach;
4874 	return 0;
4875 }
4876 
bpf_map__autoattach(const struct bpf_map * map)4877 bool bpf_map__autoattach(const struct bpf_map *map)
4878 {
4879 	return map->autoattach;
4880 }
4881 
bpf_map__reuse_fd(struct bpf_map * map,int fd)4882 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4883 {
4884 	struct bpf_map_info info;
4885 	__u32 len = sizeof(info), name_len;
4886 	int new_fd, err;
4887 	char *new_name;
4888 
4889 	memset(&info, 0, len);
4890 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4891 	if (err && errno == EINVAL)
4892 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4893 	if (err)
4894 		return libbpf_err(err);
4895 
4896 	name_len = strlen(info.name);
4897 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4898 		new_name = strdup(map->name);
4899 	else
4900 		new_name = strdup(info.name);
4901 
4902 	if (!new_name)
4903 		return libbpf_err(-errno);
4904 
4905 	/*
4906 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4907 	 * This is similar to what we do in ensure_good_fd(), but without
4908 	 * closing original FD.
4909 	 */
4910 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4911 	if (new_fd < 0) {
4912 		err = -errno;
4913 		goto err_free_new_name;
4914 	}
4915 
4916 	err = reuse_fd(map->fd, new_fd);
4917 	if (err)
4918 		goto err_free_new_name;
4919 
4920 	free(map->name);
4921 
4922 	map->name = new_name;
4923 	map->def.type = info.type;
4924 	map->def.key_size = info.key_size;
4925 	map->def.value_size = info.value_size;
4926 	map->def.max_entries = info.max_entries;
4927 	map->def.map_flags = info.map_flags;
4928 	map->btf_key_type_id = info.btf_key_type_id;
4929 	map->btf_value_type_id = info.btf_value_type_id;
4930 	map->reused = true;
4931 	map->map_extra = info.map_extra;
4932 
4933 	return 0;
4934 
4935 err_free_new_name:
4936 	free(new_name);
4937 	return libbpf_err(err);
4938 }
4939 
bpf_map__max_entries(const struct bpf_map * map)4940 __u32 bpf_map__max_entries(const struct bpf_map *map)
4941 {
4942 	return map->def.max_entries;
4943 }
4944 
bpf_map__inner_map(struct bpf_map * map)4945 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4946 {
4947 	if (!bpf_map_type__is_map_in_map(map->def.type))
4948 		return errno = EINVAL, NULL;
4949 
4950 	return map->inner_map;
4951 }
4952 
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4953 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4954 {
4955 	if (map_is_created(map))
4956 		return libbpf_err(-EBUSY);
4957 
4958 	map->def.max_entries = max_entries;
4959 
4960 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4961 	if (map_is_ringbuf(map))
4962 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4963 
4964 	return 0;
4965 }
4966 
bpf_object_prepare_token(struct bpf_object * obj)4967 static int bpf_object_prepare_token(struct bpf_object *obj)
4968 {
4969 	const char *bpffs_path;
4970 	int bpffs_fd = -1, token_fd, err;
4971 	bool mandatory;
4972 	enum libbpf_print_level level;
4973 
4974 	/* token is explicitly prevented */
4975 	if (obj->token_path && obj->token_path[0] == '\0') {
4976 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4977 		return 0;
4978 	}
4979 
4980 	mandatory = obj->token_path != NULL;
4981 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4982 
4983 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4984 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4985 	if (bpffs_fd < 0) {
4986 		err = -errno;
4987 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
4988 		     obj->name, errstr(err), bpffs_path,
4989 		     mandatory ? "" : ", skipping optional step...");
4990 		return mandatory ? err : 0;
4991 	}
4992 
4993 	token_fd = bpf_token_create(bpffs_fd, 0);
4994 	close(bpffs_fd);
4995 	if (token_fd < 0) {
4996 		if (!mandatory && token_fd == -ENOENT) {
4997 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
4998 				 obj->name, bpffs_path);
4999 			return 0;
5000 		}
5001 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5002 		     obj->name, token_fd, bpffs_path,
5003 		     mandatory ? "" : ", skipping optional step...");
5004 		return mandatory ? token_fd : 0;
5005 	}
5006 
5007 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5008 	if (!obj->feat_cache) {
5009 		close(token_fd);
5010 		return -ENOMEM;
5011 	}
5012 
5013 	obj->token_fd = token_fd;
5014 	obj->feat_cache->token_fd = token_fd;
5015 
5016 	return 0;
5017 }
5018 
5019 static int
bpf_object__probe_loading(struct bpf_object * obj)5020 bpf_object__probe_loading(struct bpf_object *obj)
5021 {
5022 	struct bpf_insn insns[] = {
5023 		BPF_MOV64_IMM(BPF_REG_0, 0),
5024 		BPF_EXIT_INSN(),
5025 	};
5026 	int ret, insn_cnt = ARRAY_SIZE(insns);
5027 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5028 		.token_fd = obj->token_fd,
5029 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5030 	);
5031 
5032 	if (obj->gen_loader)
5033 		return 0;
5034 
5035 	ret = bump_rlimit_memlock();
5036 	if (ret)
5037 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5038 			errstr(ret));
5039 
5040 	/* make sure basic loading works */
5041 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5042 	if (ret < 0)
5043 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5044 	if (ret < 0) {
5045 		ret = errno;
5046 		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",
5047 			__func__, errstr(ret));
5048 		return -ret;
5049 	}
5050 	close(ret);
5051 
5052 	return 0;
5053 }
5054 
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)5055 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5056 {
5057 	if (obj->gen_loader)
5058 		/* To generate loader program assume the latest kernel
5059 		 * to avoid doing extra prog_load, map_create syscalls.
5060 		 */
5061 		return true;
5062 
5063 	if (obj->token_fd)
5064 		return feat_supported(obj->feat_cache, feat_id);
5065 
5066 	return feat_supported(NULL, feat_id);
5067 }
5068 
map_is_reuse_compat(const struct bpf_map * map,int map_fd)5069 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5070 {
5071 	struct bpf_map_info map_info;
5072 	__u32 map_info_len = sizeof(map_info);
5073 	int err;
5074 
5075 	memset(&map_info, 0, map_info_len);
5076 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5077 	if (err && errno == EINVAL)
5078 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5079 	if (err) {
5080 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5081 			errstr(err));
5082 		return false;
5083 	}
5084 
5085 	return (map_info.type == map->def.type &&
5086 		map_info.key_size == map->def.key_size &&
5087 		map_info.value_size == map->def.value_size &&
5088 		map_info.max_entries == map->def.max_entries &&
5089 		map_info.map_flags == map->def.map_flags &&
5090 		map_info.map_extra == map->map_extra);
5091 }
5092 
5093 static int
bpf_object__reuse_map(struct bpf_map * map)5094 bpf_object__reuse_map(struct bpf_map *map)
5095 {
5096 	int err, pin_fd;
5097 
5098 	pin_fd = bpf_obj_get(map->pin_path);
5099 	if (pin_fd < 0) {
5100 		err = -errno;
5101 		if (err == -ENOENT) {
5102 			pr_debug("found no pinned map to reuse at '%s'\n",
5103 				 map->pin_path);
5104 			return 0;
5105 		}
5106 
5107 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5108 			map->pin_path, errstr(err));
5109 		return err;
5110 	}
5111 
5112 	if (!map_is_reuse_compat(map, pin_fd)) {
5113 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5114 			map->pin_path);
5115 		close(pin_fd);
5116 		return -EINVAL;
5117 	}
5118 
5119 	err = bpf_map__reuse_fd(map, pin_fd);
5120 	close(pin_fd);
5121 	if (err)
5122 		return err;
5123 
5124 	map->pinned = true;
5125 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5126 
5127 	return 0;
5128 }
5129 
5130 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5131 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5132 {
5133 	enum libbpf_map_type map_type = map->libbpf_type;
5134 	int err, zero = 0;
5135 	size_t mmap_sz;
5136 
5137 	if (obj->gen_loader) {
5138 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5139 					 map->mmaped, map->def.value_size);
5140 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5141 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5142 		return 0;
5143 	}
5144 
5145 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5146 	if (err) {
5147 		err = -errno;
5148 		pr_warn("map '%s': failed to set initial contents: %s\n",
5149 			bpf_map__name(map), errstr(err));
5150 		return err;
5151 	}
5152 
5153 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5154 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5155 		err = bpf_map_freeze(map->fd);
5156 		if (err) {
5157 			err = -errno;
5158 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5159 				bpf_map__name(map), errstr(err));
5160 			return err;
5161 		}
5162 	}
5163 
5164 	/* Remap anonymous mmap()-ed "map initialization image" as
5165 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5166 	 * memory address. This will cause kernel to change process'
5167 	 * page table to point to a different piece of kernel memory,
5168 	 * but from userspace point of view memory address (and its
5169 	 * contents, being identical at this point) will stay the
5170 	 * same. This mapping will be released by bpf_object__close()
5171 	 * as per normal clean up procedure.
5172 	 */
5173 	mmap_sz = bpf_map_mmap_sz(map);
5174 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5175 		void *mmaped;
5176 		int prot;
5177 
5178 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5179 			prot = PROT_READ;
5180 		else
5181 			prot = PROT_READ | PROT_WRITE;
5182 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5183 		if (mmaped == MAP_FAILED) {
5184 			err = -errno;
5185 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5186 				bpf_map__name(map), errstr(err));
5187 			return err;
5188 		}
5189 		map->mmaped = mmaped;
5190 	} else if (map->mmaped) {
5191 		munmap(map->mmaped, mmap_sz);
5192 		map->mmaped = NULL;
5193 	}
5194 
5195 	return 0;
5196 }
5197 
5198 static void bpf_map__destroy(struct bpf_map *map);
5199 
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5200 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5201 {
5202 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5203 	struct bpf_map_def *def = &map->def;
5204 	const char *map_name = NULL;
5205 	int err = 0, map_fd;
5206 
5207 	if (kernel_supports(obj, FEAT_PROG_NAME))
5208 		map_name = map->name;
5209 	create_attr.map_ifindex = map->map_ifindex;
5210 	create_attr.map_flags = def->map_flags;
5211 	create_attr.numa_node = map->numa_node;
5212 	create_attr.map_extra = map->map_extra;
5213 	create_attr.token_fd = obj->token_fd;
5214 	if (obj->token_fd)
5215 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5216 
5217 	if (bpf_map__is_struct_ops(map)) {
5218 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5219 		if (map->mod_btf_fd >= 0) {
5220 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5221 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5222 		}
5223 	}
5224 
5225 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5226 		create_attr.btf_fd = btf__fd(obj->btf);
5227 		create_attr.btf_key_type_id = map->btf_key_type_id;
5228 		create_attr.btf_value_type_id = map->btf_value_type_id;
5229 	}
5230 
5231 	if (bpf_map_type__is_map_in_map(def->type)) {
5232 		if (map->inner_map) {
5233 			err = map_set_def_max_entries(map->inner_map);
5234 			if (err)
5235 				return err;
5236 			err = bpf_object__create_map(obj, map->inner_map, true);
5237 			if (err) {
5238 				pr_warn("map '%s': failed to create inner map: %s\n",
5239 					map->name, errstr(err));
5240 				return err;
5241 			}
5242 			map->inner_map_fd = map->inner_map->fd;
5243 		}
5244 		if (map->inner_map_fd >= 0)
5245 			create_attr.inner_map_fd = map->inner_map_fd;
5246 	}
5247 
5248 	switch (def->type) {
5249 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5250 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5251 	case BPF_MAP_TYPE_STACK_TRACE:
5252 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5253 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5254 	case BPF_MAP_TYPE_DEVMAP:
5255 	case BPF_MAP_TYPE_DEVMAP_HASH:
5256 	case BPF_MAP_TYPE_CPUMAP:
5257 	case BPF_MAP_TYPE_XSKMAP:
5258 	case BPF_MAP_TYPE_SOCKMAP:
5259 	case BPF_MAP_TYPE_SOCKHASH:
5260 	case BPF_MAP_TYPE_QUEUE:
5261 	case BPF_MAP_TYPE_STACK:
5262 	case BPF_MAP_TYPE_ARENA:
5263 		create_attr.btf_fd = 0;
5264 		create_attr.btf_key_type_id = 0;
5265 		create_attr.btf_value_type_id = 0;
5266 		map->btf_key_type_id = 0;
5267 		map->btf_value_type_id = 0;
5268 		break;
5269 	case BPF_MAP_TYPE_STRUCT_OPS:
5270 		create_attr.btf_value_type_id = 0;
5271 		break;
5272 	default:
5273 		break;
5274 	}
5275 
5276 	if (obj->gen_loader) {
5277 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5278 				    def->key_size, def->value_size, def->max_entries,
5279 				    &create_attr, is_inner ? -1 : map - obj->maps);
5280 		/* We keep pretenting we have valid FD to pass various fd >= 0
5281 		 * checks by just keeping original placeholder FDs in place.
5282 		 * See bpf_object__add_map() comment.
5283 		 * This placeholder fd will not be used with any syscall and
5284 		 * will be reset to -1 eventually.
5285 		 */
5286 		map_fd = map->fd;
5287 	} else {
5288 		map_fd = bpf_map_create(def->type, map_name,
5289 					def->key_size, def->value_size,
5290 					def->max_entries, &create_attr);
5291 	}
5292 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5293 		err = -errno;
5294 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5295 			map->name, errstr(err));
5296 		create_attr.btf_fd = 0;
5297 		create_attr.btf_key_type_id = 0;
5298 		create_attr.btf_value_type_id = 0;
5299 		map->btf_key_type_id = 0;
5300 		map->btf_value_type_id = 0;
5301 		map_fd = bpf_map_create(def->type, map_name,
5302 					def->key_size, def->value_size,
5303 					def->max_entries, &create_attr);
5304 	}
5305 
5306 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5307 		if (obj->gen_loader)
5308 			map->inner_map->fd = -1;
5309 		bpf_map__destroy(map->inner_map);
5310 		zfree(&map->inner_map);
5311 	}
5312 
5313 	if (map_fd < 0)
5314 		return map_fd;
5315 
5316 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5317 	if (map->fd == map_fd)
5318 		return 0;
5319 
5320 	/* Keep placeholder FD value but now point it to the BPF map object.
5321 	 * This way everything that relied on this map's FD (e.g., relocated
5322 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5323 	 * map->fd stays valid but now point to what map_fd points to.
5324 	 */
5325 	return reuse_fd(map->fd, map_fd);
5326 }
5327 
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5328 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5329 {
5330 	const struct bpf_map *targ_map;
5331 	unsigned int i;
5332 	int fd, err = 0;
5333 
5334 	for (i = 0; i < map->init_slots_sz; i++) {
5335 		if (!map->init_slots[i])
5336 			continue;
5337 
5338 		targ_map = map->init_slots[i];
5339 		fd = targ_map->fd;
5340 
5341 		if (obj->gen_loader) {
5342 			bpf_gen__populate_outer_map(obj->gen_loader,
5343 						    map - obj->maps, i,
5344 						    targ_map - obj->maps);
5345 		} else {
5346 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5347 		}
5348 		if (err) {
5349 			err = -errno;
5350 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5351 				map->name, i, targ_map->name, fd, errstr(err));
5352 			return err;
5353 		}
5354 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5355 			 map->name, i, targ_map->name, fd);
5356 	}
5357 
5358 	zfree(&map->init_slots);
5359 	map->init_slots_sz = 0;
5360 
5361 	return 0;
5362 }
5363 
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5364 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5365 {
5366 	const struct bpf_program *targ_prog;
5367 	unsigned int i;
5368 	int fd, err;
5369 
5370 	if (obj->gen_loader)
5371 		return -ENOTSUP;
5372 
5373 	for (i = 0; i < map->init_slots_sz; i++) {
5374 		if (!map->init_slots[i])
5375 			continue;
5376 
5377 		targ_prog = map->init_slots[i];
5378 		fd = bpf_program__fd(targ_prog);
5379 
5380 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5381 		if (err) {
5382 			err = -errno;
5383 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5384 				map->name, i, targ_prog->name, fd, errstr(err));
5385 			return err;
5386 		}
5387 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5388 			 map->name, i, targ_prog->name, fd);
5389 	}
5390 
5391 	zfree(&map->init_slots);
5392 	map->init_slots_sz = 0;
5393 
5394 	return 0;
5395 }
5396 
bpf_object_init_prog_arrays(struct bpf_object * obj)5397 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5398 {
5399 	struct bpf_map *map;
5400 	int i, err;
5401 
5402 	for (i = 0; i < obj->nr_maps; i++) {
5403 		map = &obj->maps[i];
5404 
5405 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5406 			continue;
5407 
5408 		err = init_prog_array_slots(obj, map);
5409 		if (err < 0)
5410 			return err;
5411 	}
5412 	return 0;
5413 }
5414 
map_set_def_max_entries(struct bpf_map * map)5415 static int map_set_def_max_entries(struct bpf_map *map)
5416 {
5417 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5418 		int nr_cpus;
5419 
5420 		nr_cpus = libbpf_num_possible_cpus();
5421 		if (nr_cpus < 0) {
5422 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5423 				map->name, nr_cpus);
5424 			return nr_cpus;
5425 		}
5426 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5427 		map->def.max_entries = nr_cpus;
5428 	}
5429 
5430 	return 0;
5431 }
5432 
5433 static int
bpf_object__create_maps(struct bpf_object * obj)5434 bpf_object__create_maps(struct bpf_object *obj)
5435 {
5436 	struct bpf_map *map;
5437 	unsigned int i, j;
5438 	int err;
5439 	bool retried;
5440 
5441 	for (i = 0; i < obj->nr_maps; i++) {
5442 		map = &obj->maps[i];
5443 
5444 		/* To support old kernels, we skip creating global data maps
5445 		 * (.rodata, .data, .kconfig, etc); later on, during program
5446 		 * loading, if we detect that at least one of the to-be-loaded
5447 		 * programs is referencing any global data map, we'll error
5448 		 * out with program name and relocation index logged.
5449 		 * This approach allows to accommodate Clang emitting
5450 		 * unnecessary .rodata.str1.1 sections for string literals,
5451 		 * but also it allows to have CO-RE applications that use
5452 		 * global variables in some of BPF programs, but not others.
5453 		 * If those global variable-using programs are not loaded at
5454 		 * runtime due to bpf_program__set_autoload(prog, false),
5455 		 * bpf_object loading will succeed just fine even on old
5456 		 * kernels.
5457 		 */
5458 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5459 			map->autocreate = false;
5460 
5461 		if (!map->autocreate) {
5462 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5463 			continue;
5464 		}
5465 
5466 		err = map_set_def_max_entries(map);
5467 		if (err)
5468 			goto err_out;
5469 
5470 		retried = false;
5471 retry:
5472 		if (map->pin_path) {
5473 			err = bpf_object__reuse_map(map);
5474 			if (err) {
5475 				pr_warn("map '%s': error reusing pinned map\n",
5476 					map->name);
5477 				goto err_out;
5478 			}
5479 			if (retried && map->fd < 0) {
5480 				pr_warn("map '%s': cannot find pinned map\n",
5481 					map->name);
5482 				err = -ENOENT;
5483 				goto err_out;
5484 			}
5485 		}
5486 
5487 		if (map->reused) {
5488 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5489 				 map->name, map->fd);
5490 		} else {
5491 			err = bpf_object__create_map(obj, map, false);
5492 			if (err)
5493 				goto err_out;
5494 
5495 			pr_debug("map '%s': created successfully, fd=%d\n",
5496 				 map->name, map->fd);
5497 
5498 			if (bpf_map__is_internal(map)) {
5499 				err = bpf_object__populate_internal_map(obj, map);
5500 				if (err < 0)
5501 					goto err_out;
5502 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5503 				map->mmaped = mmap((void *)(long)map->map_extra,
5504 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5505 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5506 						   map->fd, 0);
5507 				if (map->mmaped == MAP_FAILED) {
5508 					err = -errno;
5509 					map->mmaped = NULL;
5510 					pr_warn("map '%s': failed to mmap arena: %s\n",
5511 						map->name, errstr(err));
5512 					return err;
5513 				}
5514 				if (obj->arena_data) {
5515 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5516 					zfree(&obj->arena_data);
5517 				}
5518 			}
5519 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5520 				err = init_map_in_map_slots(obj, map);
5521 				if (err < 0)
5522 					goto err_out;
5523 			}
5524 		}
5525 
5526 		if (map->pin_path && !map->pinned) {
5527 			err = bpf_map__pin(map, NULL);
5528 			if (err) {
5529 				if (!retried && err == -EEXIST) {
5530 					retried = true;
5531 					goto retry;
5532 				}
5533 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5534 					map->name, map->pin_path, errstr(err));
5535 				goto err_out;
5536 			}
5537 		}
5538 	}
5539 
5540 	return 0;
5541 
5542 err_out:
5543 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5544 	pr_perm_msg(err);
5545 	for (j = 0; j < i; j++)
5546 		zclose(obj->maps[j].fd);
5547 	return err;
5548 }
5549 
bpf_core_is_flavor_sep(const char * s)5550 static bool bpf_core_is_flavor_sep(const char *s)
5551 {
5552 	/* check X___Y name pattern, where X and Y are not underscores */
5553 	return s[0] != '_' &&				      /* X */
5554 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5555 	       s[4] != '_';				      /* Y */
5556 }
5557 
5558 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5559  * before last triple underscore. Struct name part after last triple
5560  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5561  */
bpf_core_essential_name_len(const char * name)5562 size_t bpf_core_essential_name_len(const char *name)
5563 {
5564 	size_t n = strlen(name);
5565 	int i;
5566 
5567 	for (i = n - 5; i >= 0; i--) {
5568 		if (bpf_core_is_flavor_sep(name + i))
5569 			return i + 1;
5570 	}
5571 	return n;
5572 }
5573 
bpf_core_free_cands(struct bpf_core_cand_list * cands)5574 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5575 {
5576 	if (!cands)
5577 		return;
5578 
5579 	free(cands->cands);
5580 	free(cands);
5581 }
5582 
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)5583 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5584 		       size_t local_essent_len,
5585 		       const struct btf *targ_btf,
5586 		       const char *targ_btf_name,
5587 		       int targ_start_id,
5588 		       struct bpf_core_cand_list *cands)
5589 {
5590 	struct bpf_core_cand *new_cands, *cand;
5591 	const struct btf_type *t, *local_t;
5592 	const char *targ_name, *local_name;
5593 	size_t targ_essent_len;
5594 	int n, i;
5595 
5596 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5597 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5598 
5599 	n = btf__type_cnt(targ_btf);
5600 	for (i = targ_start_id; i < n; i++) {
5601 		t = btf__type_by_id(targ_btf, i);
5602 		if (!btf_kind_core_compat(t, local_t))
5603 			continue;
5604 
5605 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5606 		if (str_is_empty(targ_name))
5607 			continue;
5608 
5609 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5610 		if (targ_essent_len != local_essent_len)
5611 			continue;
5612 
5613 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5614 			continue;
5615 
5616 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5617 			 local_cand->id, btf_kind_str(local_t),
5618 			 local_name, i, btf_kind_str(t), targ_name,
5619 			 targ_btf_name);
5620 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5621 					      sizeof(*cands->cands));
5622 		if (!new_cands)
5623 			return -ENOMEM;
5624 
5625 		cand = &new_cands[cands->len];
5626 		cand->btf = targ_btf;
5627 		cand->id = i;
5628 
5629 		cands->cands = new_cands;
5630 		cands->len++;
5631 	}
5632 	return 0;
5633 }
5634 
load_module_btfs(struct bpf_object * obj)5635 static int load_module_btfs(struct bpf_object *obj)
5636 {
5637 	struct bpf_btf_info info;
5638 	struct module_btf *mod_btf;
5639 	struct btf *btf;
5640 	char name[64];
5641 	__u32 id = 0, len;
5642 	int err, fd;
5643 
5644 	if (obj->btf_modules_loaded)
5645 		return 0;
5646 
5647 	if (obj->gen_loader)
5648 		return 0;
5649 
5650 	/* don't do this again, even if we find no module BTFs */
5651 	obj->btf_modules_loaded = true;
5652 
5653 	/* kernel too old to support module BTFs */
5654 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5655 		return 0;
5656 
5657 	while (true) {
5658 		err = bpf_btf_get_next_id(id, &id);
5659 		if (err && errno == ENOENT)
5660 			return 0;
5661 		if (err && errno == EPERM) {
5662 			pr_debug("skipping module BTFs loading, missing privileges\n");
5663 			return 0;
5664 		}
5665 		if (err) {
5666 			err = -errno;
5667 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5668 			return err;
5669 		}
5670 
5671 		fd = bpf_btf_get_fd_by_id(id);
5672 		if (fd < 0) {
5673 			if (errno == ENOENT)
5674 				continue; /* expected race: BTF was unloaded */
5675 			err = -errno;
5676 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5677 			return err;
5678 		}
5679 
5680 		len = sizeof(info);
5681 		memset(&info, 0, sizeof(info));
5682 		info.name = ptr_to_u64(name);
5683 		info.name_len = sizeof(name);
5684 
5685 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5686 		if (err) {
5687 			err = -errno;
5688 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5689 			goto err_out;
5690 		}
5691 
5692 		/* ignore non-module BTFs */
5693 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5694 			close(fd);
5695 			continue;
5696 		}
5697 
5698 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5699 		err = libbpf_get_error(btf);
5700 		if (err) {
5701 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5702 				name, id, errstr(err));
5703 			goto err_out;
5704 		}
5705 
5706 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5707 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5708 		if (err)
5709 			goto err_out;
5710 
5711 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5712 
5713 		mod_btf->btf = btf;
5714 		mod_btf->id = id;
5715 		mod_btf->fd = fd;
5716 		mod_btf->name = strdup(name);
5717 		if (!mod_btf->name) {
5718 			err = -ENOMEM;
5719 			goto err_out;
5720 		}
5721 		continue;
5722 
5723 err_out:
5724 		close(fd);
5725 		return err;
5726 	}
5727 
5728 	return 0;
5729 }
5730 
5731 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5732 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5733 {
5734 	struct bpf_core_cand local_cand = {};
5735 	struct bpf_core_cand_list *cands;
5736 	const struct btf *main_btf;
5737 	const struct btf_type *local_t;
5738 	const char *local_name;
5739 	size_t local_essent_len;
5740 	int err, i;
5741 
5742 	local_cand.btf = local_btf;
5743 	local_cand.id = local_type_id;
5744 	local_t = btf__type_by_id(local_btf, local_type_id);
5745 	if (!local_t)
5746 		return ERR_PTR(-EINVAL);
5747 
5748 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5749 	if (str_is_empty(local_name))
5750 		return ERR_PTR(-EINVAL);
5751 	local_essent_len = bpf_core_essential_name_len(local_name);
5752 
5753 	cands = calloc(1, sizeof(*cands));
5754 	if (!cands)
5755 		return ERR_PTR(-ENOMEM);
5756 
5757 	/* Attempt to find target candidates in vmlinux BTF first */
5758 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5759 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5760 	if (err)
5761 		goto err_out;
5762 
5763 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5764 	if (cands->len)
5765 		return cands;
5766 
5767 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5768 	if (obj->btf_vmlinux_override)
5769 		return cands;
5770 
5771 	/* now look through module BTFs, trying to still find candidates */
5772 	err = load_module_btfs(obj);
5773 	if (err)
5774 		goto err_out;
5775 
5776 	for (i = 0; i < obj->btf_module_cnt; i++) {
5777 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5778 					 obj->btf_modules[i].btf,
5779 					 obj->btf_modules[i].name,
5780 					 btf__type_cnt(obj->btf_vmlinux),
5781 					 cands);
5782 		if (err)
5783 			goto err_out;
5784 	}
5785 
5786 	return cands;
5787 err_out:
5788 	bpf_core_free_cands(cands);
5789 	return ERR_PTR(err);
5790 }
5791 
5792 /* Check local and target types for compatibility. This check is used for
5793  * type-based CO-RE relocations and follow slightly different rules than
5794  * field-based relocations. This function assumes that root types were already
5795  * checked for name match. Beyond that initial root-level name check, names
5796  * are completely ignored. Compatibility rules are as follows:
5797  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5798  *     kind should match for local and target types (i.e., STRUCT is not
5799  *     compatible with UNION);
5800  *   - for ENUMs, the size is ignored;
5801  *   - for INT, size and signedness are ignored;
5802  *   - for ARRAY, dimensionality is ignored, element types are checked for
5803  *     compatibility recursively;
5804  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5805  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5806  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5807  *     number of input args and compatible return and argument types.
5808  * These rules are not set in stone and probably will be adjusted as we get
5809  * more experience with using BPF CO-RE relocations.
5810  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5811 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5812 			      const struct btf *targ_btf, __u32 targ_id)
5813 {
5814 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5815 }
5816 
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5817 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5818 			 const struct btf *targ_btf, __u32 targ_id)
5819 {
5820 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5821 }
5822 
bpf_core_hash_fn(const long key,void * ctx)5823 static size_t bpf_core_hash_fn(const long key, void *ctx)
5824 {
5825 	return key;
5826 }
5827 
bpf_core_equal_fn(const long k1,const long k2,void * ctx)5828 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5829 {
5830 	return k1 == k2;
5831 }
5832 
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5833 static int record_relo_core(struct bpf_program *prog,
5834 			    const struct bpf_core_relo *core_relo, int insn_idx)
5835 {
5836 	struct reloc_desc *relos, *relo;
5837 
5838 	relos = libbpf_reallocarray(prog->reloc_desc,
5839 				    prog->nr_reloc + 1, sizeof(*relos));
5840 	if (!relos)
5841 		return -ENOMEM;
5842 	relo = &relos[prog->nr_reloc];
5843 	relo->type = RELO_CORE;
5844 	relo->insn_idx = insn_idx;
5845 	relo->core_relo = core_relo;
5846 	prog->reloc_desc = relos;
5847 	prog->nr_reloc++;
5848 	return 0;
5849 }
5850 
find_relo_core(struct bpf_program * prog,int insn_idx)5851 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5852 {
5853 	struct reloc_desc *relo;
5854 	int i;
5855 
5856 	for (i = 0; i < prog->nr_reloc; i++) {
5857 		relo = &prog->reloc_desc[i];
5858 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5859 			continue;
5860 
5861 		return relo->core_relo;
5862 	}
5863 
5864 	return NULL;
5865 }
5866 
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)5867 static int bpf_core_resolve_relo(struct bpf_program *prog,
5868 				 const struct bpf_core_relo *relo,
5869 				 int relo_idx,
5870 				 const struct btf *local_btf,
5871 				 struct hashmap *cand_cache,
5872 				 struct bpf_core_relo_res *targ_res)
5873 {
5874 	struct bpf_core_spec specs_scratch[3] = {};
5875 	struct bpf_core_cand_list *cands = NULL;
5876 	const char *prog_name = prog->name;
5877 	const struct btf_type *local_type;
5878 	const char *local_name;
5879 	__u32 local_id = relo->type_id;
5880 	int err;
5881 
5882 	local_type = btf__type_by_id(local_btf, local_id);
5883 	if (!local_type)
5884 		return -EINVAL;
5885 
5886 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5887 	if (!local_name)
5888 		return -EINVAL;
5889 
5890 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5891 	    !hashmap__find(cand_cache, local_id, &cands)) {
5892 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5893 		if (IS_ERR(cands)) {
5894 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5895 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5896 				local_name, PTR_ERR(cands));
5897 			return PTR_ERR(cands);
5898 		}
5899 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5900 		if (err) {
5901 			bpf_core_free_cands(cands);
5902 			return err;
5903 		}
5904 	}
5905 
5906 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5907 				       targ_res);
5908 }
5909 
5910 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5911 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5912 {
5913 	const struct btf_ext_info_sec *sec;
5914 	struct bpf_core_relo_res targ_res;
5915 	const struct bpf_core_relo *rec;
5916 	const struct btf_ext_info *seg;
5917 	struct hashmap_entry *entry;
5918 	struct hashmap *cand_cache = NULL;
5919 	struct bpf_program *prog;
5920 	struct bpf_insn *insn;
5921 	const char *sec_name;
5922 	int i, err = 0, insn_idx, sec_idx, sec_num;
5923 
5924 	if (obj->btf_ext->core_relo_info.len == 0)
5925 		return 0;
5926 
5927 	if (targ_btf_path) {
5928 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5929 		err = libbpf_get_error(obj->btf_vmlinux_override);
5930 		if (err) {
5931 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
5932 			return err;
5933 		}
5934 	}
5935 
5936 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5937 	if (IS_ERR(cand_cache)) {
5938 		err = PTR_ERR(cand_cache);
5939 		goto out;
5940 	}
5941 
5942 	seg = &obj->btf_ext->core_relo_info;
5943 	sec_num = 0;
5944 	for_each_btf_ext_sec(seg, sec) {
5945 		sec_idx = seg->sec_idxs[sec_num];
5946 		sec_num++;
5947 
5948 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5949 		if (str_is_empty(sec_name)) {
5950 			err = -EINVAL;
5951 			goto out;
5952 		}
5953 
5954 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5955 
5956 		for_each_btf_ext_rec(seg, sec, i, rec) {
5957 			if (rec->insn_off % BPF_INSN_SZ)
5958 				return -EINVAL;
5959 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5960 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5961 			if (!prog) {
5962 				/* When __weak subprog is "overridden" by another instance
5963 				 * of the subprog from a different object file, linker still
5964 				 * appends all the .BTF.ext info that used to belong to that
5965 				 * eliminated subprogram.
5966 				 * This is similar to what x86-64 linker does for relocations.
5967 				 * So just ignore such relocations just like we ignore
5968 				 * subprog instructions when discovering subprograms.
5969 				 */
5970 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5971 					 sec_name, i, insn_idx);
5972 				continue;
5973 			}
5974 			/* no need to apply CO-RE relocation if the program is
5975 			 * not going to be loaded
5976 			 */
5977 			if (!prog->autoload)
5978 				continue;
5979 
5980 			/* adjust insn_idx from section frame of reference to the local
5981 			 * program's frame of reference; (sub-)program code is not yet
5982 			 * relocated, so it's enough to just subtract in-section offset
5983 			 */
5984 			insn_idx = insn_idx - prog->sec_insn_off;
5985 			if (insn_idx >= prog->insns_cnt)
5986 				return -EINVAL;
5987 			insn = &prog->insns[insn_idx];
5988 
5989 			err = record_relo_core(prog, rec, insn_idx);
5990 			if (err) {
5991 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
5992 					prog->name, i, errstr(err));
5993 				goto out;
5994 			}
5995 
5996 			if (prog->obj->gen_loader)
5997 				continue;
5998 
5999 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6000 			if (err) {
6001 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6002 					prog->name, i, errstr(err));
6003 				goto out;
6004 			}
6005 
6006 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6007 			if (err) {
6008 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6009 					prog->name, i, insn_idx, errstr(err));
6010 				goto out;
6011 			}
6012 		}
6013 	}
6014 
6015 out:
6016 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6017 	btf__free(obj->btf_vmlinux_override);
6018 	obj->btf_vmlinux_override = NULL;
6019 
6020 	if (!IS_ERR_OR_NULL(cand_cache)) {
6021 		hashmap__for_each_entry(cand_cache, entry, i) {
6022 			bpf_core_free_cands(entry->pvalue);
6023 		}
6024 		hashmap__free(cand_cache);
6025 	}
6026 	return err;
6027 }
6028 
6029 /* base map load ldimm64 special constant, used also for log fixup logic */
6030 #define POISON_LDIMM64_MAP_BASE 2001000000
6031 #define POISON_LDIMM64_MAP_PFX "200100"
6032 
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)6033 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6034 			       int insn_idx, struct bpf_insn *insn,
6035 			       int map_idx, const struct bpf_map *map)
6036 {
6037 	int i;
6038 
6039 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6040 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6041 
6042 	/* we turn single ldimm64 into two identical invalid calls */
6043 	for (i = 0; i < 2; i++) {
6044 		insn->code = BPF_JMP | BPF_CALL;
6045 		insn->dst_reg = 0;
6046 		insn->src_reg = 0;
6047 		insn->off = 0;
6048 		/* if this instruction is reachable (not a dead code),
6049 		 * verifier will complain with something like:
6050 		 * invalid func unknown#2001000123
6051 		 * where lower 123 is map index into obj->maps[] array
6052 		 */
6053 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6054 
6055 		insn++;
6056 	}
6057 }
6058 
6059 /* unresolved kfunc call special constant, used also for log fixup logic */
6060 #define POISON_CALL_KFUNC_BASE 2002000000
6061 #define POISON_CALL_KFUNC_PFX "2002"
6062 
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)6063 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6064 			      int insn_idx, struct bpf_insn *insn,
6065 			      int ext_idx, const struct extern_desc *ext)
6066 {
6067 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6068 		 prog->name, relo_idx, insn_idx, ext->name);
6069 
6070 	/* we turn kfunc call into invalid helper call with identifiable constant */
6071 	insn->code = BPF_JMP | BPF_CALL;
6072 	insn->dst_reg = 0;
6073 	insn->src_reg = 0;
6074 	insn->off = 0;
6075 	/* if this instruction is reachable (not a dead code),
6076 	 * verifier will complain with something like:
6077 	 * invalid func unknown#2001000123
6078 	 * where lower 123 is extern index into obj->externs[] array
6079 	 */
6080 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6081 }
6082 
6083 /* Relocate data references within program code:
6084  *  - map references;
6085  *  - global variable references;
6086  *  - extern references.
6087  */
6088 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)6089 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6090 {
6091 	int i;
6092 
6093 	for (i = 0; i < prog->nr_reloc; i++) {
6094 		struct reloc_desc *relo = &prog->reloc_desc[i];
6095 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6096 		const struct bpf_map *map;
6097 		struct extern_desc *ext;
6098 
6099 		switch (relo->type) {
6100 		case RELO_LD64:
6101 			map = &obj->maps[relo->map_idx];
6102 			if (obj->gen_loader) {
6103 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6104 				insn[0].imm = relo->map_idx;
6105 			} else if (map->autocreate) {
6106 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6107 				insn[0].imm = map->fd;
6108 			} else {
6109 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6110 						   relo->map_idx, map);
6111 			}
6112 			break;
6113 		case RELO_DATA:
6114 			map = &obj->maps[relo->map_idx];
6115 			insn[1].imm = insn[0].imm + relo->sym_off;
6116 			if (obj->gen_loader) {
6117 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6118 				insn[0].imm = relo->map_idx;
6119 			} else if (map->autocreate) {
6120 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6121 				insn[0].imm = map->fd;
6122 			} else {
6123 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6124 						   relo->map_idx, map);
6125 			}
6126 			break;
6127 		case RELO_EXTERN_LD64:
6128 			ext = &obj->externs[relo->ext_idx];
6129 			if (ext->type == EXT_KCFG) {
6130 				if (obj->gen_loader) {
6131 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6132 					insn[0].imm = obj->kconfig_map_idx;
6133 				} else {
6134 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6135 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6136 				}
6137 				insn[1].imm = ext->kcfg.data_off;
6138 			} else /* EXT_KSYM */ {
6139 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6140 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6141 					insn[0].imm = ext->ksym.kernel_btf_id;
6142 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6143 				} else { /* typeless ksyms or unresolved typed ksyms */
6144 					insn[0].imm = (__u32)ext->ksym.addr;
6145 					insn[1].imm = ext->ksym.addr >> 32;
6146 				}
6147 			}
6148 			break;
6149 		case RELO_EXTERN_CALL:
6150 			ext = &obj->externs[relo->ext_idx];
6151 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6152 			if (ext->is_set) {
6153 				insn[0].imm = ext->ksym.kernel_btf_id;
6154 				insn[0].off = ext->ksym.btf_fd_idx;
6155 			} else { /* unresolved weak kfunc call */
6156 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6157 						  relo->ext_idx, ext);
6158 			}
6159 			break;
6160 		case RELO_SUBPROG_ADDR:
6161 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6162 				pr_warn("prog '%s': relo #%d: bad insn\n",
6163 					prog->name, i);
6164 				return -EINVAL;
6165 			}
6166 			/* handled already */
6167 			break;
6168 		case RELO_CALL:
6169 			/* handled already */
6170 			break;
6171 		case RELO_CORE:
6172 			/* will be handled by bpf_program_record_relos() */
6173 			break;
6174 		default:
6175 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6176 				prog->name, i, relo->type);
6177 			return -EINVAL;
6178 		}
6179 	}
6180 
6181 	return 0;
6182 }
6183 
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)6184 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6185 				    const struct bpf_program *prog,
6186 				    const struct btf_ext_info *ext_info,
6187 				    void **prog_info, __u32 *prog_rec_cnt,
6188 				    __u32 *prog_rec_sz)
6189 {
6190 	void *copy_start = NULL, *copy_end = NULL;
6191 	void *rec, *rec_end, *new_prog_info;
6192 	const struct btf_ext_info_sec *sec;
6193 	size_t old_sz, new_sz;
6194 	int i, sec_num, sec_idx, off_adj;
6195 
6196 	sec_num = 0;
6197 	for_each_btf_ext_sec(ext_info, sec) {
6198 		sec_idx = ext_info->sec_idxs[sec_num];
6199 		sec_num++;
6200 		if (prog->sec_idx != sec_idx)
6201 			continue;
6202 
6203 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6204 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6205 
6206 			if (insn_off < prog->sec_insn_off)
6207 				continue;
6208 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6209 				break;
6210 
6211 			if (!copy_start)
6212 				copy_start = rec;
6213 			copy_end = rec + ext_info->rec_size;
6214 		}
6215 
6216 		if (!copy_start)
6217 			return -ENOENT;
6218 
6219 		/* append func/line info of a given (sub-)program to the main
6220 		 * program func/line info
6221 		 */
6222 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6223 		new_sz = old_sz + (copy_end - copy_start);
6224 		new_prog_info = realloc(*prog_info, new_sz);
6225 		if (!new_prog_info)
6226 			return -ENOMEM;
6227 		*prog_info = new_prog_info;
6228 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6229 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6230 
6231 		/* Kernel instruction offsets are in units of 8-byte
6232 		 * instructions, while .BTF.ext instruction offsets generated
6233 		 * by Clang are in units of bytes. So convert Clang offsets
6234 		 * into kernel offsets and adjust offset according to program
6235 		 * relocated position.
6236 		 */
6237 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6238 		rec = new_prog_info + old_sz;
6239 		rec_end = new_prog_info + new_sz;
6240 		for (; rec < rec_end; rec += ext_info->rec_size) {
6241 			__u32 *insn_off = rec;
6242 
6243 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6244 		}
6245 		*prog_rec_sz = ext_info->rec_size;
6246 		return 0;
6247 	}
6248 
6249 	return -ENOENT;
6250 }
6251 
6252 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6253 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6254 			      struct bpf_program *main_prog,
6255 			      const struct bpf_program *prog)
6256 {
6257 	int err;
6258 
6259 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6260 	 * support func/line info
6261 	 */
6262 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6263 		return 0;
6264 
6265 	/* only attempt func info relocation if main program's func_info
6266 	 * relocation was successful
6267 	 */
6268 	if (main_prog != prog && !main_prog->func_info)
6269 		goto line_info;
6270 
6271 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6272 				       &main_prog->func_info,
6273 				       &main_prog->func_info_cnt,
6274 				       &main_prog->func_info_rec_size);
6275 	if (err) {
6276 		if (err != -ENOENT) {
6277 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6278 				prog->name, errstr(err));
6279 			return err;
6280 		}
6281 		if (main_prog->func_info) {
6282 			/*
6283 			 * Some info has already been found but has problem
6284 			 * in the last btf_ext reloc. Must have to error out.
6285 			 */
6286 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6287 			return err;
6288 		}
6289 		/* Have problem loading the very first info. Ignore the rest. */
6290 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6291 			prog->name);
6292 	}
6293 
6294 line_info:
6295 	/* don't relocate line info if main program's relocation failed */
6296 	if (main_prog != prog && !main_prog->line_info)
6297 		return 0;
6298 
6299 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6300 				       &main_prog->line_info,
6301 				       &main_prog->line_info_cnt,
6302 				       &main_prog->line_info_rec_size);
6303 	if (err) {
6304 		if (err != -ENOENT) {
6305 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6306 				prog->name, errstr(err));
6307 			return err;
6308 		}
6309 		if (main_prog->line_info) {
6310 			/*
6311 			 * Some info has already been found but has problem
6312 			 * in the last btf_ext reloc. Must have to error out.
6313 			 */
6314 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6315 			return err;
6316 		}
6317 		/* Have problem loading the very first info. Ignore the rest. */
6318 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6319 			prog->name);
6320 	}
6321 	return 0;
6322 }
6323 
cmp_relo_by_insn_idx(const void * key,const void * elem)6324 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6325 {
6326 	size_t insn_idx = *(const size_t *)key;
6327 	const struct reloc_desc *relo = elem;
6328 
6329 	if (insn_idx == relo->insn_idx)
6330 		return 0;
6331 	return insn_idx < relo->insn_idx ? -1 : 1;
6332 }
6333 
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6334 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6335 {
6336 	if (!prog->nr_reloc)
6337 		return NULL;
6338 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6339 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6340 }
6341 
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6342 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6343 {
6344 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6345 	struct reloc_desc *relos;
6346 	int i;
6347 
6348 	if (main_prog == subprog)
6349 		return 0;
6350 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6351 	/* if new count is zero, reallocarray can return a valid NULL result;
6352 	 * in this case the previous pointer will be freed, so we *have to*
6353 	 * reassign old pointer to the new value (even if it's NULL)
6354 	 */
6355 	if (!relos && new_cnt)
6356 		return -ENOMEM;
6357 	if (subprog->nr_reloc)
6358 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6359 		       sizeof(*relos) * subprog->nr_reloc);
6360 
6361 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6362 		relos[i].insn_idx += subprog->sub_insn_off;
6363 	/* After insn_idx adjustment the 'relos' array is still sorted
6364 	 * by insn_idx and doesn't break bsearch.
6365 	 */
6366 	main_prog->reloc_desc = relos;
6367 	main_prog->nr_reloc = new_cnt;
6368 	return 0;
6369 }
6370 
6371 static int
bpf_object__append_subprog_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * subprog)6372 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6373 				struct bpf_program *subprog)
6374 {
6375        struct bpf_insn *insns;
6376        size_t new_cnt;
6377        int err;
6378 
6379        subprog->sub_insn_off = main_prog->insns_cnt;
6380 
6381        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6382        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6383        if (!insns) {
6384                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6385                return -ENOMEM;
6386        }
6387        main_prog->insns = insns;
6388        main_prog->insns_cnt = new_cnt;
6389 
6390        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6391               subprog->insns_cnt * sizeof(*insns));
6392 
6393        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6394                 main_prog->name, subprog->insns_cnt, subprog->name);
6395 
6396        /* The subprog insns are now appended. Append its relos too. */
6397        err = append_subprog_relos(main_prog, subprog);
6398        if (err)
6399                return err;
6400        return 0;
6401 }
6402 
6403 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6404 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6405 		       struct bpf_program *prog)
6406 {
6407 	size_t sub_insn_idx, insn_idx;
6408 	struct bpf_program *subprog;
6409 	struct reloc_desc *relo;
6410 	struct bpf_insn *insn;
6411 	int err;
6412 
6413 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6414 	if (err)
6415 		return err;
6416 
6417 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6418 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6419 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6420 			continue;
6421 
6422 		relo = find_prog_insn_relo(prog, insn_idx);
6423 		if (relo && relo->type == RELO_EXTERN_CALL)
6424 			/* kfunc relocations will be handled later
6425 			 * in bpf_object__relocate_data()
6426 			 */
6427 			continue;
6428 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6429 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6430 				prog->name, insn_idx, relo->type);
6431 			return -LIBBPF_ERRNO__RELOC;
6432 		}
6433 		if (relo) {
6434 			/* sub-program instruction index is a combination of
6435 			 * an offset of a symbol pointed to by relocation and
6436 			 * call instruction's imm field; for global functions,
6437 			 * call always has imm = -1, but for static functions
6438 			 * relocation is against STT_SECTION and insn->imm
6439 			 * points to a start of a static function
6440 			 *
6441 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6442 			 * the byte offset in the corresponding section.
6443 			 */
6444 			if (relo->type == RELO_CALL)
6445 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6446 			else
6447 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6448 		} else if (insn_is_pseudo_func(insn)) {
6449 			/*
6450 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6451 			 * functions are in the same section, so it shouldn't reach here.
6452 			 */
6453 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6454 				prog->name, insn_idx);
6455 			return -LIBBPF_ERRNO__RELOC;
6456 		} else {
6457 			/* if subprogram call is to a static function within
6458 			 * the same ELF section, there won't be any relocation
6459 			 * emitted, but it also means there is no additional
6460 			 * offset necessary, insns->imm is relative to
6461 			 * instruction's original position within the section
6462 			 */
6463 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6464 		}
6465 
6466 		/* we enforce that sub-programs should be in .text section */
6467 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6468 		if (!subprog) {
6469 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6470 				prog->name);
6471 			return -LIBBPF_ERRNO__RELOC;
6472 		}
6473 
6474 		/* if it's the first call instruction calling into this
6475 		 * subprogram (meaning this subprog hasn't been processed
6476 		 * yet) within the context of current main program:
6477 		 *   - append it at the end of main program's instructions blog;
6478 		 *   - process is recursively, while current program is put on hold;
6479 		 *   - if that subprogram calls some other not yet processes
6480 		 *   subprogram, same thing will happen recursively until
6481 		 *   there are no more unprocesses subprograms left to append
6482 		 *   and relocate.
6483 		 */
6484 		if (subprog->sub_insn_off == 0) {
6485 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6486 			if (err)
6487 				return err;
6488 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6489 			if (err)
6490 				return err;
6491 		}
6492 
6493 		/* main_prog->insns memory could have been re-allocated, so
6494 		 * calculate pointer again
6495 		 */
6496 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6497 		/* calculate correct instruction position within current main
6498 		 * prog; each main prog can have a different set of
6499 		 * subprograms appended (potentially in different order as
6500 		 * well), so position of any subprog can be different for
6501 		 * different main programs
6502 		 */
6503 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6504 
6505 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6506 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6507 	}
6508 
6509 	return 0;
6510 }
6511 
6512 /*
6513  * Relocate sub-program calls.
6514  *
6515  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6516  * main prog) is processed separately. For each subprog (non-entry functions,
6517  * that can be called from either entry progs or other subprogs) gets their
6518  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6519  * hasn't been yet appended and relocated within current main prog. Once its
6520  * relocated, sub_insn_off will point at the position within current main prog
6521  * where given subprog was appended. This will further be used to relocate all
6522  * the call instructions jumping into this subprog.
6523  *
6524  * We start with main program and process all call instructions. If the call
6525  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6526  * is zero), subprog instructions are appended at the end of main program's
6527  * instruction array. Then main program is "put on hold" while we recursively
6528  * process newly appended subprogram. If that subprogram calls into another
6529  * subprogram that hasn't been appended, new subprogram is appended again to
6530  * the *main* prog's instructions (subprog's instructions are always left
6531  * untouched, as they need to be in unmodified state for subsequent main progs
6532  * and subprog instructions are always sent only as part of a main prog) and
6533  * the process continues recursively. Once all the subprogs called from a main
6534  * prog or any of its subprogs are appended (and relocated), all their
6535  * positions within finalized instructions array are known, so it's easy to
6536  * rewrite call instructions with correct relative offsets, corresponding to
6537  * desired target subprog.
6538  *
6539  * Its important to realize that some subprogs might not be called from some
6540  * main prog and any of its called/used subprogs. Those will keep their
6541  * subprog->sub_insn_off as zero at all times and won't be appended to current
6542  * main prog and won't be relocated within the context of current main prog.
6543  * They might still be used from other main progs later.
6544  *
6545  * Visually this process can be shown as below. Suppose we have two main
6546  * programs mainA and mainB and BPF object contains three subprogs: subA,
6547  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6548  * subC both call subB:
6549  *
6550  *        +--------+ +-------+
6551  *        |        v v       |
6552  *     +--+---+ +--+-+-+ +---+--+
6553  *     | subA | | subB | | subC |
6554  *     +--+---+ +------+ +---+--+
6555  *        ^                  ^
6556  *        |                  |
6557  *    +---+-------+   +------+----+
6558  *    |   mainA   |   |   mainB   |
6559  *    +-----------+   +-----------+
6560  *
6561  * We'll start relocating mainA, will find subA, append it and start
6562  * processing sub A recursively:
6563  *
6564  *    +-----------+------+
6565  *    |   mainA   | subA |
6566  *    +-----------+------+
6567  *
6568  * At this point we notice that subB is used from subA, so we append it and
6569  * relocate (there are no further subcalls from subB):
6570  *
6571  *    +-----------+------+------+
6572  *    |   mainA   | subA | subB |
6573  *    +-----------+------+------+
6574  *
6575  * At this point, we relocate subA calls, then go one level up and finish with
6576  * relocatin mainA calls. mainA is done.
6577  *
6578  * For mainB process is similar but results in different order. We start with
6579  * mainB and skip subA and subB, as mainB never calls them (at least
6580  * directly), but we see subC is needed, so we append and start processing it:
6581  *
6582  *    +-----------+------+
6583  *    |   mainB   | subC |
6584  *    +-----------+------+
6585  * Now we see subC needs subB, so we go back to it, append and relocate it:
6586  *
6587  *    +-----------+------+------+
6588  *    |   mainB   | subC | subB |
6589  *    +-----------+------+------+
6590  *
6591  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6592  */
6593 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6594 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6595 {
6596 	struct bpf_program *subprog;
6597 	int i, err;
6598 
6599 	/* mark all subprogs as not relocated (yet) within the context of
6600 	 * current main program
6601 	 */
6602 	for (i = 0; i < obj->nr_programs; i++) {
6603 		subprog = &obj->programs[i];
6604 		if (!prog_is_subprog(obj, subprog))
6605 			continue;
6606 
6607 		subprog->sub_insn_off = 0;
6608 	}
6609 
6610 	err = bpf_object__reloc_code(obj, prog, prog);
6611 	if (err)
6612 		return err;
6613 
6614 	return 0;
6615 }
6616 
6617 static void
bpf_object__free_relocs(struct bpf_object * obj)6618 bpf_object__free_relocs(struct bpf_object *obj)
6619 {
6620 	struct bpf_program *prog;
6621 	int i;
6622 
6623 	/* free up relocation descriptors */
6624 	for (i = 0; i < obj->nr_programs; i++) {
6625 		prog = &obj->programs[i];
6626 		zfree(&prog->reloc_desc);
6627 		prog->nr_reloc = 0;
6628 	}
6629 }
6630 
cmp_relocs(const void * _a,const void * _b)6631 static int cmp_relocs(const void *_a, const void *_b)
6632 {
6633 	const struct reloc_desc *a = _a;
6634 	const struct reloc_desc *b = _b;
6635 
6636 	if (a->insn_idx != b->insn_idx)
6637 		return a->insn_idx < b->insn_idx ? -1 : 1;
6638 
6639 	/* no two relocations should have the same insn_idx, but ... */
6640 	if (a->type != b->type)
6641 		return a->type < b->type ? -1 : 1;
6642 
6643 	return 0;
6644 }
6645 
bpf_object__sort_relos(struct bpf_object * obj)6646 static void bpf_object__sort_relos(struct bpf_object *obj)
6647 {
6648 	int i;
6649 
6650 	for (i = 0; i < obj->nr_programs; i++) {
6651 		struct bpf_program *p = &obj->programs[i];
6652 
6653 		if (!p->nr_reloc)
6654 			continue;
6655 
6656 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6657 	}
6658 }
6659 
bpf_prog_assign_exc_cb(struct bpf_object * obj,struct bpf_program * prog)6660 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6661 {
6662 	const char *str = "exception_callback:";
6663 	size_t pfx_len = strlen(str);
6664 	int i, j, n;
6665 
6666 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6667 		return 0;
6668 
6669 	n = btf__type_cnt(obj->btf);
6670 	for (i = 1; i < n; i++) {
6671 		const char *name;
6672 		struct btf_type *t;
6673 
6674 		t = btf_type_by_id(obj->btf, i);
6675 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6676 			continue;
6677 
6678 		name = btf__str_by_offset(obj->btf, t->name_off);
6679 		if (strncmp(name, str, pfx_len) != 0)
6680 			continue;
6681 
6682 		t = btf_type_by_id(obj->btf, t->type);
6683 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6684 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6685 				prog->name);
6686 			return -EINVAL;
6687 		}
6688 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6689 			continue;
6690 		/* Multiple callbacks are specified for the same prog,
6691 		 * the verifier will eventually return an error for this
6692 		 * case, hence simply skip appending a subprog.
6693 		 */
6694 		if (prog->exception_cb_idx >= 0) {
6695 			prog->exception_cb_idx = -1;
6696 			break;
6697 		}
6698 
6699 		name += pfx_len;
6700 		if (str_is_empty(name)) {
6701 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6702 				prog->name);
6703 			return -EINVAL;
6704 		}
6705 
6706 		for (j = 0; j < obj->nr_programs; j++) {
6707 			struct bpf_program *subprog = &obj->programs[j];
6708 
6709 			if (!prog_is_subprog(obj, subprog))
6710 				continue;
6711 			if (strcmp(name, subprog->name) != 0)
6712 				continue;
6713 			/* Enforce non-hidden, as from verifier point of
6714 			 * view it expects global functions, whereas the
6715 			 * mark_btf_static fixes up linkage as static.
6716 			 */
6717 			if (!subprog->sym_global || subprog->mark_btf_static) {
6718 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6719 					prog->name, subprog->name);
6720 				return -EINVAL;
6721 			}
6722 			/* Let's see if we already saw a static exception callback with the same name */
6723 			if (prog->exception_cb_idx >= 0) {
6724 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6725 					prog->name, subprog->name);
6726 				return -EINVAL;
6727 			}
6728 			prog->exception_cb_idx = j;
6729 			break;
6730 		}
6731 
6732 		if (prog->exception_cb_idx >= 0)
6733 			continue;
6734 
6735 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6736 		return -ENOENT;
6737 	}
6738 
6739 	return 0;
6740 }
6741 
6742 static struct {
6743 	enum bpf_prog_type prog_type;
6744 	const char *ctx_name;
6745 } global_ctx_map[] = {
6746 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6747 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6748 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6749 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6750 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6751 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6752 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6753 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6754 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6755 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6756 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6757 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6758 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6759 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6760 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6761 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6762 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6763 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6764 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6765 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6766 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6767 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6768 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6769 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6770 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6771 	/* all other program types don't have "named" context structs */
6772 };
6773 
6774 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6775  * for below __builtin_types_compatible_p() checks;
6776  * with this approach we don't need any extra arch-specific #ifdef guards
6777  */
6778 struct pt_regs;
6779 struct user_pt_regs;
6780 struct user_regs_struct;
6781 
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)6782 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6783 				     const char *subprog_name, int arg_idx,
6784 				     int arg_type_id, const char *ctx_name)
6785 {
6786 	const struct btf_type *t;
6787 	const char *tname;
6788 
6789 	/* check if existing parameter already matches verifier expectations */
6790 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6791 	if (!btf_is_ptr(t))
6792 		goto out_warn;
6793 
6794 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6795 	 * and perf_event programs, so check this case early on and forget
6796 	 * about it for subsequent checks
6797 	 */
6798 	while (btf_is_mod(t))
6799 		t = btf__type_by_id(btf, t->type);
6800 	if (btf_is_typedef(t) &&
6801 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6802 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6803 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6804 			return false; /* canonical type for kprobe/perf_event */
6805 	}
6806 
6807 	/* now we can ignore typedefs moving forward */
6808 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6809 
6810 	/* if it's `void *`, definitely fix up BTF info */
6811 	if (btf_is_void(t))
6812 		return true;
6813 
6814 	/* if it's already proper canonical type, no need to fix up */
6815 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6816 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6817 		return false;
6818 
6819 	/* special cases */
6820 	switch (prog->type) {
6821 	case BPF_PROG_TYPE_KPROBE:
6822 		/* `struct pt_regs *` is expected, but we need to fix up */
6823 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6824 			return true;
6825 		break;
6826 	case BPF_PROG_TYPE_PERF_EVENT:
6827 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6828 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6829 			return true;
6830 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6831 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6832 			return true;
6833 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6834 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6835 			return true;
6836 		break;
6837 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6838 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6839 		/* allow u64* as ctx */
6840 		if (btf_is_int(t) && t->size == 8)
6841 			return true;
6842 		break;
6843 	default:
6844 		break;
6845 	}
6846 
6847 out_warn:
6848 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6849 		prog->name, subprog_name, arg_idx, ctx_name);
6850 	return false;
6851 }
6852 
clone_func_btf_info(struct btf * btf,int orig_fn_id,struct bpf_program * prog)6853 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6854 {
6855 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6856 	int i, err, arg_cnt, fn_name_off, linkage;
6857 	struct btf_type *fn_t, *fn_proto_t, *t;
6858 	struct btf_param *p;
6859 
6860 	/* caller already validated FUNC -> FUNC_PROTO validity */
6861 	fn_t = btf_type_by_id(btf, orig_fn_id);
6862 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6863 
6864 	/* Note that each btf__add_xxx() operation invalidates
6865 	 * all btf_type and string pointers, so we need to be
6866 	 * very careful when cloning BTF types. BTF type
6867 	 * pointers have to be always refetched. And to avoid
6868 	 * problems with invalidated string pointers, we
6869 	 * add empty strings initially, then just fix up
6870 	 * name_off offsets in place. Offsets are stable for
6871 	 * existing strings, so that works out.
6872 	 */
6873 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6874 	linkage = btf_func_linkage(fn_t);
6875 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6876 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6877 	arg_cnt = btf_vlen(fn_proto_t);
6878 
6879 	/* clone FUNC_PROTO and its params */
6880 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6881 	if (fn_proto_id < 0)
6882 		return -EINVAL;
6883 
6884 	for (i = 0; i < arg_cnt; i++) {
6885 		int name_off;
6886 
6887 		/* copy original parameter data */
6888 		t = btf_type_by_id(btf, orig_proto_id);
6889 		p = &btf_params(t)[i];
6890 		name_off = p->name_off;
6891 
6892 		err = btf__add_func_param(btf, "", p->type);
6893 		if (err)
6894 			return err;
6895 
6896 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6897 		p = &btf_params(fn_proto_t)[i];
6898 		p->name_off = name_off; /* use remembered str offset */
6899 	}
6900 
6901 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6902 	 * entry program's name as a placeholder, which we replace immediately
6903 	 * with original name_off
6904 	 */
6905 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6906 	if (fn_id < 0)
6907 		return -EINVAL;
6908 
6909 	fn_t = btf_type_by_id(btf, fn_id);
6910 	fn_t->name_off = fn_name_off; /* reuse original string */
6911 
6912 	return fn_id;
6913 }
6914 
6915 /* Check if main program or global subprog's function prototype has `arg:ctx`
6916  * argument tags, and, if necessary, substitute correct type to match what BPF
6917  * verifier would expect, taking into account specific program type. This
6918  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6919  * have a native support for it in the verifier, making user's life much
6920  * easier.
6921  */
bpf_program_fixup_func_info(struct bpf_object * obj,struct bpf_program * prog)6922 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6923 {
6924 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6925 	struct bpf_func_info_min *func_rec;
6926 	struct btf_type *fn_t, *fn_proto_t;
6927 	struct btf *btf = obj->btf;
6928 	const struct btf_type *t;
6929 	struct btf_param *p;
6930 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6931 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6932 	int *orig_ids;
6933 
6934 	/* no .BTF.ext, no problem */
6935 	if (!obj->btf_ext || !prog->func_info)
6936 		return 0;
6937 
6938 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6939 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6940 		return 0;
6941 
6942 	/* some BPF program types just don't have named context structs, so
6943 	 * this fallback mechanism doesn't work for them
6944 	 */
6945 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6946 		if (global_ctx_map[i].prog_type != prog->type)
6947 			continue;
6948 		ctx_name = global_ctx_map[i].ctx_name;
6949 		break;
6950 	}
6951 	if (!ctx_name)
6952 		return 0;
6953 
6954 	/* remember original func BTF IDs to detect if we already cloned them */
6955 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6956 	if (!orig_ids)
6957 		return -ENOMEM;
6958 	for (i = 0; i < prog->func_info_cnt; i++) {
6959 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6960 		orig_ids[i] = func_rec->type_id;
6961 	}
6962 
6963 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6964 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6965 	 * clone and adjust FUNC -> FUNC_PROTO combo
6966 	 */
6967 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6968 		/* only DECL_TAG with "arg:ctx" value are interesting */
6969 		t = btf__type_by_id(btf, i);
6970 		if (!btf_is_decl_tag(t))
6971 			continue;
6972 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6973 			continue;
6974 
6975 		/* only global funcs need adjustment, if at all */
6976 		orig_fn_id = t->type;
6977 		fn_t = btf_type_by_id(btf, orig_fn_id);
6978 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6979 			continue;
6980 
6981 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6982 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6983 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6984 			continue;
6985 
6986 		/* find corresponding func_info record */
6987 		func_rec = NULL;
6988 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6989 			if (orig_ids[rec_idx] == t->type) {
6990 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6991 				break;
6992 			}
6993 		}
6994 		/* current main program doesn't call into this subprog */
6995 		if (!func_rec)
6996 			continue;
6997 
6998 		/* some more sanity checking of DECL_TAG */
6999 		arg_cnt = btf_vlen(fn_proto_t);
7000 		arg_idx = btf_decl_tag(t)->component_idx;
7001 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7002 			continue;
7003 
7004 		/* check if we should fix up argument type */
7005 		p = &btf_params(fn_proto_t)[arg_idx];
7006 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7007 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7008 			continue;
7009 
7010 		/* clone fn/fn_proto, unless we already did it for another arg */
7011 		if (func_rec->type_id == orig_fn_id) {
7012 			int fn_id;
7013 
7014 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7015 			if (fn_id < 0) {
7016 				err = fn_id;
7017 				goto err_out;
7018 			}
7019 
7020 			/* point func_info record to a cloned FUNC type */
7021 			func_rec->type_id = fn_id;
7022 		}
7023 
7024 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7025 		 * we do it just once per main BPF program, as all global
7026 		 * funcs share the same program type, so need only PTR ->
7027 		 * STRUCT type chain
7028 		 */
7029 		if (ptr_id == 0) {
7030 			struct_id = btf__add_struct(btf, ctx_name, 0);
7031 			ptr_id = btf__add_ptr(btf, struct_id);
7032 			if (ptr_id < 0 || struct_id < 0) {
7033 				err = -EINVAL;
7034 				goto err_out;
7035 			}
7036 		}
7037 
7038 		/* for completeness, clone DECL_TAG and point it to cloned param */
7039 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7040 		if (tag_id < 0) {
7041 			err = -EINVAL;
7042 			goto err_out;
7043 		}
7044 
7045 		/* all the BTF manipulations invalidated pointers, refetch them */
7046 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7047 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7048 
7049 		/* fix up type ID pointed to by param */
7050 		p = &btf_params(fn_proto_t)[arg_idx];
7051 		p->type = ptr_id;
7052 	}
7053 
7054 	free(orig_ids);
7055 	return 0;
7056 err_out:
7057 	free(orig_ids);
7058 	return err;
7059 }
7060 
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)7061 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7062 {
7063 	struct bpf_program *prog;
7064 	size_t i, j;
7065 	int err;
7066 
7067 	if (obj->btf_ext) {
7068 		err = bpf_object__relocate_core(obj, targ_btf_path);
7069 		if (err) {
7070 			pr_warn("failed to perform CO-RE relocations: %s\n",
7071 				errstr(err));
7072 			return err;
7073 		}
7074 		bpf_object__sort_relos(obj);
7075 	}
7076 
7077 	/* Before relocating calls pre-process relocations and mark
7078 	 * few ld_imm64 instructions that points to subprogs.
7079 	 * Otherwise bpf_object__reloc_code() later would have to consider
7080 	 * all ld_imm64 insns as relocation candidates. That would
7081 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7082 	 * would increase and most of them will fail to find a relo.
7083 	 */
7084 	for (i = 0; i < obj->nr_programs; i++) {
7085 		prog = &obj->programs[i];
7086 		for (j = 0; j < prog->nr_reloc; j++) {
7087 			struct reloc_desc *relo = &prog->reloc_desc[j];
7088 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7089 
7090 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7091 			if (relo->type == RELO_SUBPROG_ADDR)
7092 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7093 		}
7094 	}
7095 
7096 	/* relocate subprogram calls and append used subprograms to main
7097 	 * programs; each copy of subprogram code needs to be relocated
7098 	 * differently for each main program, because its code location might
7099 	 * have changed.
7100 	 * Append subprog relos to main programs to allow data relos to be
7101 	 * processed after text is completely relocated.
7102 	 */
7103 	for (i = 0; i < obj->nr_programs; i++) {
7104 		prog = &obj->programs[i];
7105 		/* sub-program's sub-calls are relocated within the context of
7106 		 * its main program only
7107 		 */
7108 		if (prog_is_subprog(obj, prog))
7109 			continue;
7110 		if (!prog->autoload)
7111 			continue;
7112 
7113 		err = bpf_object__relocate_calls(obj, prog);
7114 		if (err) {
7115 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7116 				prog->name, errstr(err));
7117 			return err;
7118 		}
7119 
7120 		err = bpf_prog_assign_exc_cb(obj, prog);
7121 		if (err)
7122 			return err;
7123 		/* Now, also append exception callback if it has not been done already. */
7124 		if (prog->exception_cb_idx >= 0) {
7125 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7126 
7127 			/* Calling exception callback directly is disallowed, which the
7128 			 * verifier will reject later. In case it was processed already,
7129 			 * we can skip this step, otherwise for all other valid cases we
7130 			 * have to append exception callback now.
7131 			 */
7132 			if (subprog->sub_insn_off == 0) {
7133 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7134 				if (err)
7135 					return err;
7136 				err = bpf_object__reloc_code(obj, prog, subprog);
7137 				if (err)
7138 					return err;
7139 			}
7140 		}
7141 	}
7142 	for (i = 0; i < obj->nr_programs; i++) {
7143 		prog = &obj->programs[i];
7144 		if (prog_is_subprog(obj, prog))
7145 			continue;
7146 		if (!prog->autoload)
7147 			continue;
7148 
7149 		/* Process data relos for main programs */
7150 		err = bpf_object__relocate_data(obj, prog);
7151 		if (err) {
7152 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7153 				prog->name, errstr(err));
7154 			return err;
7155 		}
7156 
7157 		/* Fix up .BTF.ext information, if necessary */
7158 		err = bpf_program_fixup_func_info(obj, prog);
7159 		if (err) {
7160 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7161 				prog->name, errstr(err));
7162 			return err;
7163 		}
7164 	}
7165 
7166 	return 0;
7167 }
7168 
7169 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7170 					    Elf64_Shdr *shdr, Elf_Data *data);
7171 
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)7172 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7173 					 Elf64_Shdr *shdr, Elf_Data *data)
7174 {
7175 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7176 	int i, j, nrels, new_sz;
7177 	const struct btf_var_secinfo *vi = NULL;
7178 	const struct btf_type *sec, *var, *def;
7179 	struct bpf_map *map = NULL, *targ_map = NULL;
7180 	struct bpf_program *targ_prog = NULL;
7181 	bool is_prog_array, is_map_in_map;
7182 	const struct btf_member *member;
7183 	const char *name, *mname, *type;
7184 	unsigned int moff;
7185 	Elf64_Sym *sym;
7186 	Elf64_Rel *rel;
7187 	void *tmp;
7188 
7189 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7190 		return -EINVAL;
7191 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7192 	if (!sec)
7193 		return -EINVAL;
7194 
7195 	nrels = shdr->sh_size / shdr->sh_entsize;
7196 	for (i = 0; i < nrels; i++) {
7197 		rel = elf_rel_by_idx(data, i);
7198 		if (!rel) {
7199 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7200 			return -LIBBPF_ERRNO__FORMAT;
7201 		}
7202 
7203 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7204 		if (!sym) {
7205 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7206 				i, (size_t)ELF64_R_SYM(rel->r_info));
7207 			return -LIBBPF_ERRNO__FORMAT;
7208 		}
7209 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7210 
7211 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7212 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7213 			 (size_t)rel->r_offset, sym->st_name, name);
7214 
7215 		for (j = 0; j < obj->nr_maps; j++) {
7216 			map = &obj->maps[j];
7217 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7218 				continue;
7219 
7220 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7221 			if (vi->offset <= rel->r_offset &&
7222 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7223 				break;
7224 		}
7225 		if (j == obj->nr_maps) {
7226 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7227 				i, name, (size_t)rel->r_offset);
7228 			return -EINVAL;
7229 		}
7230 
7231 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7232 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7233 		type = is_map_in_map ? "map" : "prog";
7234 		if (is_map_in_map) {
7235 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7236 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7237 					i, name);
7238 				return -LIBBPF_ERRNO__RELOC;
7239 			}
7240 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7241 			    map->def.key_size != sizeof(int)) {
7242 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7243 					i, map->name, sizeof(int));
7244 				return -EINVAL;
7245 			}
7246 			targ_map = bpf_object__find_map_by_name(obj, name);
7247 			if (!targ_map) {
7248 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7249 					i, name);
7250 				return -ESRCH;
7251 			}
7252 		} else if (is_prog_array) {
7253 			targ_prog = bpf_object__find_program_by_name(obj, name);
7254 			if (!targ_prog) {
7255 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7256 					i, name);
7257 				return -ESRCH;
7258 			}
7259 			if (targ_prog->sec_idx != sym->st_shndx ||
7260 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7261 			    prog_is_subprog(obj, targ_prog)) {
7262 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7263 					i, name);
7264 				return -LIBBPF_ERRNO__RELOC;
7265 			}
7266 		} else {
7267 			return -EINVAL;
7268 		}
7269 
7270 		var = btf__type_by_id(obj->btf, vi->type);
7271 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7272 		if (btf_vlen(def) == 0)
7273 			return -EINVAL;
7274 		member = btf_members(def) + btf_vlen(def) - 1;
7275 		mname = btf__name_by_offset(obj->btf, member->name_off);
7276 		if (strcmp(mname, "values"))
7277 			return -EINVAL;
7278 
7279 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7280 		if (rel->r_offset - vi->offset < moff)
7281 			return -EINVAL;
7282 
7283 		moff = rel->r_offset - vi->offset - moff;
7284 		/* here we use BPF pointer size, which is always 64 bit, as we
7285 		 * are parsing ELF that was built for BPF target
7286 		 */
7287 		if (moff % bpf_ptr_sz)
7288 			return -EINVAL;
7289 		moff /= bpf_ptr_sz;
7290 		if (moff >= map->init_slots_sz) {
7291 			new_sz = moff + 1;
7292 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7293 			if (!tmp)
7294 				return -ENOMEM;
7295 			map->init_slots = tmp;
7296 			memset(map->init_slots + map->init_slots_sz, 0,
7297 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7298 			map->init_slots_sz = new_sz;
7299 		}
7300 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7301 
7302 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7303 			 i, map->name, moff, type, name);
7304 	}
7305 
7306 	return 0;
7307 }
7308 
bpf_object__collect_relos(struct bpf_object * obj)7309 static int bpf_object__collect_relos(struct bpf_object *obj)
7310 {
7311 	int i, err;
7312 
7313 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7314 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7315 		Elf64_Shdr *shdr;
7316 		Elf_Data *data;
7317 		int idx;
7318 
7319 		if (sec_desc->sec_type != SEC_RELO)
7320 			continue;
7321 
7322 		shdr = sec_desc->shdr;
7323 		data = sec_desc->data;
7324 		idx = shdr->sh_info;
7325 
7326 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7327 			pr_warn("internal error at %d\n", __LINE__);
7328 			return -LIBBPF_ERRNO__INTERNAL;
7329 		}
7330 
7331 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7332 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7333 		else if (idx == obj->efile.btf_maps_shndx)
7334 			err = bpf_object__collect_map_relos(obj, shdr, data);
7335 		else
7336 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7337 		if (err)
7338 			return err;
7339 	}
7340 
7341 	bpf_object__sort_relos(obj);
7342 	return 0;
7343 }
7344 
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)7345 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7346 {
7347 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7348 	    BPF_OP(insn->code) == BPF_CALL &&
7349 	    BPF_SRC(insn->code) == BPF_K &&
7350 	    insn->src_reg == 0 &&
7351 	    insn->dst_reg == 0) {
7352 		    *func_id = insn->imm;
7353 		    return true;
7354 	}
7355 	return false;
7356 }
7357 
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)7358 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7359 {
7360 	struct bpf_insn *insn = prog->insns;
7361 	enum bpf_func_id func_id;
7362 	int i;
7363 
7364 	if (obj->gen_loader)
7365 		return 0;
7366 
7367 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7368 		if (!insn_is_helper_call(insn, &func_id))
7369 			continue;
7370 
7371 		/* on kernels that don't yet support
7372 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7373 		 * to bpf_probe_read() which works well for old kernels
7374 		 */
7375 		switch (func_id) {
7376 		case BPF_FUNC_probe_read_kernel:
7377 		case BPF_FUNC_probe_read_user:
7378 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7379 				insn->imm = BPF_FUNC_probe_read;
7380 			break;
7381 		case BPF_FUNC_probe_read_kernel_str:
7382 		case BPF_FUNC_probe_read_user_str:
7383 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7384 				insn->imm = BPF_FUNC_probe_read_str;
7385 			break;
7386 		default:
7387 			break;
7388 		}
7389 	}
7390 	return 0;
7391 }
7392 
7393 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7394 				     int *btf_obj_fd, int *btf_type_id);
7395 
7396 /* 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)7397 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7398 				    struct bpf_prog_load_opts *opts, long cookie)
7399 {
7400 	enum sec_def_flags def = cookie;
7401 
7402 	/* old kernels might not support specifying expected_attach_type */
7403 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7404 		opts->expected_attach_type = 0;
7405 
7406 	if (def & SEC_SLEEPABLE)
7407 		opts->prog_flags |= BPF_F_SLEEPABLE;
7408 
7409 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7410 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7411 
7412 	/* special check for usdt to use uprobe_multi link */
7413 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7414 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7415 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7416 		 * update both.
7417 		 */
7418 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7419 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7420 	}
7421 
7422 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7423 		int btf_obj_fd = 0, btf_type_id = 0, err;
7424 		const char *attach_name;
7425 
7426 		attach_name = strchr(prog->sec_name, '/');
7427 		if (!attach_name) {
7428 			/* if BPF program is annotated with just SEC("fentry")
7429 			 * (or similar) without declaratively specifying
7430 			 * target, then it is expected that target will be
7431 			 * specified with bpf_program__set_attach_target() at
7432 			 * runtime before BPF object load step. If not, then
7433 			 * there is nothing to load into the kernel as BPF
7434 			 * verifier won't be able to validate BPF program
7435 			 * correctness anyways.
7436 			 */
7437 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7438 				prog->name);
7439 			return -EINVAL;
7440 		}
7441 		attach_name++; /* skip over / */
7442 
7443 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7444 		if (err)
7445 			return err;
7446 
7447 		/* cache resolved BTF FD and BTF type ID in the prog */
7448 		prog->attach_btf_obj_fd = btf_obj_fd;
7449 		prog->attach_btf_id = btf_type_id;
7450 
7451 		/* but by now libbpf common logic is not utilizing
7452 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7453 		 * this callback is called after opts were populated by
7454 		 * libbpf, so this callback has to update opts explicitly here
7455 		 */
7456 		opts->attach_btf_obj_fd = btf_obj_fd;
7457 		opts->attach_btf_id = btf_type_id;
7458 	}
7459 	return 0;
7460 }
7461 
7462 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7463 
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)7464 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7465 				struct bpf_insn *insns, int insns_cnt,
7466 				const char *license, __u32 kern_version, int *prog_fd)
7467 {
7468 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7469 	const char *prog_name = NULL;
7470 	size_t log_buf_size = 0;
7471 	char *log_buf = NULL, *tmp;
7472 	bool own_log_buf = true;
7473 	__u32 log_level = prog->log_level;
7474 	int ret, err;
7475 
7476 	/* Be more helpful by rejecting programs that can't be validated early
7477 	 * with more meaningful and actionable error message.
7478 	 */
7479 	switch (prog->type) {
7480 	case BPF_PROG_TYPE_UNSPEC:
7481 		/*
7482 		 * The program type must be set.  Most likely we couldn't find a proper
7483 		 * section definition at load time, and thus we didn't infer the type.
7484 		 */
7485 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7486 			prog->name, prog->sec_name);
7487 		return -EINVAL;
7488 	case BPF_PROG_TYPE_STRUCT_OPS:
7489 		if (prog->attach_btf_id == 0) {
7490 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7491 				prog->name);
7492 			return -EINVAL;
7493 		}
7494 		break;
7495 	default:
7496 		break;
7497 	}
7498 
7499 	if (!insns || !insns_cnt)
7500 		return -EINVAL;
7501 
7502 	if (kernel_supports(obj, FEAT_PROG_NAME))
7503 		prog_name = prog->name;
7504 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7505 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7506 	load_attr.attach_btf_id = prog->attach_btf_id;
7507 	load_attr.kern_version = kern_version;
7508 	load_attr.prog_ifindex = prog->prog_ifindex;
7509 	load_attr.expected_attach_type = prog->expected_attach_type;
7510 
7511 	/* specify func_info/line_info only if kernel supports them */
7512 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7513 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7514 		load_attr.func_info = prog->func_info;
7515 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7516 		load_attr.func_info_cnt = prog->func_info_cnt;
7517 		load_attr.line_info = prog->line_info;
7518 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7519 		load_attr.line_info_cnt = prog->line_info_cnt;
7520 	}
7521 	load_attr.log_level = log_level;
7522 	load_attr.prog_flags = prog->prog_flags;
7523 	load_attr.fd_array = obj->fd_array;
7524 
7525 	load_attr.token_fd = obj->token_fd;
7526 	if (obj->token_fd)
7527 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7528 
7529 	/* adjust load_attr if sec_def provides custom preload callback */
7530 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7531 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7532 		if (err < 0) {
7533 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7534 				prog->name, errstr(err));
7535 			return err;
7536 		}
7537 		insns = prog->insns;
7538 		insns_cnt = prog->insns_cnt;
7539 	}
7540 
7541 	if (obj->gen_loader) {
7542 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7543 				   license, insns, insns_cnt, &load_attr,
7544 				   prog - obj->programs);
7545 		*prog_fd = -1;
7546 		return 0;
7547 	}
7548 
7549 retry_load:
7550 	/* if log_level is zero, we don't request logs initially even if
7551 	 * custom log_buf is specified; if the program load fails, then we'll
7552 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7553 	 * our own and retry the load to get details on what failed
7554 	 */
7555 	if (log_level) {
7556 		if (prog->log_buf) {
7557 			log_buf = prog->log_buf;
7558 			log_buf_size = prog->log_size;
7559 			own_log_buf = false;
7560 		} else if (obj->log_buf) {
7561 			log_buf = obj->log_buf;
7562 			log_buf_size = obj->log_size;
7563 			own_log_buf = false;
7564 		} else {
7565 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7566 			tmp = realloc(log_buf, log_buf_size);
7567 			if (!tmp) {
7568 				ret = -ENOMEM;
7569 				goto out;
7570 			}
7571 			log_buf = tmp;
7572 			log_buf[0] = '\0';
7573 			own_log_buf = true;
7574 		}
7575 	}
7576 
7577 	load_attr.log_buf = log_buf;
7578 	load_attr.log_size = log_buf_size;
7579 	load_attr.log_level = log_level;
7580 
7581 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7582 	if (ret >= 0) {
7583 		if (log_level && own_log_buf) {
7584 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7585 				 prog->name, log_buf);
7586 		}
7587 
7588 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7589 			struct bpf_map *map;
7590 			int i;
7591 
7592 			for (i = 0; i < obj->nr_maps; i++) {
7593 				map = &prog->obj->maps[i];
7594 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7595 					continue;
7596 
7597 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7598 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7599 						prog->name, map->real_name, errstr(errno));
7600 					/* Don't fail hard if can't bind rodata. */
7601 				}
7602 			}
7603 		}
7604 
7605 		*prog_fd = ret;
7606 		ret = 0;
7607 		goto out;
7608 	}
7609 
7610 	if (log_level == 0) {
7611 		log_level = 1;
7612 		goto retry_load;
7613 	}
7614 	/* On ENOSPC, increase log buffer size and retry, unless custom
7615 	 * log_buf is specified.
7616 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7617 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7618 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7619 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7620 	 */
7621 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7622 		goto retry_load;
7623 
7624 	ret = -errno;
7625 
7626 	/* post-process verifier log to improve error descriptions */
7627 	fixup_verifier_log(prog, log_buf, log_buf_size);
7628 
7629 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7630 	pr_perm_msg(ret);
7631 
7632 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7633 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7634 			prog->name, log_buf);
7635 	}
7636 
7637 out:
7638 	if (own_log_buf)
7639 		free(log_buf);
7640 	return ret;
7641 }
7642 
find_prev_line(char * buf,char * cur)7643 static char *find_prev_line(char *buf, char *cur)
7644 {
7645 	char *p;
7646 
7647 	if (cur == buf) /* end of a log buf */
7648 		return NULL;
7649 
7650 	p = cur - 1;
7651 	while (p - 1 >= buf && *(p - 1) != '\n')
7652 		p--;
7653 
7654 	return p;
7655 }
7656 
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)7657 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7658 		      char *orig, size_t orig_sz, const char *patch)
7659 {
7660 	/* size of the remaining log content to the right from the to-be-replaced part */
7661 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7662 	size_t patch_sz = strlen(patch);
7663 
7664 	if (patch_sz != orig_sz) {
7665 		/* If patch line(s) are longer than original piece of verifier log,
7666 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7667 		 * starting from after to-be-replaced part of the log.
7668 		 *
7669 		 * If patch line(s) are shorter than original piece of verifier log,
7670 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7671 		 * starting from after to-be-replaced part of the log
7672 		 *
7673 		 * We need to be careful about not overflowing available
7674 		 * buf_sz capacity. If that's the case, we'll truncate the end
7675 		 * of the original log, as necessary.
7676 		 */
7677 		if (patch_sz > orig_sz) {
7678 			if (orig + patch_sz >= buf + buf_sz) {
7679 				/* patch is big enough to cover remaining space completely */
7680 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7681 				rem_sz = 0;
7682 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7683 				/* patch causes part of remaining log to be truncated */
7684 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7685 			}
7686 		}
7687 		/* shift remaining log to the right by calculated amount */
7688 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7689 	}
7690 
7691 	memcpy(orig, patch, patch_sz);
7692 }
7693 
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)7694 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7695 				       char *buf, size_t buf_sz, size_t log_sz,
7696 				       char *line1, char *line2, char *line3)
7697 {
7698 	/* Expected log for failed and not properly guarded CO-RE relocation:
7699 	 * line1 -> 123: (85) call unknown#195896080
7700 	 * line2 -> invalid func unknown#195896080
7701 	 * line3 -> <anything else or end of buffer>
7702 	 *
7703 	 * "123" is the index of the instruction that was poisoned. We extract
7704 	 * instruction index to find corresponding CO-RE relocation and
7705 	 * replace this part of the log with more relevant information about
7706 	 * failed CO-RE relocation.
7707 	 */
7708 	const struct bpf_core_relo *relo;
7709 	struct bpf_core_spec spec;
7710 	char patch[512], spec_buf[256];
7711 	int insn_idx, err, spec_len;
7712 
7713 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7714 		return;
7715 
7716 	relo = find_relo_core(prog, insn_idx);
7717 	if (!relo)
7718 		return;
7719 
7720 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7721 	if (err)
7722 		return;
7723 
7724 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7725 	snprintf(patch, sizeof(patch),
7726 		 "%d: <invalid CO-RE relocation>\n"
7727 		 "failed to resolve CO-RE relocation %s%s\n",
7728 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7729 
7730 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7731 }
7732 
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)7733 static void fixup_log_missing_map_load(struct bpf_program *prog,
7734 				       char *buf, size_t buf_sz, size_t log_sz,
7735 				       char *line1, char *line2, char *line3)
7736 {
7737 	/* Expected log for failed and not properly guarded map reference:
7738 	 * line1 -> 123: (85) call unknown#2001000345
7739 	 * line2 -> invalid func unknown#2001000345
7740 	 * line3 -> <anything else or end of buffer>
7741 	 *
7742 	 * "123" is the index of the instruction that was poisoned.
7743 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7744 	 */
7745 	struct bpf_object *obj = prog->obj;
7746 	const struct bpf_map *map;
7747 	int insn_idx, map_idx;
7748 	char patch[128];
7749 
7750 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7751 		return;
7752 
7753 	map_idx -= POISON_LDIMM64_MAP_BASE;
7754 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7755 		return;
7756 	map = &obj->maps[map_idx];
7757 
7758 	snprintf(patch, sizeof(patch),
7759 		 "%d: <invalid BPF map reference>\n"
7760 		 "BPF map '%s' is referenced but wasn't created\n",
7761 		 insn_idx, map->name);
7762 
7763 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7764 }
7765 
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)7766 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7767 					 char *buf, size_t buf_sz, size_t log_sz,
7768 					 char *line1, char *line2, char *line3)
7769 {
7770 	/* Expected log for failed and not properly guarded kfunc call:
7771 	 * line1 -> 123: (85) call unknown#2002000345
7772 	 * line2 -> invalid func unknown#2002000345
7773 	 * line3 -> <anything else or end of buffer>
7774 	 *
7775 	 * "123" is the index of the instruction that was poisoned.
7776 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7777 	 */
7778 	struct bpf_object *obj = prog->obj;
7779 	const struct extern_desc *ext;
7780 	int insn_idx, ext_idx;
7781 	char patch[128];
7782 
7783 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7784 		return;
7785 
7786 	ext_idx -= POISON_CALL_KFUNC_BASE;
7787 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7788 		return;
7789 	ext = &obj->externs[ext_idx];
7790 
7791 	snprintf(patch, sizeof(patch),
7792 		 "%d: <invalid kfunc call>\n"
7793 		 "kfunc '%s' is referenced but wasn't resolved\n",
7794 		 insn_idx, ext->name);
7795 
7796 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7797 }
7798 
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7799 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7800 {
7801 	/* look for familiar error patterns in last N lines of the log */
7802 	const size_t max_last_line_cnt = 10;
7803 	char *prev_line, *cur_line, *next_line;
7804 	size_t log_sz;
7805 	int i;
7806 
7807 	if (!buf)
7808 		return;
7809 
7810 	log_sz = strlen(buf) + 1;
7811 	next_line = buf + log_sz - 1;
7812 
7813 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7814 		cur_line = find_prev_line(buf, next_line);
7815 		if (!cur_line)
7816 			return;
7817 
7818 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7819 			prev_line = find_prev_line(buf, cur_line);
7820 			if (!prev_line)
7821 				continue;
7822 
7823 			/* failed CO-RE relocation case */
7824 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7825 						   prev_line, cur_line, next_line);
7826 			return;
7827 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7828 			prev_line = find_prev_line(buf, cur_line);
7829 			if (!prev_line)
7830 				continue;
7831 
7832 			/* reference to uncreated BPF map */
7833 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7834 						   prev_line, cur_line, next_line);
7835 			return;
7836 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7837 			prev_line = find_prev_line(buf, cur_line);
7838 			if (!prev_line)
7839 				continue;
7840 
7841 			/* reference to unresolved kfunc */
7842 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7843 						     prev_line, cur_line, next_line);
7844 			return;
7845 		}
7846 	}
7847 }
7848 
bpf_program_record_relos(struct bpf_program * prog)7849 static int bpf_program_record_relos(struct bpf_program *prog)
7850 {
7851 	struct bpf_object *obj = prog->obj;
7852 	int i;
7853 
7854 	for (i = 0; i < prog->nr_reloc; i++) {
7855 		struct reloc_desc *relo = &prog->reloc_desc[i];
7856 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7857 		int kind;
7858 
7859 		switch (relo->type) {
7860 		case RELO_EXTERN_LD64:
7861 			if (ext->type != EXT_KSYM)
7862 				continue;
7863 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7864 				BTF_KIND_VAR : BTF_KIND_FUNC;
7865 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7866 					       ext->is_weak, !ext->ksym.type_id,
7867 					       true, kind, relo->insn_idx);
7868 			break;
7869 		case RELO_EXTERN_CALL:
7870 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7871 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7872 					       relo->insn_idx);
7873 			break;
7874 		case RELO_CORE: {
7875 			struct bpf_core_relo cr = {
7876 				.insn_off = relo->insn_idx * 8,
7877 				.type_id = relo->core_relo->type_id,
7878 				.access_str_off = relo->core_relo->access_str_off,
7879 				.kind = relo->core_relo->kind,
7880 			};
7881 
7882 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7883 			break;
7884 		}
7885 		default:
7886 			continue;
7887 		}
7888 	}
7889 	return 0;
7890 }
7891 
7892 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7893 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7894 {
7895 	struct bpf_program *prog;
7896 	size_t i;
7897 	int err;
7898 
7899 	for (i = 0; i < obj->nr_programs; i++) {
7900 		prog = &obj->programs[i];
7901 		if (prog_is_subprog(obj, prog))
7902 			continue;
7903 		if (!prog->autoload) {
7904 			pr_debug("prog '%s': skipped loading\n", prog->name);
7905 			continue;
7906 		}
7907 		prog->log_level |= log_level;
7908 
7909 		if (obj->gen_loader)
7910 			bpf_program_record_relos(prog);
7911 
7912 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7913 					   obj->license, obj->kern_version, &prog->fd);
7914 		if (err) {
7915 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7916 			return err;
7917 		}
7918 	}
7919 
7920 	bpf_object__free_relocs(obj);
7921 	return 0;
7922 }
7923 
bpf_object_prepare_progs(struct bpf_object * obj)7924 static int bpf_object_prepare_progs(struct bpf_object *obj)
7925 {
7926 	struct bpf_program *prog;
7927 	size_t i;
7928 	int err;
7929 
7930 	for (i = 0; i < obj->nr_programs; i++) {
7931 		prog = &obj->programs[i];
7932 		err = bpf_object__sanitize_prog(obj, prog);
7933 		if (err)
7934 			return err;
7935 	}
7936 	return 0;
7937 }
7938 
7939 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7940 
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7941 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7942 {
7943 	struct bpf_program *prog;
7944 	int err;
7945 
7946 	bpf_object__for_each_program(prog, obj) {
7947 		prog->sec_def = find_sec_def(prog->sec_name);
7948 		if (!prog->sec_def) {
7949 			/* couldn't guess, but user might manually specify */
7950 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7951 				prog->name, prog->sec_name);
7952 			continue;
7953 		}
7954 
7955 		prog->type = prog->sec_def->prog_type;
7956 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7957 
7958 		/* sec_def can have custom callback which should be called
7959 		 * after bpf_program is initialized to adjust its properties
7960 		 */
7961 		if (prog->sec_def->prog_setup_fn) {
7962 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7963 			if (err < 0) {
7964 				pr_warn("prog '%s': failed to initialize: %s\n",
7965 					prog->name, errstr(err));
7966 				return err;
7967 			}
7968 		}
7969 	}
7970 
7971 	return 0;
7972 }
7973 
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)7974 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7975 					  const char *obj_name,
7976 					  const struct bpf_object_open_opts *opts)
7977 {
7978 	const char *kconfig, *btf_tmp_path, *token_path;
7979 	struct bpf_object *obj;
7980 	int err;
7981 	char *log_buf;
7982 	size_t log_size;
7983 	__u32 log_level;
7984 
7985 	if (obj_buf && !obj_name)
7986 		return ERR_PTR(-EINVAL);
7987 
7988 	if (elf_version(EV_CURRENT) == EV_NONE) {
7989 		pr_warn("failed to init libelf for %s\n",
7990 			path ? : "(mem buf)");
7991 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7992 	}
7993 
7994 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7995 		return ERR_PTR(-EINVAL);
7996 
7997 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
7998 	if (obj_buf) {
7999 		path = obj_name;
8000 		pr_debug("loading object '%s' from buffer\n", obj_name);
8001 	} else {
8002 		pr_debug("loading object from %s\n", path);
8003 	}
8004 
8005 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8006 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8007 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8008 	if (log_size > UINT_MAX)
8009 		return ERR_PTR(-EINVAL);
8010 	if (log_size && !log_buf)
8011 		return ERR_PTR(-EINVAL);
8012 
8013 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8014 	/* if user didn't specify bpf_token_path explicitly, check if
8015 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8016 	 * option
8017 	 */
8018 	if (!token_path)
8019 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8020 	if (token_path && strlen(token_path) >= PATH_MAX)
8021 		return ERR_PTR(-ENAMETOOLONG);
8022 
8023 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8024 	if (IS_ERR(obj))
8025 		return obj;
8026 
8027 	obj->log_buf = log_buf;
8028 	obj->log_size = log_size;
8029 	obj->log_level = log_level;
8030 
8031 	if (token_path) {
8032 		obj->token_path = strdup(token_path);
8033 		if (!obj->token_path) {
8034 			err = -ENOMEM;
8035 			goto out;
8036 		}
8037 	}
8038 
8039 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8040 	if (btf_tmp_path) {
8041 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8042 			err = -ENAMETOOLONG;
8043 			goto out;
8044 		}
8045 		obj->btf_custom_path = strdup(btf_tmp_path);
8046 		if (!obj->btf_custom_path) {
8047 			err = -ENOMEM;
8048 			goto out;
8049 		}
8050 	}
8051 
8052 	kconfig = OPTS_GET(opts, kconfig, NULL);
8053 	if (kconfig) {
8054 		obj->kconfig = strdup(kconfig);
8055 		if (!obj->kconfig) {
8056 			err = -ENOMEM;
8057 			goto out;
8058 		}
8059 	}
8060 
8061 	err = bpf_object__elf_init(obj);
8062 	err = err ? : bpf_object__elf_collect(obj);
8063 	err = err ? : bpf_object__collect_externs(obj);
8064 	err = err ? : bpf_object_fixup_btf(obj);
8065 	err = err ? : bpf_object__init_maps(obj, opts);
8066 	err = err ? : bpf_object_init_progs(obj, opts);
8067 	err = err ? : bpf_object__collect_relos(obj);
8068 	if (err)
8069 		goto out;
8070 
8071 	bpf_object__elf_finish(obj);
8072 
8073 	return obj;
8074 out:
8075 	bpf_object__close(obj);
8076 	return ERR_PTR(err);
8077 }
8078 
8079 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)8080 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8081 {
8082 	if (!path)
8083 		return libbpf_err_ptr(-EINVAL);
8084 
8085 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8086 }
8087 
bpf_object__open(const char * path)8088 struct bpf_object *bpf_object__open(const char *path)
8089 {
8090 	return bpf_object__open_file(path, NULL);
8091 }
8092 
8093 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)8094 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8095 		     const struct bpf_object_open_opts *opts)
8096 {
8097 	char tmp_name[64];
8098 
8099 	if (!obj_buf || obj_buf_sz == 0)
8100 		return libbpf_err_ptr(-EINVAL);
8101 
8102 	/* create a (quite useless) default "name" for this memory buffer object */
8103 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8104 
8105 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8106 }
8107 
bpf_object_unload(struct bpf_object * obj)8108 static int bpf_object_unload(struct bpf_object *obj)
8109 {
8110 	size_t i;
8111 
8112 	if (!obj)
8113 		return libbpf_err(-EINVAL);
8114 
8115 	for (i = 0; i < obj->nr_maps; i++) {
8116 		zclose(obj->maps[i].fd);
8117 		if (obj->maps[i].st_ops)
8118 			zfree(&obj->maps[i].st_ops->kern_vdata);
8119 	}
8120 
8121 	for (i = 0; i < obj->nr_programs; i++)
8122 		bpf_program__unload(&obj->programs[i]);
8123 
8124 	return 0;
8125 }
8126 
bpf_object__sanitize_maps(struct bpf_object * obj)8127 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8128 {
8129 	struct bpf_map *m;
8130 
8131 	bpf_object__for_each_map(m, obj) {
8132 		if (!bpf_map__is_internal(m))
8133 			continue;
8134 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8135 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8136 	}
8137 
8138 	return 0;
8139 }
8140 
8141 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8142 			     const char *sym_name, void *ctx);
8143 
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)8144 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8145 {
8146 	char sym_type, sym_name[500];
8147 	unsigned long long sym_addr;
8148 	int ret, err = 0;
8149 	FILE *f;
8150 
8151 	f = fopen("/proc/kallsyms", "re");
8152 	if (!f) {
8153 		err = -errno;
8154 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8155 		return err;
8156 	}
8157 
8158 	while (true) {
8159 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8160 			     &sym_addr, &sym_type, sym_name);
8161 		if (ret == EOF && feof(f))
8162 			break;
8163 		if (ret != 3) {
8164 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8165 			err = -EINVAL;
8166 			break;
8167 		}
8168 
8169 		err = cb(sym_addr, sym_type, sym_name, ctx);
8170 		if (err)
8171 			break;
8172 	}
8173 
8174 	fclose(f);
8175 	return err;
8176 }
8177 
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)8178 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8179 		       const char *sym_name, void *ctx)
8180 {
8181 	struct bpf_object *obj = ctx;
8182 	const struct btf_type *t;
8183 	struct extern_desc *ext;
8184 	char *res;
8185 
8186 	res = strstr(sym_name, ".llvm.");
8187 	if (sym_type == 'd' && res)
8188 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8189 	else
8190 		ext = find_extern_by_name(obj, sym_name);
8191 	if (!ext || ext->type != EXT_KSYM)
8192 		return 0;
8193 
8194 	t = btf__type_by_id(obj->btf, ext->btf_id);
8195 	if (!btf_is_var(t))
8196 		return 0;
8197 
8198 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8199 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8200 			sym_name, ext->ksym.addr, sym_addr);
8201 		return -EINVAL;
8202 	}
8203 	if (!ext->is_set) {
8204 		ext->is_set = true;
8205 		ext->ksym.addr = sym_addr;
8206 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8207 	}
8208 	return 0;
8209 }
8210 
bpf_object__read_kallsyms_file(struct bpf_object * obj)8211 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8212 {
8213 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8214 }
8215 
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)8216 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8217 			    __u16 kind, struct btf **res_btf,
8218 			    struct module_btf **res_mod_btf)
8219 {
8220 	struct module_btf *mod_btf;
8221 	struct btf *btf;
8222 	int i, id, err;
8223 
8224 	btf = obj->btf_vmlinux;
8225 	mod_btf = NULL;
8226 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8227 
8228 	if (id == -ENOENT) {
8229 		err = load_module_btfs(obj);
8230 		if (err)
8231 			return err;
8232 
8233 		for (i = 0; i < obj->btf_module_cnt; i++) {
8234 			/* we assume module_btf's BTF FD is always >0 */
8235 			mod_btf = &obj->btf_modules[i];
8236 			btf = mod_btf->btf;
8237 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8238 			if (id != -ENOENT)
8239 				break;
8240 		}
8241 	}
8242 	if (id <= 0)
8243 		return -ESRCH;
8244 
8245 	*res_btf = btf;
8246 	*res_mod_btf = mod_btf;
8247 	return id;
8248 }
8249 
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)8250 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8251 					       struct extern_desc *ext)
8252 {
8253 	const struct btf_type *targ_var, *targ_type;
8254 	__u32 targ_type_id, local_type_id;
8255 	struct module_btf *mod_btf = NULL;
8256 	const char *targ_var_name;
8257 	struct btf *btf = NULL;
8258 	int id, err;
8259 
8260 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8261 	if (id < 0) {
8262 		if (id == -ESRCH && ext->is_weak)
8263 			return 0;
8264 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8265 			ext->name);
8266 		return id;
8267 	}
8268 
8269 	/* find local type_id */
8270 	local_type_id = ext->ksym.type_id;
8271 
8272 	/* find target type_id */
8273 	targ_var = btf__type_by_id(btf, id);
8274 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8275 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8276 
8277 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8278 					btf, targ_type_id);
8279 	if (err <= 0) {
8280 		const struct btf_type *local_type;
8281 		const char *targ_name, *local_name;
8282 
8283 		local_type = btf__type_by_id(obj->btf, local_type_id);
8284 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8285 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8286 
8287 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8288 			ext->name, local_type_id,
8289 			btf_kind_str(local_type), local_name, targ_type_id,
8290 			btf_kind_str(targ_type), targ_name);
8291 		return -EINVAL;
8292 	}
8293 
8294 	ext->is_set = true;
8295 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8296 	ext->ksym.kernel_btf_id = id;
8297 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8298 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8299 
8300 	return 0;
8301 }
8302 
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)8303 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8304 						struct extern_desc *ext)
8305 {
8306 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8307 	struct module_btf *mod_btf = NULL;
8308 	const struct btf_type *kern_func;
8309 	struct btf *kern_btf = NULL;
8310 	int ret;
8311 
8312 	local_func_proto_id = ext->ksym.type_id;
8313 
8314 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8315 				    &mod_btf);
8316 	if (kfunc_id < 0) {
8317 		if (kfunc_id == -ESRCH && ext->is_weak)
8318 			return 0;
8319 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8320 			ext->name);
8321 		return kfunc_id;
8322 	}
8323 
8324 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8325 	kfunc_proto_id = kern_func->type;
8326 
8327 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8328 					kern_btf, kfunc_proto_id);
8329 	if (ret <= 0) {
8330 		if (ext->is_weak)
8331 			return 0;
8332 
8333 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8334 			ext->name, local_func_proto_id,
8335 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8336 		return -EINVAL;
8337 	}
8338 
8339 	/* set index for module BTF fd in fd_array, if unset */
8340 	if (mod_btf && !mod_btf->fd_array_idx) {
8341 		/* insn->off is s16 */
8342 		if (obj->fd_array_cnt == INT16_MAX) {
8343 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8344 				ext->name, mod_btf->fd_array_idx);
8345 			return -E2BIG;
8346 		}
8347 		/* Cannot use index 0 for module BTF fd */
8348 		if (!obj->fd_array_cnt)
8349 			obj->fd_array_cnt = 1;
8350 
8351 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8352 					obj->fd_array_cnt + 1);
8353 		if (ret)
8354 			return ret;
8355 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8356 		/* we assume module BTF FD is always >0 */
8357 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8358 	}
8359 
8360 	ext->is_set = true;
8361 	ext->ksym.kernel_btf_id = kfunc_id;
8362 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8363 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8364 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8365 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8366 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8367 	 */
8368 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8369 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8370 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8371 
8372 	return 0;
8373 }
8374 
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)8375 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8376 {
8377 	const struct btf_type *t;
8378 	struct extern_desc *ext;
8379 	int i, err;
8380 
8381 	for (i = 0; i < obj->nr_extern; i++) {
8382 		ext = &obj->externs[i];
8383 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8384 			continue;
8385 
8386 		if (obj->gen_loader) {
8387 			ext->is_set = true;
8388 			ext->ksym.kernel_btf_obj_fd = 0;
8389 			ext->ksym.kernel_btf_id = 0;
8390 			continue;
8391 		}
8392 		t = btf__type_by_id(obj->btf, ext->btf_id);
8393 		if (btf_is_var(t))
8394 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8395 		else
8396 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8397 		if (err)
8398 			return err;
8399 	}
8400 	return 0;
8401 }
8402 
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)8403 static int bpf_object__resolve_externs(struct bpf_object *obj,
8404 				       const char *extra_kconfig)
8405 {
8406 	bool need_config = false, need_kallsyms = false;
8407 	bool need_vmlinux_btf = false;
8408 	struct extern_desc *ext;
8409 	void *kcfg_data = NULL;
8410 	int err, i;
8411 
8412 	if (obj->nr_extern == 0)
8413 		return 0;
8414 
8415 	if (obj->kconfig_map_idx >= 0)
8416 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8417 
8418 	for (i = 0; i < obj->nr_extern; i++) {
8419 		ext = &obj->externs[i];
8420 
8421 		if (ext->type == EXT_KSYM) {
8422 			if (ext->ksym.type_id)
8423 				need_vmlinux_btf = true;
8424 			else
8425 				need_kallsyms = true;
8426 			continue;
8427 		} else if (ext->type == EXT_KCFG) {
8428 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8429 			__u64 value = 0;
8430 
8431 			/* Kconfig externs need actual /proc/config.gz */
8432 			if (str_has_pfx(ext->name, "CONFIG_")) {
8433 				need_config = true;
8434 				continue;
8435 			}
8436 
8437 			/* Virtual kcfg externs are customly handled by libbpf */
8438 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8439 				value = get_kernel_version();
8440 				if (!value) {
8441 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8442 					return -EINVAL;
8443 				}
8444 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8445 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8446 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8447 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8448 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8449 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8450 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8451 				 * customly by libbpf (their values don't come from Kconfig).
8452 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8453 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8454 				 * externs.
8455 				 */
8456 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8457 				return -EINVAL;
8458 			}
8459 
8460 			err = set_kcfg_value_num(ext, ext_ptr, value);
8461 			if (err)
8462 				return err;
8463 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8464 				 ext->name, (long long)value);
8465 		} else {
8466 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8467 			return -EINVAL;
8468 		}
8469 	}
8470 	if (need_config && extra_kconfig) {
8471 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8472 		if (err)
8473 			return -EINVAL;
8474 		need_config = false;
8475 		for (i = 0; i < obj->nr_extern; i++) {
8476 			ext = &obj->externs[i];
8477 			if (ext->type == EXT_KCFG && !ext->is_set) {
8478 				need_config = true;
8479 				break;
8480 			}
8481 		}
8482 	}
8483 	if (need_config) {
8484 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8485 		if (err)
8486 			return -EINVAL;
8487 	}
8488 	if (need_kallsyms) {
8489 		err = bpf_object__read_kallsyms_file(obj);
8490 		if (err)
8491 			return -EINVAL;
8492 	}
8493 	if (need_vmlinux_btf) {
8494 		err = bpf_object__resolve_ksyms_btf_id(obj);
8495 		if (err)
8496 			return -EINVAL;
8497 	}
8498 	for (i = 0; i < obj->nr_extern; i++) {
8499 		ext = &obj->externs[i];
8500 
8501 		if (!ext->is_set && !ext->is_weak) {
8502 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8503 			return -ESRCH;
8504 		} else if (!ext->is_set) {
8505 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8506 				 ext->name);
8507 		}
8508 	}
8509 
8510 	return 0;
8511 }
8512 
bpf_map_prepare_vdata(const struct bpf_map * map)8513 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8514 {
8515 	const struct btf_type *type;
8516 	struct bpf_struct_ops *st_ops;
8517 	__u32 i;
8518 
8519 	st_ops = map->st_ops;
8520 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8521 	for (i = 0; i < btf_vlen(type); i++) {
8522 		struct bpf_program *prog = st_ops->progs[i];
8523 		void *kern_data;
8524 		int prog_fd;
8525 
8526 		if (!prog)
8527 			continue;
8528 
8529 		prog_fd = bpf_program__fd(prog);
8530 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8531 		*(unsigned long *)kern_data = prog_fd;
8532 	}
8533 }
8534 
bpf_object_prepare_struct_ops(struct bpf_object * obj)8535 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8536 {
8537 	struct bpf_map *map;
8538 	int i;
8539 
8540 	for (i = 0; i < obj->nr_maps; i++) {
8541 		map = &obj->maps[i];
8542 
8543 		if (!bpf_map__is_struct_ops(map))
8544 			continue;
8545 
8546 		if (!map->autocreate)
8547 			continue;
8548 
8549 		bpf_map_prepare_vdata(map);
8550 	}
8551 
8552 	return 0;
8553 }
8554 
bpf_object_unpin(struct bpf_object * obj)8555 static void bpf_object_unpin(struct bpf_object *obj)
8556 {
8557 	int i;
8558 
8559 	/* unpin any maps that were auto-pinned during load */
8560 	for (i = 0; i < obj->nr_maps; i++)
8561 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8562 			bpf_map__unpin(&obj->maps[i], NULL);
8563 }
8564 
bpf_object_post_load_cleanup(struct bpf_object * obj)8565 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8566 {
8567 	int i;
8568 
8569 	/* clean up fd_array */
8570 	zfree(&obj->fd_array);
8571 
8572 	/* clean up module BTFs */
8573 	for (i = 0; i < obj->btf_module_cnt; i++) {
8574 		close(obj->btf_modules[i].fd);
8575 		btf__free(obj->btf_modules[i].btf);
8576 		free(obj->btf_modules[i].name);
8577 	}
8578 	obj->btf_module_cnt = 0;
8579 	zfree(&obj->btf_modules);
8580 
8581 	/* clean up vmlinux BTF */
8582 	btf__free(obj->btf_vmlinux);
8583 	obj->btf_vmlinux = NULL;
8584 }
8585 
bpf_object_prepare(struct bpf_object * obj,const char * target_btf_path)8586 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8587 {
8588 	int err;
8589 
8590 	if (obj->state >= OBJ_PREPARED) {
8591 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8592 		return -EINVAL;
8593 	}
8594 
8595 	err = bpf_object_prepare_token(obj);
8596 	err = err ? : bpf_object__probe_loading(obj);
8597 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8598 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8599 	err = err ? : bpf_object__sanitize_maps(obj);
8600 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8601 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8602 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8603 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8604 	err = err ? : bpf_object__create_maps(obj);
8605 	err = err ? : bpf_object_prepare_progs(obj);
8606 
8607 	if (err) {
8608 		bpf_object_unpin(obj);
8609 		bpf_object_unload(obj);
8610 		obj->state = OBJ_LOADED;
8611 		return err;
8612 	}
8613 
8614 	obj->state = OBJ_PREPARED;
8615 	return 0;
8616 }
8617 
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)8618 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8619 {
8620 	int err;
8621 
8622 	if (!obj)
8623 		return libbpf_err(-EINVAL);
8624 
8625 	if (obj->state >= OBJ_LOADED) {
8626 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8627 		return libbpf_err(-EINVAL);
8628 	}
8629 
8630 	/* Disallow kernel loading programs of non-native endianness but
8631 	 * permit cross-endian creation of "light skeleton".
8632 	 */
8633 	if (obj->gen_loader) {
8634 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8635 	} else if (!is_native_endianness(obj)) {
8636 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8637 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8638 	}
8639 
8640 	if (obj->state < OBJ_PREPARED) {
8641 		err = bpf_object_prepare(obj, target_btf_path);
8642 		if (err)
8643 			return libbpf_err(err);
8644 	}
8645 	err = bpf_object__load_progs(obj, extra_log_level);
8646 	err = err ? : bpf_object_init_prog_arrays(obj);
8647 	err = err ? : bpf_object_prepare_struct_ops(obj);
8648 
8649 	if (obj->gen_loader) {
8650 		/* reset FDs */
8651 		if (obj->btf)
8652 			btf__set_fd(obj->btf, -1);
8653 		if (!err)
8654 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8655 	}
8656 
8657 	bpf_object_post_load_cleanup(obj);
8658 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8659 
8660 	if (err) {
8661 		bpf_object_unpin(obj);
8662 		bpf_object_unload(obj);
8663 		pr_warn("failed to load object '%s'\n", obj->path);
8664 		return libbpf_err(err);
8665 	}
8666 
8667 	return 0;
8668 }
8669 
bpf_object__prepare(struct bpf_object * obj)8670 int bpf_object__prepare(struct bpf_object *obj)
8671 {
8672 	return libbpf_err(bpf_object_prepare(obj, NULL));
8673 }
8674 
bpf_object__load(struct bpf_object * obj)8675 int bpf_object__load(struct bpf_object *obj)
8676 {
8677 	return bpf_object_load(obj, 0, NULL);
8678 }
8679 
make_parent_dir(const char * path)8680 static int make_parent_dir(const char *path)
8681 {
8682 	char *dname, *dir;
8683 	int err = 0;
8684 
8685 	dname = strdup(path);
8686 	if (dname == NULL)
8687 		return -ENOMEM;
8688 
8689 	dir = dirname(dname);
8690 	if (mkdir(dir, 0700) && errno != EEXIST)
8691 		err = -errno;
8692 
8693 	free(dname);
8694 	if (err) {
8695 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8696 	}
8697 	return err;
8698 }
8699 
check_path(const char * path)8700 static int check_path(const char *path)
8701 {
8702 	struct statfs st_fs;
8703 	char *dname, *dir;
8704 	int err = 0;
8705 
8706 	if (path == NULL)
8707 		return -EINVAL;
8708 
8709 	dname = strdup(path);
8710 	if (dname == NULL)
8711 		return -ENOMEM;
8712 
8713 	dir = dirname(dname);
8714 	if (statfs(dir, &st_fs)) {
8715 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8716 		err = -errno;
8717 	}
8718 	free(dname);
8719 
8720 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8721 		pr_warn("specified path %s is not on BPF FS\n", path);
8722 		err = -EINVAL;
8723 	}
8724 
8725 	return err;
8726 }
8727 
bpf_program__pin(struct bpf_program * prog,const char * path)8728 int bpf_program__pin(struct bpf_program *prog, const char *path)
8729 {
8730 	int err;
8731 
8732 	if (prog->fd < 0) {
8733 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8734 		return libbpf_err(-EINVAL);
8735 	}
8736 
8737 	err = make_parent_dir(path);
8738 	if (err)
8739 		return libbpf_err(err);
8740 
8741 	err = check_path(path);
8742 	if (err)
8743 		return libbpf_err(err);
8744 
8745 	if (bpf_obj_pin(prog->fd, path)) {
8746 		err = -errno;
8747 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8748 		return libbpf_err(err);
8749 	}
8750 
8751 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8752 	return 0;
8753 }
8754 
bpf_program__unpin(struct bpf_program * prog,const char * path)8755 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8756 {
8757 	int err;
8758 
8759 	if (prog->fd < 0) {
8760 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8761 		return libbpf_err(-EINVAL);
8762 	}
8763 
8764 	err = check_path(path);
8765 	if (err)
8766 		return libbpf_err(err);
8767 
8768 	err = unlink(path);
8769 	if (err)
8770 		return libbpf_err(-errno);
8771 
8772 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8773 	return 0;
8774 }
8775 
bpf_map__pin(struct bpf_map * map,const char * path)8776 int bpf_map__pin(struct bpf_map *map, const char *path)
8777 {
8778 	int err;
8779 
8780 	if (map == NULL) {
8781 		pr_warn("invalid map pointer\n");
8782 		return libbpf_err(-EINVAL);
8783 	}
8784 
8785 	if (map->fd < 0) {
8786 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8787 		return libbpf_err(-EINVAL);
8788 	}
8789 
8790 	if (map->pin_path) {
8791 		if (path && strcmp(path, map->pin_path)) {
8792 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8793 				bpf_map__name(map), map->pin_path, path);
8794 			return libbpf_err(-EINVAL);
8795 		} else if (map->pinned) {
8796 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8797 				 bpf_map__name(map), map->pin_path);
8798 			return 0;
8799 		}
8800 	} else {
8801 		if (!path) {
8802 			pr_warn("missing a path to pin map '%s' at\n",
8803 				bpf_map__name(map));
8804 			return libbpf_err(-EINVAL);
8805 		} else if (map->pinned) {
8806 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8807 			return libbpf_err(-EEXIST);
8808 		}
8809 
8810 		map->pin_path = strdup(path);
8811 		if (!map->pin_path) {
8812 			err = -errno;
8813 			goto out_err;
8814 		}
8815 	}
8816 
8817 	err = make_parent_dir(map->pin_path);
8818 	if (err)
8819 		return libbpf_err(err);
8820 
8821 	err = check_path(map->pin_path);
8822 	if (err)
8823 		return libbpf_err(err);
8824 
8825 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8826 		err = -errno;
8827 		goto out_err;
8828 	}
8829 
8830 	map->pinned = true;
8831 	pr_debug("pinned map '%s'\n", map->pin_path);
8832 
8833 	return 0;
8834 
8835 out_err:
8836 	pr_warn("failed to pin map: %s\n", errstr(err));
8837 	return libbpf_err(err);
8838 }
8839 
bpf_map__unpin(struct bpf_map * map,const char * path)8840 int bpf_map__unpin(struct bpf_map *map, const char *path)
8841 {
8842 	int err;
8843 
8844 	if (map == NULL) {
8845 		pr_warn("invalid map pointer\n");
8846 		return libbpf_err(-EINVAL);
8847 	}
8848 
8849 	if (map->pin_path) {
8850 		if (path && strcmp(path, map->pin_path)) {
8851 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8852 				bpf_map__name(map), map->pin_path, path);
8853 			return libbpf_err(-EINVAL);
8854 		}
8855 		path = map->pin_path;
8856 	} else if (!path) {
8857 		pr_warn("no path to unpin map '%s' from\n",
8858 			bpf_map__name(map));
8859 		return libbpf_err(-EINVAL);
8860 	}
8861 
8862 	err = check_path(path);
8863 	if (err)
8864 		return libbpf_err(err);
8865 
8866 	err = unlink(path);
8867 	if (err != 0)
8868 		return libbpf_err(-errno);
8869 
8870 	map->pinned = false;
8871 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8872 
8873 	return 0;
8874 }
8875 
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8876 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8877 {
8878 	char *new = NULL;
8879 
8880 	if (path) {
8881 		new = strdup(path);
8882 		if (!new)
8883 			return libbpf_err(-errno);
8884 	}
8885 
8886 	free(map->pin_path);
8887 	map->pin_path = new;
8888 	return 0;
8889 }
8890 
8891 __alias(bpf_map__pin_path)
8892 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8893 
bpf_map__pin_path(const struct bpf_map * map)8894 const char *bpf_map__pin_path(const struct bpf_map *map)
8895 {
8896 	return map->pin_path;
8897 }
8898 
bpf_map__is_pinned(const struct bpf_map * map)8899 bool bpf_map__is_pinned(const struct bpf_map *map)
8900 {
8901 	return map->pinned;
8902 }
8903 
sanitize_pin_path(char * s)8904 static void sanitize_pin_path(char *s)
8905 {
8906 	/* bpffs disallows periods in path names */
8907 	while (*s) {
8908 		if (*s == '.')
8909 			*s = '_';
8910 		s++;
8911 	}
8912 }
8913 
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8914 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8915 {
8916 	struct bpf_map *map;
8917 	int err;
8918 
8919 	if (!obj)
8920 		return libbpf_err(-ENOENT);
8921 
8922 	if (obj->state < OBJ_PREPARED) {
8923 		pr_warn("object not yet loaded; load it first\n");
8924 		return libbpf_err(-ENOENT);
8925 	}
8926 
8927 	bpf_object__for_each_map(map, obj) {
8928 		char *pin_path = NULL;
8929 		char buf[PATH_MAX];
8930 
8931 		if (!map->autocreate)
8932 			continue;
8933 
8934 		if (path) {
8935 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8936 			if (err)
8937 				goto err_unpin_maps;
8938 			sanitize_pin_path(buf);
8939 			pin_path = buf;
8940 		} else if (!map->pin_path) {
8941 			continue;
8942 		}
8943 
8944 		err = bpf_map__pin(map, pin_path);
8945 		if (err)
8946 			goto err_unpin_maps;
8947 	}
8948 
8949 	return 0;
8950 
8951 err_unpin_maps:
8952 	while ((map = bpf_object__prev_map(obj, map))) {
8953 		if (!map->pin_path)
8954 			continue;
8955 
8956 		bpf_map__unpin(map, NULL);
8957 	}
8958 
8959 	return libbpf_err(err);
8960 }
8961 
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8962 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8963 {
8964 	struct bpf_map *map;
8965 	int err;
8966 
8967 	if (!obj)
8968 		return libbpf_err(-ENOENT);
8969 
8970 	bpf_object__for_each_map(map, obj) {
8971 		char *pin_path = NULL;
8972 		char buf[PATH_MAX];
8973 
8974 		if (path) {
8975 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8976 			if (err)
8977 				return libbpf_err(err);
8978 			sanitize_pin_path(buf);
8979 			pin_path = buf;
8980 		} else if (!map->pin_path) {
8981 			continue;
8982 		}
8983 
8984 		err = bpf_map__unpin(map, pin_path);
8985 		if (err)
8986 			return libbpf_err(err);
8987 	}
8988 
8989 	return 0;
8990 }
8991 
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8992 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8993 {
8994 	struct bpf_program *prog;
8995 	char buf[PATH_MAX];
8996 	int err;
8997 
8998 	if (!obj)
8999 		return libbpf_err(-ENOENT);
9000 
9001 	if (obj->state < OBJ_LOADED) {
9002 		pr_warn("object not yet loaded; load it first\n");
9003 		return libbpf_err(-ENOENT);
9004 	}
9005 
9006 	bpf_object__for_each_program(prog, obj) {
9007 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9008 		if (err)
9009 			goto err_unpin_programs;
9010 
9011 		err = bpf_program__pin(prog, buf);
9012 		if (err)
9013 			goto err_unpin_programs;
9014 	}
9015 
9016 	return 0;
9017 
9018 err_unpin_programs:
9019 	while ((prog = bpf_object__prev_program(obj, prog))) {
9020 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9021 			continue;
9022 
9023 		bpf_program__unpin(prog, buf);
9024 	}
9025 
9026 	return libbpf_err(err);
9027 }
9028 
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)9029 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9030 {
9031 	struct bpf_program *prog;
9032 	int err;
9033 
9034 	if (!obj)
9035 		return libbpf_err(-ENOENT);
9036 
9037 	bpf_object__for_each_program(prog, obj) {
9038 		char buf[PATH_MAX];
9039 
9040 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9041 		if (err)
9042 			return libbpf_err(err);
9043 
9044 		err = bpf_program__unpin(prog, buf);
9045 		if (err)
9046 			return libbpf_err(err);
9047 	}
9048 
9049 	return 0;
9050 }
9051 
bpf_object__pin(struct bpf_object * obj,const char * path)9052 int bpf_object__pin(struct bpf_object *obj, const char *path)
9053 {
9054 	int err;
9055 
9056 	err = bpf_object__pin_maps(obj, path);
9057 	if (err)
9058 		return libbpf_err(err);
9059 
9060 	err = bpf_object__pin_programs(obj, path);
9061 	if (err) {
9062 		bpf_object__unpin_maps(obj, path);
9063 		return libbpf_err(err);
9064 	}
9065 
9066 	return 0;
9067 }
9068 
bpf_object__unpin(struct bpf_object * obj,const char * path)9069 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9070 {
9071 	int err;
9072 
9073 	err = bpf_object__unpin_programs(obj, path);
9074 	if (err)
9075 		return libbpf_err(err);
9076 
9077 	err = bpf_object__unpin_maps(obj, path);
9078 	if (err)
9079 		return libbpf_err(err);
9080 
9081 	return 0;
9082 }
9083 
bpf_map__destroy(struct bpf_map * map)9084 static void bpf_map__destroy(struct bpf_map *map)
9085 {
9086 	if (map->inner_map) {
9087 		bpf_map__destroy(map->inner_map);
9088 		zfree(&map->inner_map);
9089 	}
9090 
9091 	zfree(&map->init_slots);
9092 	map->init_slots_sz = 0;
9093 
9094 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9095 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9096 	map->mmaped = NULL;
9097 
9098 	if (map->st_ops) {
9099 		zfree(&map->st_ops->data);
9100 		zfree(&map->st_ops->progs);
9101 		zfree(&map->st_ops->kern_func_off);
9102 		zfree(&map->st_ops);
9103 	}
9104 
9105 	zfree(&map->name);
9106 	zfree(&map->real_name);
9107 	zfree(&map->pin_path);
9108 
9109 	if (map->fd >= 0)
9110 		zclose(map->fd);
9111 }
9112 
bpf_object__close(struct bpf_object * obj)9113 void bpf_object__close(struct bpf_object *obj)
9114 {
9115 	size_t i;
9116 
9117 	if (IS_ERR_OR_NULL(obj))
9118 		return;
9119 
9120 	/*
9121 	 * if user called bpf_object__prepare() without ever getting to
9122 	 * bpf_object__load(), we need to clean up stuff that is normally
9123 	 * cleaned up at the end of loading step
9124 	 */
9125 	bpf_object_post_load_cleanup(obj);
9126 
9127 	usdt_manager_free(obj->usdt_man);
9128 	obj->usdt_man = NULL;
9129 
9130 	bpf_gen__free(obj->gen_loader);
9131 	bpf_object__elf_finish(obj);
9132 	bpf_object_unload(obj);
9133 	btf__free(obj->btf);
9134 	btf__free(obj->btf_vmlinux);
9135 	btf_ext__free(obj->btf_ext);
9136 
9137 	for (i = 0; i < obj->nr_maps; i++)
9138 		bpf_map__destroy(&obj->maps[i]);
9139 
9140 	zfree(&obj->btf_custom_path);
9141 	zfree(&obj->kconfig);
9142 
9143 	for (i = 0; i < obj->nr_extern; i++) {
9144 		zfree(&obj->externs[i].name);
9145 		zfree(&obj->externs[i].essent_name);
9146 	}
9147 
9148 	zfree(&obj->externs);
9149 	obj->nr_extern = 0;
9150 
9151 	zfree(&obj->maps);
9152 	obj->nr_maps = 0;
9153 
9154 	if (obj->programs && obj->nr_programs) {
9155 		for (i = 0; i < obj->nr_programs; i++)
9156 			bpf_program__exit(&obj->programs[i]);
9157 	}
9158 	zfree(&obj->programs);
9159 
9160 	zfree(&obj->feat_cache);
9161 	zfree(&obj->token_path);
9162 	if (obj->token_fd > 0)
9163 		close(obj->token_fd);
9164 
9165 	zfree(&obj->arena_data);
9166 
9167 	free(obj);
9168 }
9169 
bpf_object__name(const struct bpf_object * obj)9170 const char *bpf_object__name(const struct bpf_object *obj)
9171 {
9172 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9173 }
9174 
bpf_object__kversion(const struct bpf_object * obj)9175 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9176 {
9177 	return obj ? obj->kern_version : 0;
9178 }
9179 
bpf_object__token_fd(const struct bpf_object * obj)9180 int bpf_object__token_fd(const struct bpf_object *obj)
9181 {
9182 	return obj->token_fd ?: -1;
9183 }
9184 
bpf_object__btf(const struct bpf_object * obj)9185 struct btf *bpf_object__btf(const struct bpf_object *obj)
9186 {
9187 	return obj ? obj->btf : NULL;
9188 }
9189 
bpf_object__btf_fd(const struct bpf_object * obj)9190 int bpf_object__btf_fd(const struct bpf_object *obj)
9191 {
9192 	return obj->btf ? btf__fd(obj->btf) : -1;
9193 }
9194 
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)9195 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9196 {
9197 	if (obj->state >= OBJ_LOADED)
9198 		return libbpf_err(-EINVAL);
9199 
9200 	obj->kern_version = kern_version;
9201 
9202 	return 0;
9203 }
9204 
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)9205 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9206 {
9207 	struct bpf_gen *gen;
9208 
9209 	if (!opts)
9210 		return libbpf_err(-EFAULT);
9211 	if (!OPTS_VALID(opts, gen_loader_opts))
9212 		return libbpf_err(-EINVAL);
9213 	gen = calloc(sizeof(*gen), 1);
9214 	if (!gen)
9215 		return libbpf_err(-ENOMEM);
9216 	gen->opts = opts;
9217 	gen->swapped_endian = !is_native_endianness(obj);
9218 	obj->gen_loader = gen;
9219 	return 0;
9220 }
9221 
9222 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)9223 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9224 		    bool forward)
9225 {
9226 	size_t nr_programs = obj->nr_programs;
9227 	ssize_t idx;
9228 
9229 	if (!nr_programs)
9230 		return NULL;
9231 
9232 	if (!p)
9233 		/* Iter from the beginning */
9234 		return forward ? &obj->programs[0] :
9235 			&obj->programs[nr_programs - 1];
9236 
9237 	if (p->obj != obj) {
9238 		pr_warn("error: program handler doesn't match object\n");
9239 		return errno = EINVAL, NULL;
9240 	}
9241 
9242 	idx = (p - obj->programs) + (forward ? 1 : -1);
9243 	if (idx >= obj->nr_programs || idx < 0)
9244 		return NULL;
9245 	return &obj->programs[idx];
9246 }
9247 
9248 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)9249 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9250 {
9251 	struct bpf_program *prog = prev;
9252 
9253 	do {
9254 		prog = __bpf_program__iter(prog, obj, true);
9255 	} while (prog && prog_is_subprog(obj, prog));
9256 
9257 	return prog;
9258 }
9259 
9260 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)9261 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9262 {
9263 	struct bpf_program *prog = next;
9264 
9265 	do {
9266 		prog = __bpf_program__iter(prog, obj, false);
9267 	} while (prog && prog_is_subprog(obj, prog));
9268 
9269 	return prog;
9270 }
9271 
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)9272 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9273 {
9274 	prog->prog_ifindex = ifindex;
9275 }
9276 
bpf_program__name(const struct bpf_program * prog)9277 const char *bpf_program__name(const struct bpf_program *prog)
9278 {
9279 	return prog->name;
9280 }
9281 
bpf_program__section_name(const struct bpf_program * prog)9282 const char *bpf_program__section_name(const struct bpf_program *prog)
9283 {
9284 	return prog->sec_name;
9285 }
9286 
bpf_program__autoload(const struct bpf_program * prog)9287 bool bpf_program__autoload(const struct bpf_program *prog)
9288 {
9289 	return prog->autoload;
9290 }
9291 
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)9292 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9293 {
9294 	if (prog->obj->state >= OBJ_LOADED)
9295 		return libbpf_err(-EINVAL);
9296 
9297 	prog->autoload = autoload;
9298 	return 0;
9299 }
9300 
bpf_program__autoattach(const struct bpf_program * prog)9301 bool bpf_program__autoattach(const struct bpf_program *prog)
9302 {
9303 	return prog->autoattach;
9304 }
9305 
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)9306 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9307 {
9308 	prog->autoattach = autoattach;
9309 }
9310 
bpf_program__insns(const struct bpf_program * prog)9311 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9312 {
9313 	return prog->insns;
9314 }
9315 
bpf_program__insn_cnt(const struct bpf_program * prog)9316 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9317 {
9318 	return prog->insns_cnt;
9319 }
9320 
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)9321 int bpf_program__set_insns(struct bpf_program *prog,
9322 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9323 {
9324 	struct bpf_insn *insns;
9325 
9326 	if (prog->obj->state >= OBJ_LOADED)
9327 		return libbpf_err(-EBUSY);
9328 
9329 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9330 	/* NULL is a valid return from reallocarray if the new count is zero */
9331 	if (!insns && new_insn_cnt) {
9332 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9333 		return libbpf_err(-ENOMEM);
9334 	}
9335 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9336 
9337 	prog->insns = insns;
9338 	prog->insns_cnt = new_insn_cnt;
9339 	return 0;
9340 }
9341 
bpf_program__fd(const struct bpf_program * prog)9342 int bpf_program__fd(const struct bpf_program *prog)
9343 {
9344 	if (!prog)
9345 		return libbpf_err(-EINVAL);
9346 
9347 	if (prog->fd < 0)
9348 		return libbpf_err(-ENOENT);
9349 
9350 	return prog->fd;
9351 }
9352 
9353 __alias(bpf_program__type)
9354 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9355 
bpf_program__type(const struct bpf_program * prog)9356 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9357 {
9358 	return prog->type;
9359 }
9360 
9361 static size_t custom_sec_def_cnt;
9362 static struct bpf_sec_def *custom_sec_defs;
9363 static struct bpf_sec_def custom_fallback_def;
9364 static bool has_custom_fallback_def;
9365 static int last_custom_sec_def_handler_id;
9366 
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)9367 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9368 {
9369 	if (prog->obj->state >= OBJ_LOADED)
9370 		return libbpf_err(-EBUSY);
9371 
9372 	/* if type is not changed, do nothing */
9373 	if (prog->type == type)
9374 		return 0;
9375 
9376 	prog->type = type;
9377 
9378 	/* If a program type was changed, we need to reset associated SEC()
9379 	 * handler, as it will be invalid now. The only exception is a generic
9380 	 * fallback handler, which by definition is program type-agnostic and
9381 	 * is a catch-all custom handler, optionally set by the application,
9382 	 * so should be able to handle any type of BPF program.
9383 	 */
9384 	if (prog->sec_def != &custom_fallback_def)
9385 		prog->sec_def = NULL;
9386 	return 0;
9387 }
9388 
9389 __alias(bpf_program__expected_attach_type)
9390 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9391 
bpf_program__expected_attach_type(const struct bpf_program * prog)9392 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9393 {
9394 	return prog->expected_attach_type;
9395 }
9396 
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)9397 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9398 					   enum bpf_attach_type type)
9399 {
9400 	if (prog->obj->state >= OBJ_LOADED)
9401 		return libbpf_err(-EBUSY);
9402 
9403 	prog->expected_attach_type = type;
9404 	return 0;
9405 }
9406 
bpf_program__flags(const struct bpf_program * prog)9407 __u32 bpf_program__flags(const struct bpf_program *prog)
9408 {
9409 	return prog->prog_flags;
9410 }
9411 
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)9412 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9413 {
9414 	if (prog->obj->state >= OBJ_LOADED)
9415 		return libbpf_err(-EBUSY);
9416 
9417 	prog->prog_flags = flags;
9418 	return 0;
9419 }
9420 
bpf_program__log_level(const struct bpf_program * prog)9421 __u32 bpf_program__log_level(const struct bpf_program *prog)
9422 {
9423 	return prog->log_level;
9424 }
9425 
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)9426 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9427 {
9428 	if (prog->obj->state >= OBJ_LOADED)
9429 		return libbpf_err(-EBUSY);
9430 
9431 	prog->log_level = log_level;
9432 	return 0;
9433 }
9434 
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)9435 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9436 {
9437 	*log_size = prog->log_size;
9438 	return prog->log_buf;
9439 }
9440 
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)9441 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9442 {
9443 	if (log_size && !log_buf)
9444 		return libbpf_err(-EINVAL);
9445 	if (prog->log_size > UINT_MAX)
9446 		return libbpf_err(-EINVAL);
9447 	if (prog->obj->state >= OBJ_LOADED)
9448 		return libbpf_err(-EBUSY);
9449 
9450 	prog->log_buf = log_buf;
9451 	prog->log_size = log_size;
9452 	return 0;
9453 }
9454 
bpf_program__func_info(const struct bpf_program * prog)9455 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9456 {
9457 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9458 		return libbpf_err_ptr(-EOPNOTSUPP);
9459 	return prog->func_info;
9460 }
9461 
bpf_program__func_info_cnt(const struct bpf_program * prog)9462 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9463 {
9464 	return prog->func_info_cnt;
9465 }
9466 
bpf_program__line_info(const struct bpf_program * prog)9467 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9468 {
9469 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9470 		return libbpf_err_ptr(-EOPNOTSUPP);
9471 	return prog->line_info;
9472 }
9473 
bpf_program__line_info_cnt(const struct bpf_program * prog)9474 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9475 {
9476 	return prog->line_info_cnt;
9477 }
9478 
9479 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9480 	.sec = (char *)sec_pfx,						    \
9481 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9482 	.expected_attach_type = atype,					    \
9483 	.cookie = (long)(flags),					    \
9484 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9485 	__VA_ARGS__							    \
9486 }
9487 
9488 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9489 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9490 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9491 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9492 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9493 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9494 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9495 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9496 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9497 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9498 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9499 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9500 
9501 static const struct bpf_sec_def section_defs[] = {
9502 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9503 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9504 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9505 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9506 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9507 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9508 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9509 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9510 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9511 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9512 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9513 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9514 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9515 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9516 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9517 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9518 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9519 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9520 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9521 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9522 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9523 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9524 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9525 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9526 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9527 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9528 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9529 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9530 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9531 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9532 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9533 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9534 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9535 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9536 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9537 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9538 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9539 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9540 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9541 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9542 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9543 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9544 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9545 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9546 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9547 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9548 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9549 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9550 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9551 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9552 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9553 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9554 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9555 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9556 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9557 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9558 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9559 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9560 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9561 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9562 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9563 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9564 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9565 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9566 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9567 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9568 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9569 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9570 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9571 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9572 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9573 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9574 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9575 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9576 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9577 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9578 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9579 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9580 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9581 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9582 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9583 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9584 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9585 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9586 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9587 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9588 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9589 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9590 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9591 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9592 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9593 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9594 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9595 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9596 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9597 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9598 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9599 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9600 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9601 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9602 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9603 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9604 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9605 };
9606 
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)9607 int libbpf_register_prog_handler(const char *sec,
9608 				 enum bpf_prog_type prog_type,
9609 				 enum bpf_attach_type exp_attach_type,
9610 				 const struct libbpf_prog_handler_opts *opts)
9611 {
9612 	struct bpf_sec_def *sec_def;
9613 
9614 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9615 		return libbpf_err(-EINVAL);
9616 
9617 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9618 		return libbpf_err(-E2BIG);
9619 
9620 	if (sec) {
9621 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9622 					      sizeof(*sec_def));
9623 		if (!sec_def)
9624 			return libbpf_err(-ENOMEM);
9625 
9626 		custom_sec_defs = sec_def;
9627 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9628 	} else {
9629 		if (has_custom_fallback_def)
9630 			return libbpf_err(-EBUSY);
9631 
9632 		sec_def = &custom_fallback_def;
9633 	}
9634 
9635 	sec_def->sec = sec ? strdup(sec) : NULL;
9636 	if (sec && !sec_def->sec)
9637 		return libbpf_err(-ENOMEM);
9638 
9639 	sec_def->prog_type = prog_type;
9640 	sec_def->expected_attach_type = exp_attach_type;
9641 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9642 
9643 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9644 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9645 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9646 
9647 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9648 
9649 	if (sec)
9650 		custom_sec_def_cnt++;
9651 	else
9652 		has_custom_fallback_def = true;
9653 
9654 	return sec_def->handler_id;
9655 }
9656 
libbpf_unregister_prog_handler(int handler_id)9657 int libbpf_unregister_prog_handler(int handler_id)
9658 {
9659 	struct bpf_sec_def *sec_defs;
9660 	int i;
9661 
9662 	if (handler_id <= 0)
9663 		return libbpf_err(-EINVAL);
9664 
9665 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9666 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9667 		has_custom_fallback_def = false;
9668 		return 0;
9669 	}
9670 
9671 	for (i = 0; i < custom_sec_def_cnt; i++) {
9672 		if (custom_sec_defs[i].handler_id == handler_id)
9673 			break;
9674 	}
9675 
9676 	if (i == custom_sec_def_cnt)
9677 		return libbpf_err(-ENOENT);
9678 
9679 	free(custom_sec_defs[i].sec);
9680 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9681 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9682 	custom_sec_def_cnt--;
9683 
9684 	/* try to shrink the array, but it's ok if we couldn't */
9685 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9686 	/* if new count is zero, reallocarray can return a valid NULL result;
9687 	 * in this case the previous pointer will be freed, so we *have to*
9688 	 * reassign old pointer to the new value (even if it's NULL)
9689 	 */
9690 	if (sec_defs || custom_sec_def_cnt == 0)
9691 		custom_sec_defs = sec_defs;
9692 
9693 	return 0;
9694 }
9695 
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)9696 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9697 {
9698 	size_t len = strlen(sec_def->sec);
9699 
9700 	/* "type/" always has to have proper SEC("type/extras") form */
9701 	if (sec_def->sec[len - 1] == '/') {
9702 		if (str_has_pfx(sec_name, sec_def->sec))
9703 			return true;
9704 		return false;
9705 	}
9706 
9707 	/* "type+" means it can be either exact SEC("type") or
9708 	 * well-formed SEC("type/extras") with proper '/' separator
9709 	 */
9710 	if (sec_def->sec[len - 1] == '+') {
9711 		len--;
9712 		/* not even a prefix */
9713 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9714 			return false;
9715 		/* exact match or has '/' separator */
9716 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9717 			return true;
9718 		return false;
9719 	}
9720 
9721 	return strcmp(sec_name, sec_def->sec) == 0;
9722 }
9723 
find_sec_def(const char * sec_name)9724 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9725 {
9726 	const struct bpf_sec_def *sec_def;
9727 	int i, n;
9728 
9729 	n = custom_sec_def_cnt;
9730 	for (i = 0; i < n; i++) {
9731 		sec_def = &custom_sec_defs[i];
9732 		if (sec_def_matches(sec_def, sec_name))
9733 			return sec_def;
9734 	}
9735 
9736 	n = ARRAY_SIZE(section_defs);
9737 	for (i = 0; i < n; i++) {
9738 		sec_def = &section_defs[i];
9739 		if (sec_def_matches(sec_def, sec_name))
9740 			return sec_def;
9741 	}
9742 
9743 	if (has_custom_fallback_def)
9744 		return &custom_fallback_def;
9745 
9746 	return NULL;
9747 }
9748 
9749 #define MAX_TYPE_NAME_SIZE 32
9750 
libbpf_get_type_names(bool attach_type)9751 static char *libbpf_get_type_names(bool attach_type)
9752 {
9753 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9754 	char *buf;
9755 
9756 	buf = malloc(len);
9757 	if (!buf)
9758 		return NULL;
9759 
9760 	buf[0] = '\0';
9761 	/* Forge string buf with all available names */
9762 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9763 		const struct bpf_sec_def *sec_def = &section_defs[i];
9764 
9765 		if (attach_type) {
9766 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9767 				continue;
9768 
9769 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9770 				continue;
9771 		}
9772 
9773 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9774 			free(buf);
9775 			return NULL;
9776 		}
9777 		strcat(buf, " ");
9778 		strcat(buf, section_defs[i].sec);
9779 	}
9780 
9781 	return buf;
9782 }
9783 
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9784 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9785 			     enum bpf_attach_type *expected_attach_type)
9786 {
9787 	const struct bpf_sec_def *sec_def;
9788 	char *type_names;
9789 
9790 	if (!name)
9791 		return libbpf_err(-EINVAL);
9792 
9793 	sec_def = find_sec_def(name);
9794 	if (sec_def) {
9795 		*prog_type = sec_def->prog_type;
9796 		*expected_attach_type = sec_def->expected_attach_type;
9797 		return 0;
9798 	}
9799 
9800 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9801 	type_names = libbpf_get_type_names(false);
9802 	if (type_names != NULL) {
9803 		pr_debug("supported section(type) names are:%s\n", type_names);
9804 		free(type_names);
9805 	}
9806 
9807 	return libbpf_err(-ESRCH);
9808 }
9809 
libbpf_bpf_attach_type_str(enum bpf_attach_type t)9810 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9811 {
9812 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9813 		return NULL;
9814 
9815 	return attach_type_name[t];
9816 }
9817 
libbpf_bpf_link_type_str(enum bpf_link_type t)9818 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9819 {
9820 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9821 		return NULL;
9822 
9823 	return link_type_name[t];
9824 }
9825 
libbpf_bpf_map_type_str(enum bpf_map_type t)9826 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9827 {
9828 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9829 		return NULL;
9830 
9831 	return map_type_name[t];
9832 }
9833 
libbpf_bpf_prog_type_str(enum bpf_prog_type t)9834 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9835 {
9836 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9837 		return NULL;
9838 
9839 	return prog_type_name[t];
9840 }
9841 
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)9842 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9843 						     int sec_idx,
9844 						     size_t offset)
9845 {
9846 	struct bpf_map *map;
9847 	size_t i;
9848 
9849 	for (i = 0; i < obj->nr_maps; i++) {
9850 		map = &obj->maps[i];
9851 		if (!bpf_map__is_struct_ops(map))
9852 			continue;
9853 		if (map->sec_idx == sec_idx &&
9854 		    map->sec_offset <= offset &&
9855 		    offset - map->sec_offset < map->def.value_size)
9856 			return map;
9857 	}
9858 
9859 	return NULL;
9860 }
9861 
9862 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9863  * st_ops->data for shadow type.
9864  */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)9865 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9866 					    Elf64_Shdr *shdr, Elf_Data *data)
9867 {
9868 	const struct btf_type *type;
9869 	const struct btf_member *member;
9870 	struct bpf_struct_ops *st_ops;
9871 	struct bpf_program *prog;
9872 	unsigned int shdr_idx;
9873 	const struct btf *btf;
9874 	struct bpf_map *map;
9875 	unsigned int moff, insn_idx;
9876 	const char *name;
9877 	__u32 member_idx;
9878 	Elf64_Sym *sym;
9879 	Elf64_Rel *rel;
9880 	int i, nrels;
9881 
9882 	btf = obj->btf;
9883 	nrels = shdr->sh_size / shdr->sh_entsize;
9884 	for (i = 0; i < nrels; i++) {
9885 		rel = elf_rel_by_idx(data, i);
9886 		if (!rel) {
9887 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9888 			return -LIBBPF_ERRNO__FORMAT;
9889 		}
9890 
9891 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9892 		if (!sym) {
9893 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9894 				(size_t)ELF64_R_SYM(rel->r_info));
9895 			return -LIBBPF_ERRNO__FORMAT;
9896 		}
9897 
9898 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9899 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9900 		if (!map) {
9901 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9902 				(size_t)rel->r_offset);
9903 			return -EINVAL;
9904 		}
9905 
9906 		moff = rel->r_offset - map->sec_offset;
9907 		shdr_idx = sym->st_shndx;
9908 		st_ops = map->st_ops;
9909 		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",
9910 			 map->name,
9911 			 (long long)(rel->r_info >> 32),
9912 			 (long long)sym->st_value,
9913 			 shdr_idx, (size_t)rel->r_offset,
9914 			 map->sec_offset, sym->st_name, name);
9915 
9916 		if (shdr_idx >= SHN_LORESERVE) {
9917 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9918 				map->name, (size_t)rel->r_offset, shdr_idx);
9919 			return -LIBBPF_ERRNO__RELOC;
9920 		}
9921 		if (sym->st_value % BPF_INSN_SZ) {
9922 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9923 				map->name, (unsigned long long)sym->st_value);
9924 			return -LIBBPF_ERRNO__FORMAT;
9925 		}
9926 		insn_idx = sym->st_value / BPF_INSN_SZ;
9927 
9928 		type = btf__type_by_id(btf, st_ops->type_id);
9929 		member = find_member_by_offset(type, moff * 8);
9930 		if (!member) {
9931 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9932 				map->name, moff);
9933 			return -EINVAL;
9934 		}
9935 		member_idx = member - btf_members(type);
9936 		name = btf__name_by_offset(btf, member->name_off);
9937 
9938 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9939 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9940 				map->name, name);
9941 			return -EINVAL;
9942 		}
9943 
9944 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9945 		if (!prog) {
9946 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9947 				map->name, shdr_idx, name);
9948 			return -EINVAL;
9949 		}
9950 
9951 		/* prevent the use of BPF prog with invalid type */
9952 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9953 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9954 				map->name, prog->name);
9955 			return -EINVAL;
9956 		}
9957 
9958 		st_ops->progs[member_idx] = prog;
9959 
9960 		/* st_ops->data will be exposed to users, being returned by
9961 		 * bpf_map__initial_value() as a pointer to the shadow
9962 		 * type. All function pointers in the original struct type
9963 		 * should be converted to a pointer to struct bpf_program
9964 		 * in the shadow type.
9965 		 */
9966 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9967 	}
9968 
9969 	return 0;
9970 }
9971 
9972 #define BTF_TRACE_PREFIX "btf_trace_"
9973 #define BTF_LSM_PREFIX "bpf_lsm_"
9974 #define BTF_ITER_PREFIX "bpf_iter_"
9975 #define BTF_MAX_NAME_SIZE 128
9976 
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9977 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9978 				const char **prefix, int *kind)
9979 {
9980 	switch (attach_type) {
9981 	case BPF_TRACE_RAW_TP:
9982 		*prefix = BTF_TRACE_PREFIX;
9983 		*kind = BTF_KIND_TYPEDEF;
9984 		break;
9985 	case BPF_LSM_MAC:
9986 	case BPF_LSM_CGROUP:
9987 		*prefix = BTF_LSM_PREFIX;
9988 		*kind = BTF_KIND_FUNC;
9989 		break;
9990 	case BPF_TRACE_ITER:
9991 		*prefix = BTF_ITER_PREFIX;
9992 		*kind = BTF_KIND_FUNC;
9993 		break;
9994 	default:
9995 		*prefix = "";
9996 		*kind = BTF_KIND_FUNC;
9997 	}
9998 }
9999 
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)10000 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10001 				   const char *name, __u32 kind)
10002 {
10003 	char btf_type_name[BTF_MAX_NAME_SIZE];
10004 	int ret;
10005 
10006 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10007 		       "%s%s", prefix, name);
10008 	/* snprintf returns the number of characters written excluding the
10009 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10010 	 * indicates truncation.
10011 	 */
10012 	if (ret < 0 || ret >= sizeof(btf_type_name))
10013 		return -ENAMETOOLONG;
10014 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10015 }
10016 
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)10017 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10018 				     enum bpf_attach_type attach_type)
10019 {
10020 	const char *prefix;
10021 	int kind;
10022 
10023 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10024 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10025 }
10026 
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)10027 int libbpf_find_vmlinux_btf_id(const char *name,
10028 			       enum bpf_attach_type attach_type)
10029 {
10030 	struct btf *btf;
10031 	int err;
10032 
10033 	btf = btf__load_vmlinux_btf();
10034 	err = libbpf_get_error(btf);
10035 	if (err) {
10036 		pr_warn("vmlinux BTF is not found\n");
10037 		return libbpf_err(err);
10038 	}
10039 
10040 	err = find_attach_btf_id(btf, name, attach_type);
10041 	if (err <= 0)
10042 		pr_warn("%s is not found in vmlinux BTF\n", name);
10043 
10044 	btf__free(btf);
10045 	return libbpf_err(err);
10046 }
10047 
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd,int token_fd)10048 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10049 {
10050 	struct bpf_prog_info info;
10051 	__u32 info_len = sizeof(info);
10052 	struct btf *btf;
10053 	int err;
10054 
10055 	memset(&info, 0, info_len);
10056 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10057 	if (err) {
10058 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10059 			attach_prog_fd, errstr(err));
10060 		return err;
10061 	}
10062 
10063 	err = -EINVAL;
10064 	if (!info.btf_id) {
10065 		pr_warn("The target program doesn't have BTF\n");
10066 		goto out;
10067 	}
10068 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10069 	err = libbpf_get_error(btf);
10070 	if (err) {
10071 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10072 		goto out;
10073 	}
10074 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10075 	btf__free(btf);
10076 	if (err <= 0) {
10077 		pr_warn("%s is not found in prog's BTF\n", name);
10078 		goto out;
10079 	}
10080 out:
10081 	return err;
10082 }
10083 
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)10084 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10085 			      enum bpf_attach_type attach_type,
10086 			      int *btf_obj_fd, int *btf_type_id)
10087 {
10088 	int ret, i, mod_len;
10089 	const char *fn_name, *mod_name = NULL;
10090 
10091 	fn_name = strchr(attach_name, ':');
10092 	if (fn_name) {
10093 		mod_name = attach_name;
10094 		mod_len = fn_name - mod_name;
10095 		fn_name++;
10096 	}
10097 
10098 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10099 		ret = find_attach_btf_id(obj->btf_vmlinux,
10100 					 mod_name ? fn_name : attach_name,
10101 					 attach_type);
10102 		if (ret > 0) {
10103 			*btf_obj_fd = 0; /* vmlinux BTF */
10104 			*btf_type_id = ret;
10105 			return 0;
10106 		}
10107 		if (ret != -ENOENT)
10108 			return ret;
10109 	}
10110 
10111 	ret = load_module_btfs(obj);
10112 	if (ret)
10113 		return ret;
10114 
10115 	for (i = 0; i < obj->btf_module_cnt; i++) {
10116 		const struct module_btf *mod = &obj->btf_modules[i];
10117 
10118 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10119 			continue;
10120 
10121 		ret = find_attach_btf_id(mod->btf,
10122 					 mod_name ? fn_name : attach_name,
10123 					 attach_type);
10124 		if (ret > 0) {
10125 			*btf_obj_fd = mod->fd;
10126 			*btf_type_id = ret;
10127 			return 0;
10128 		}
10129 		if (ret == -ENOENT)
10130 			continue;
10131 
10132 		return ret;
10133 	}
10134 
10135 	return -ESRCH;
10136 }
10137 
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)10138 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10139 				     int *btf_obj_fd, int *btf_type_id)
10140 {
10141 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10142 	__u32 attach_prog_fd = prog->attach_prog_fd;
10143 	int err = 0;
10144 
10145 	/* BPF program's BTF ID */
10146 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10147 		if (!attach_prog_fd) {
10148 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10149 			return -EINVAL;
10150 		}
10151 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10152 		if (err < 0) {
10153 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10154 				prog->name, attach_prog_fd, attach_name, errstr(err));
10155 			return err;
10156 		}
10157 		*btf_obj_fd = 0;
10158 		*btf_type_id = err;
10159 		return 0;
10160 	}
10161 
10162 	/* kernel/module BTF ID */
10163 	if (prog->obj->gen_loader) {
10164 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10165 		*btf_obj_fd = 0;
10166 		*btf_type_id = 1;
10167 	} else {
10168 		err = find_kernel_btf_id(prog->obj, attach_name,
10169 					 attach_type, btf_obj_fd,
10170 					 btf_type_id);
10171 	}
10172 	if (err) {
10173 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10174 			prog->name, attach_name, errstr(err));
10175 		return err;
10176 	}
10177 	return 0;
10178 }
10179 
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)10180 int libbpf_attach_type_by_name(const char *name,
10181 			       enum bpf_attach_type *attach_type)
10182 {
10183 	char *type_names;
10184 	const struct bpf_sec_def *sec_def;
10185 
10186 	if (!name)
10187 		return libbpf_err(-EINVAL);
10188 
10189 	sec_def = find_sec_def(name);
10190 	if (!sec_def) {
10191 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10192 		type_names = libbpf_get_type_names(true);
10193 		if (type_names != NULL) {
10194 			pr_debug("attachable section(type) names are:%s\n", type_names);
10195 			free(type_names);
10196 		}
10197 
10198 		return libbpf_err(-EINVAL);
10199 	}
10200 
10201 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10202 		return libbpf_err(-EINVAL);
10203 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10204 		return libbpf_err(-EINVAL);
10205 
10206 	*attach_type = sec_def->expected_attach_type;
10207 	return 0;
10208 }
10209 
bpf_map__fd(const struct bpf_map * map)10210 int bpf_map__fd(const struct bpf_map *map)
10211 {
10212 	if (!map)
10213 		return libbpf_err(-EINVAL);
10214 	if (!map_is_created(map))
10215 		return -1;
10216 	return map->fd;
10217 }
10218 
map_uses_real_name(const struct bpf_map * map)10219 static bool map_uses_real_name(const struct bpf_map *map)
10220 {
10221 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10222 	 * their user-visible name differs from kernel-visible name. Users see
10223 	 * such map's corresponding ELF section name as a map name.
10224 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10225 	 * maps to know which name has to be returned to the user.
10226 	 */
10227 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10228 		return true;
10229 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10230 		return true;
10231 	return false;
10232 }
10233 
bpf_map__name(const struct bpf_map * map)10234 const char *bpf_map__name(const struct bpf_map *map)
10235 {
10236 	if (!map)
10237 		return NULL;
10238 
10239 	if (map_uses_real_name(map))
10240 		return map->real_name;
10241 
10242 	return map->name;
10243 }
10244 
bpf_map__type(const struct bpf_map * map)10245 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10246 {
10247 	return map->def.type;
10248 }
10249 
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)10250 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10251 {
10252 	if (map_is_created(map))
10253 		return libbpf_err(-EBUSY);
10254 	map->def.type = type;
10255 	return 0;
10256 }
10257 
bpf_map__map_flags(const struct bpf_map * map)10258 __u32 bpf_map__map_flags(const struct bpf_map *map)
10259 {
10260 	return map->def.map_flags;
10261 }
10262 
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)10263 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10264 {
10265 	if (map_is_created(map))
10266 		return libbpf_err(-EBUSY);
10267 	map->def.map_flags = flags;
10268 	return 0;
10269 }
10270 
bpf_map__map_extra(const struct bpf_map * map)10271 __u64 bpf_map__map_extra(const struct bpf_map *map)
10272 {
10273 	return map->map_extra;
10274 }
10275 
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)10276 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10277 {
10278 	if (map_is_created(map))
10279 		return libbpf_err(-EBUSY);
10280 	map->map_extra = map_extra;
10281 	return 0;
10282 }
10283 
bpf_map__numa_node(const struct bpf_map * map)10284 __u32 bpf_map__numa_node(const struct bpf_map *map)
10285 {
10286 	return map->numa_node;
10287 }
10288 
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)10289 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10290 {
10291 	if (map_is_created(map))
10292 		return libbpf_err(-EBUSY);
10293 	map->numa_node = numa_node;
10294 	return 0;
10295 }
10296 
bpf_map__key_size(const struct bpf_map * map)10297 __u32 bpf_map__key_size(const struct bpf_map *map)
10298 {
10299 	return map->def.key_size;
10300 }
10301 
bpf_map__set_key_size(struct bpf_map * map,__u32 size)10302 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10303 {
10304 	if (map_is_created(map))
10305 		return libbpf_err(-EBUSY);
10306 	map->def.key_size = size;
10307 	return 0;
10308 }
10309 
bpf_map__value_size(const struct bpf_map * map)10310 __u32 bpf_map__value_size(const struct bpf_map *map)
10311 {
10312 	return map->def.value_size;
10313 }
10314 
map_btf_datasec_resize(struct bpf_map * map,__u32 size)10315 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10316 {
10317 	struct btf *btf;
10318 	struct btf_type *datasec_type, *var_type;
10319 	struct btf_var_secinfo *var;
10320 	const struct btf_type *array_type;
10321 	const struct btf_array *array;
10322 	int vlen, element_sz, new_array_id;
10323 	__u32 nr_elements;
10324 
10325 	/* check btf existence */
10326 	btf = bpf_object__btf(map->obj);
10327 	if (!btf)
10328 		return -ENOENT;
10329 
10330 	/* verify map is datasec */
10331 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10332 	if (!btf_is_datasec(datasec_type)) {
10333 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10334 			bpf_map__name(map));
10335 		return -EINVAL;
10336 	}
10337 
10338 	/* verify datasec has at least one var */
10339 	vlen = btf_vlen(datasec_type);
10340 	if (vlen == 0) {
10341 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10342 			bpf_map__name(map));
10343 		return -EINVAL;
10344 	}
10345 
10346 	/* verify last var in the datasec is an array */
10347 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10348 	var_type = btf_type_by_id(btf, var->type);
10349 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10350 	if (!btf_is_array(array_type)) {
10351 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10352 			bpf_map__name(map));
10353 		return -EINVAL;
10354 	}
10355 
10356 	/* verify request size aligns with array */
10357 	array = btf_array(array_type);
10358 	element_sz = btf__resolve_size(btf, array->type);
10359 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10360 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10361 			bpf_map__name(map), element_sz, size);
10362 		return -EINVAL;
10363 	}
10364 
10365 	/* create a new array based on the existing array, but with new length */
10366 	nr_elements = (size - var->offset) / element_sz;
10367 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10368 	if (new_array_id < 0)
10369 		return new_array_id;
10370 
10371 	/* adding a new btf type invalidates existing pointers to btf objects,
10372 	 * so refresh pointers before proceeding
10373 	 */
10374 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10375 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10376 	var_type = btf_type_by_id(btf, var->type);
10377 
10378 	/* finally update btf info */
10379 	datasec_type->size = size;
10380 	var->size = size - var->offset;
10381 	var_type->type = new_array_id;
10382 
10383 	return 0;
10384 }
10385 
bpf_map__set_value_size(struct bpf_map * map,__u32 size)10386 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10387 {
10388 	if (map_is_created(map))
10389 		return libbpf_err(-EBUSY);
10390 
10391 	if (map->mmaped) {
10392 		size_t mmap_old_sz, mmap_new_sz;
10393 		int err;
10394 
10395 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10396 			return libbpf_err(-EOPNOTSUPP);
10397 
10398 		mmap_old_sz = bpf_map_mmap_sz(map);
10399 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10400 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10401 		if (err) {
10402 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10403 				bpf_map__name(map), errstr(err));
10404 			return libbpf_err(err);
10405 		}
10406 		err = map_btf_datasec_resize(map, size);
10407 		if (err && err != -ENOENT) {
10408 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10409 				bpf_map__name(map), errstr(err));
10410 			map->btf_value_type_id = 0;
10411 			map->btf_key_type_id = 0;
10412 		}
10413 	}
10414 
10415 	map->def.value_size = size;
10416 	return 0;
10417 }
10418 
bpf_map__btf_key_type_id(const struct bpf_map * map)10419 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10420 {
10421 	return map ? map->btf_key_type_id : 0;
10422 }
10423 
bpf_map__btf_value_type_id(const struct bpf_map * map)10424 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10425 {
10426 	return map ? map->btf_value_type_id : 0;
10427 }
10428 
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)10429 int bpf_map__set_initial_value(struct bpf_map *map,
10430 			       const void *data, size_t size)
10431 {
10432 	size_t actual_sz;
10433 
10434 	if (map_is_created(map))
10435 		return libbpf_err(-EBUSY);
10436 
10437 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10438 		return libbpf_err(-EINVAL);
10439 
10440 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10441 		actual_sz = map->obj->arena_data_sz;
10442 	else
10443 		actual_sz = map->def.value_size;
10444 	if (size != actual_sz)
10445 		return libbpf_err(-EINVAL);
10446 
10447 	memcpy(map->mmaped, data, size);
10448 	return 0;
10449 }
10450 
bpf_map__initial_value(const struct bpf_map * map,size_t * psize)10451 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10452 {
10453 	if (bpf_map__is_struct_ops(map)) {
10454 		if (psize)
10455 			*psize = map->def.value_size;
10456 		return map->st_ops->data;
10457 	}
10458 
10459 	if (!map->mmaped)
10460 		return NULL;
10461 
10462 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10463 		*psize = map->obj->arena_data_sz;
10464 	else
10465 		*psize = map->def.value_size;
10466 
10467 	return map->mmaped;
10468 }
10469 
bpf_map__is_internal(const struct bpf_map * map)10470 bool bpf_map__is_internal(const struct bpf_map *map)
10471 {
10472 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10473 }
10474 
bpf_map__ifindex(const struct bpf_map * map)10475 __u32 bpf_map__ifindex(const struct bpf_map *map)
10476 {
10477 	return map->map_ifindex;
10478 }
10479 
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)10480 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10481 {
10482 	if (map_is_created(map))
10483 		return libbpf_err(-EBUSY);
10484 	map->map_ifindex = ifindex;
10485 	return 0;
10486 }
10487 
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)10488 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10489 {
10490 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10491 		pr_warn("error: unsupported map type\n");
10492 		return libbpf_err(-EINVAL);
10493 	}
10494 	if (map->inner_map_fd != -1) {
10495 		pr_warn("error: inner_map_fd already specified\n");
10496 		return libbpf_err(-EINVAL);
10497 	}
10498 	if (map->inner_map) {
10499 		bpf_map__destroy(map->inner_map);
10500 		zfree(&map->inner_map);
10501 	}
10502 	map->inner_map_fd = fd;
10503 	return 0;
10504 }
10505 
10506 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)10507 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10508 {
10509 	ssize_t idx;
10510 	struct bpf_map *s, *e;
10511 
10512 	if (!obj || !obj->maps)
10513 		return errno = EINVAL, NULL;
10514 
10515 	s = obj->maps;
10516 	e = obj->maps + obj->nr_maps;
10517 
10518 	if ((m < s) || (m >= e)) {
10519 		pr_warn("error in %s: map handler doesn't belong to object\n",
10520 			 __func__);
10521 		return errno = EINVAL, NULL;
10522 	}
10523 
10524 	idx = (m - obj->maps) + i;
10525 	if (idx >= obj->nr_maps || idx < 0)
10526 		return NULL;
10527 	return &obj->maps[idx];
10528 }
10529 
10530 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)10531 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10532 {
10533 	if (prev == NULL && obj != NULL)
10534 		return obj->maps;
10535 
10536 	return __bpf_map__iter(prev, obj, 1);
10537 }
10538 
10539 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)10540 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10541 {
10542 	if (next == NULL && obj != NULL) {
10543 		if (!obj->nr_maps)
10544 			return NULL;
10545 		return obj->maps + obj->nr_maps - 1;
10546 	}
10547 
10548 	return __bpf_map__iter(next, obj, -1);
10549 }
10550 
10551 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)10552 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10553 {
10554 	struct bpf_map *pos;
10555 
10556 	bpf_object__for_each_map(pos, obj) {
10557 		/* if it's a special internal map name (which always starts
10558 		 * with dot) then check if that special name matches the
10559 		 * real map name (ELF section name)
10560 		 */
10561 		if (name[0] == '.') {
10562 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10563 				return pos;
10564 			continue;
10565 		}
10566 		/* otherwise map name has to be an exact match */
10567 		if (map_uses_real_name(pos)) {
10568 			if (strcmp(pos->real_name, name) == 0)
10569 				return pos;
10570 			continue;
10571 		}
10572 		if (strcmp(pos->name, name) == 0)
10573 			return pos;
10574 	}
10575 	return errno = ENOENT, NULL;
10576 }
10577 
10578 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)10579 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10580 {
10581 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10582 }
10583 
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)10584 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10585 			   size_t value_sz, bool check_value_sz)
10586 {
10587 	if (!map_is_created(map)) /* map is not yet created */
10588 		return -ENOENT;
10589 
10590 	if (map->def.key_size != key_sz) {
10591 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10592 			map->name, key_sz, map->def.key_size);
10593 		return -EINVAL;
10594 	}
10595 
10596 	if (map->fd < 0) {
10597 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10598 		return -EINVAL;
10599 	}
10600 
10601 	if (!check_value_sz)
10602 		return 0;
10603 
10604 	switch (map->def.type) {
10605 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10606 	case BPF_MAP_TYPE_PERCPU_HASH:
10607 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10608 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10609 		int num_cpu = libbpf_num_possible_cpus();
10610 		size_t elem_sz = roundup(map->def.value_size, 8);
10611 
10612 		if (value_sz != num_cpu * elem_sz) {
10613 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10614 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10615 			return -EINVAL;
10616 		}
10617 		break;
10618 	}
10619 	default:
10620 		if (map->def.value_size != value_sz) {
10621 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10622 				map->name, value_sz, map->def.value_size);
10623 			return -EINVAL;
10624 		}
10625 		break;
10626 	}
10627 	return 0;
10628 }
10629 
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)10630 int bpf_map__lookup_elem(const struct bpf_map *map,
10631 			 const void *key, size_t key_sz,
10632 			 void *value, size_t value_sz, __u64 flags)
10633 {
10634 	int err;
10635 
10636 	err = validate_map_op(map, key_sz, value_sz, true);
10637 	if (err)
10638 		return libbpf_err(err);
10639 
10640 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10641 }
10642 
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)10643 int bpf_map__update_elem(const struct bpf_map *map,
10644 			 const void *key, size_t key_sz,
10645 			 const void *value, size_t value_sz, __u64 flags)
10646 {
10647 	int err;
10648 
10649 	err = validate_map_op(map, key_sz, value_sz, true);
10650 	if (err)
10651 		return libbpf_err(err);
10652 
10653 	return bpf_map_update_elem(map->fd, key, value, flags);
10654 }
10655 
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)10656 int bpf_map__delete_elem(const struct bpf_map *map,
10657 			 const void *key, size_t key_sz, __u64 flags)
10658 {
10659 	int err;
10660 
10661 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10662 	if (err)
10663 		return libbpf_err(err);
10664 
10665 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10666 }
10667 
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)10668 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10669 				    const void *key, size_t key_sz,
10670 				    void *value, size_t value_sz, __u64 flags)
10671 {
10672 	int err;
10673 
10674 	err = validate_map_op(map, key_sz, value_sz, true);
10675 	if (err)
10676 		return libbpf_err(err);
10677 
10678 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10679 }
10680 
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)10681 int bpf_map__get_next_key(const struct bpf_map *map,
10682 			  const void *cur_key, void *next_key, size_t key_sz)
10683 {
10684 	int err;
10685 
10686 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10687 	if (err)
10688 		return libbpf_err(err);
10689 
10690 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10691 }
10692 
libbpf_get_error(const void * ptr)10693 long libbpf_get_error(const void *ptr)
10694 {
10695 	if (!IS_ERR_OR_NULL(ptr))
10696 		return 0;
10697 
10698 	if (IS_ERR(ptr))
10699 		errno = -PTR_ERR(ptr);
10700 
10701 	/* If ptr == NULL, then errno should be already set by the failing
10702 	 * API, because libbpf never returns NULL on success and it now always
10703 	 * sets errno on error. So no extra errno handling for ptr == NULL
10704 	 * case.
10705 	 */
10706 	return -errno;
10707 }
10708 
10709 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)10710 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10711 {
10712 	int ret;
10713 	int prog_fd = bpf_program__fd(prog);
10714 
10715 	if (prog_fd < 0) {
10716 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10717 			prog->name);
10718 		return libbpf_err(-EINVAL);
10719 	}
10720 
10721 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10722 	return libbpf_err_errno(ret);
10723 }
10724 
10725 /* Release "ownership" of underlying BPF resource (typically, BPF program
10726  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10727  * link, when destructed through bpf_link__destroy() call won't attempt to
10728  * detach/unregisted that BPF resource. This is useful in situations where,
10729  * say, attached BPF program has to outlive userspace program that attached it
10730  * in the system. Depending on type of BPF program, though, there might be
10731  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10732  * exit of userspace program doesn't trigger automatic detachment and clean up
10733  * inside the kernel.
10734  */
bpf_link__disconnect(struct bpf_link * link)10735 void bpf_link__disconnect(struct bpf_link *link)
10736 {
10737 	link->disconnected = true;
10738 }
10739 
bpf_link__destroy(struct bpf_link * link)10740 int bpf_link__destroy(struct bpf_link *link)
10741 {
10742 	int err = 0;
10743 
10744 	if (IS_ERR_OR_NULL(link))
10745 		return 0;
10746 
10747 	if (!link->disconnected && link->detach)
10748 		err = link->detach(link);
10749 	if (link->pin_path)
10750 		free(link->pin_path);
10751 	if (link->dealloc)
10752 		link->dealloc(link);
10753 	else
10754 		free(link);
10755 
10756 	return libbpf_err(err);
10757 }
10758 
bpf_link__fd(const struct bpf_link * link)10759 int bpf_link__fd(const struct bpf_link *link)
10760 {
10761 	return link->fd;
10762 }
10763 
bpf_link__pin_path(const struct bpf_link * link)10764 const char *bpf_link__pin_path(const struct bpf_link *link)
10765 {
10766 	return link->pin_path;
10767 }
10768 
bpf_link__detach_fd(struct bpf_link * link)10769 static int bpf_link__detach_fd(struct bpf_link *link)
10770 {
10771 	return libbpf_err_errno(close(link->fd));
10772 }
10773 
bpf_link__open(const char * path)10774 struct bpf_link *bpf_link__open(const char *path)
10775 {
10776 	struct bpf_link *link;
10777 	int fd;
10778 
10779 	fd = bpf_obj_get(path);
10780 	if (fd < 0) {
10781 		fd = -errno;
10782 		pr_warn("failed to open link at %s: %d\n", path, fd);
10783 		return libbpf_err_ptr(fd);
10784 	}
10785 
10786 	link = calloc(1, sizeof(*link));
10787 	if (!link) {
10788 		close(fd);
10789 		return libbpf_err_ptr(-ENOMEM);
10790 	}
10791 	link->detach = &bpf_link__detach_fd;
10792 	link->fd = fd;
10793 
10794 	link->pin_path = strdup(path);
10795 	if (!link->pin_path) {
10796 		bpf_link__destroy(link);
10797 		return libbpf_err_ptr(-ENOMEM);
10798 	}
10799 
10800 	return link;
10801 }
10802 
bpf_link__detach(struct bpf_link * link)10803 int bpf_link__detach(struct bpf_link *link)
10804 {
10805 	return bpf_link_detach(link->fd) ? -errno : 0;
10806 }
10807 
bpf_link__pin(struct bpf_link * link,const char * path)10808 int bpf_link__pin(struct bpf_link *link, const char *path)
10809 {
10810 	int err;
10811 
10812 	if (link->pin_path)
10813 		return libbpf_err(-EBUSY);
10814 	err = make_parent_dir(path);
10815 	if (err)
10816 		return libbpf_err(err);
10817 	err = check_path(path);
10818 	if (err)
10819 		return libbpf_err(err);
10820 
10821 	link->pin_path = strdup(path);
10822 	if (!link->pin_path)
10823 		return libbpf_err(-ENOMEM);
10824 
10825 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10826 		err = -errno;
10827 		zfree(&link->pin_path);
10828 		return libbpf_err(err);
10829 	}
10830 
10831 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10832 	return 0;
10833 }
10834 
bpf_link__unpin(struct bpf_link * link)10835 int bpf_link__unpin(struct bpf_link *link)
10836 {
10837 	int err;
10838 
10839 	if (!link->pin_path)
10840 		return libbpf_err(-EINVAL);
10841 
10842 	err = unlink(link->pin_path);
10843 	if (err != 0)
10844 		return -errno;
10845 
10846 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10847 	zfree(&link->pin_path);
10848 	return 0;
10849 }
10850 
10851 struct bpf_link_perf {
10852 	struct bpf_link link;
10853 	int perf_event_fd;
10854 	/* legacy kprobe support: keep track of probe identifier and type */
10855 	char *legacy_probe_name;
10856 	bool legacy_is_kprobe;
10857 	bool legacy_is_retprobe;
10858 };
10859 
10860 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10861 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10862 
bpf_link_perf_detach(struct bpf_link * link)10863 static int bpf_link_perf_detach(struct bpf_link *link)
10864 {
10865 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10866 	int err = 0;
10867 
10868 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10869 		err = -errno;
10870 
10871 	if (perf_link->perf_event_fd != link->fd)
10872 		close(perf_link->perf_event_fd);
10873 	close(link->fd);
10874 
10875 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10876 	if (perf_link->legacy_probe_name) {
10877 		if (perf_link->legacy_is_kprobe) {
10878 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10879 							 perf_link->legacy_is_retprobe);
10880 		} else {
10881 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10882 							 perf_link->legacy_is_retprobe);
10883 		}
10884 	}
10885 
10886 	return err;
10887 }
10888 
bpf_link_perf_dealloc(struct bpf_link * link)10889 static void bpf_link_perf_dealloc(struct bpf_link *link)
10890 {
10891 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10892 
10893 	free(perf_link->legacy_probe_name);
10894 	free(perf_link);
10895 }
10896 
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10897 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10898 						     const struct bpf_perf_event_opts *opts)
10899 {
10900 	struct bpf_link_perf *link;
10901 	int prog_fd, link_fd = -1, err;
10902 	bool force_ioctl_attach;
10903 
10904 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10905 		return libbpf_err_ptr(-EINVAL);
10906 
10907 	if (pfd < 0) {
10908 		pr_warn("prog '%s': invalid perf event FD %d\n",
10909 			prog->name, pfd);
10910 		return libbpf_err_ptr(-EINVAL);
10911 	}
10912 	prog_fd = bpf_program__fd(prog);
10913 	if (prog_fd < 0) {
10914 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10915 			prog->name);
10916 		return libbpf_err_ptr(-EINVAL);
10917 	}
10918 
10919 	link = calloc(1, sizeof(*link));
10920 	if (!link)
10921 		return libbpf_err_ptr(-ENOMEM);
10922 	link->link.detach = &bpf_link_perf_detach;
10923 	link->link.dealloc = &bpf_link_perf_dealloc;
10924 	link->perf_event_fd = pfd;
10925 
10926 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10927 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10928 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10929 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10930 
10931 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10932 		if (link_fd < 0) {
10933 			err = -errno;
10934 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
10935 				prog->name, pfd, errstr(err));
10936 			goto err_out;
10937 		}
10938 		link->link.fd = link_fd;
10939 	} else {
10940 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10941 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10942 			err = -EOPNOTSUPP;
10943 			goto err_out;
10944 		}
10945 
10946 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10947 			err = -errno;
10948 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10949 				prog->name, pfd, errstr(err));
10950 			if (err == -EPROTO)
10951 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10952 					prog->name, pfd);
10953 			goto err_out;
10954 		}
10955 		link->link.fd = pfd;
10956 	}
10957 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10958 		err = -errno;
10959 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10960 			prog->name, pfd, errstr(err));
10961 		goto err_out;
10962 	}
10963 
10964 	return &link->link;
10965 err_out:
10966 	if (link_fd >= 0)
10967 		close(link_fd);
10968 	free(link);
10969 	return libbpf_err_ptr(err);
10970 }
10971 
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10972 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10973 {
10974 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10975 }
10976 
10977 /*
10978  * this function is expected to parse integer in the range of [0, 2^31-1] from
10979  * given file using scanf format string fmt. If actual parsed value is
10980  * negative, the result might be indistinguishable from error
10981  */
parse_uint_from_file(const char * file,const char * fmt)10982 static int parse_uint_from_file(const char *file, const char *fmt)
10983 {
10984 	int err, ret;
10985 	FILE *f;
10986 
10987 	f = fopen(file, "re");
10988 	if (!f) {
10989 		err = -errno;
10990 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
10991 		return err;
10992 	}
10993 	err = fscanf(f, fmt, &ret);
10994 	if (err != 1) {
10995 		err = err == EOF ? -EIO : -errno;
10996 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
10997 		fclose(f);
10998 		return err;
10999 	}
11000 	fclose(f);
11001 	return ret;
11002 }
11003 
determine_kprobe_perf_type(void)11004 static int determine_kprobe_perf_type(void)
11005 {
11006 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11007 
11008 	return parse_uint_from_file(file, "%d\n");
11009 }
11010 
determine_uprobe_perf_type(void)11011 static int determine_uprobe_perf_type(void)
11012 {
11013 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11014 
11015 	return parse_uint_from_file(file, "%d\n");
11016 }
11017 
determine_kprobe_retprobe_bit(void)11018 static int determine_kprobe_retprobe_bit(void)
11019 {
11020 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11021 
11022 	return parse_uint_from_file(file, "config:%d\n");
11023 }
11024 
determine_uprobe_retprobe_bit(void)11025 static int determine_uprobe_retprobe_bit(void)
11026 {
11027 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11028 
11029 	return parse_uint_from_file(file, "config:%d\n");
11030 }
11031 
11032 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11033 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11034 
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)11035 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11036 				 uint64_t offset, int pid, size_t ref_ctr_off)
11037 {
11038 	const size_t attr_sz = sizeof(struct perf_event_attr);
11039 	struct perf_event_attr attr;
11040 	int type, pfd;
11041 
11042 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11043 		return -EINVAL;
11044 
11045 	memset(&attr, 0, attr_sz);
11046 
11047 	type = uprobe ? determine_uprobe_perf_type()
11048 		      : determine_kprobe_perf_type();
11049 	if (type < 0) {
11050 		pr_warn("failed to determine %s perf type: %s\n",
11051 			uprobe ? "uprobe" : "kprobe",
11052 			errstr(type));
11053 		return type;
11054 	}
11055 	if (retprobe) {
11056 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11057 				 : determine_kprobe_retprobe_bit();
11058 
11059 		if (bit < 0) {
11060 			pr_warn("failed to determine %s retprobe bit: %s\n",
11061 				uprobe ? "uprobe" : "kprobe",
11062 				errstr(bit));
11063 			return bit;
11064 		}
11065 		attr.config |= 1 << bit;
11066 	}
11067 	attr.size = attr_sz;
11068 	attr.type = type;
11069 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11070 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11071 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11072 
11073 	/* pid filter is meaningful only for uprobes */
11074 	pfd = syscall(__NR_perf_event_open, &attr,
11075 		      pid < 0 ? -1 : pid /* pid */,
11076 		      pid == -1 ? 0 : -1 /* cpu */,
11077 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11078 	return pfd >= 0 ? pfd : -errno;
11079 }
11080 
append_to_file(const char * file,const char * fmt,...)11081 static int append_to_file(const char *file, const char *fmt, ...)
11082 {
11083 	int fd, n, err = 0;
11084 	va_list ap;
11085 	char buf[1024];
11086 
11087 	va_start(ap, fmt);
11088 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11089 	va_end(ap);
11090 
11091 	if (n < 0 || n >= sizeof(buf))
11092 		return -EINVAL;
11093 
11094 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11095 	if (fd < 0)
11096 		return -errno;
11097 
11098 	if (write(fd, buf, n) < 0)
11099 		err = -errno;
11100 
11101 	close(fd);
11102 	return err;
11103 }
11104 
11105 #define DEBUGFS "/sys/kernel/debug/tracing"
11106 #define TRACEFS "/sys/kernel/tracing"
11107 
use_debugfs(void)11108 static bool use_debugfs(void)
11109 {
11110 	static int has_debugfs = -1;
11111 
11112 	if (has_debugfs < 0)
11113 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11114 
11115 	return has_debugfs == 1;
11116 }
11117 
tracefs_path(void)11118 static const char *tracefs_path(void)
11119 {
11120 	return use_debugfs() ? DEBUGFS : TRACEFS;
11121 }
11122 
tracefs_kprobe_events(void)11123 static const char *tracefs_kprobe_events(void)
11124 {
11125 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11126 }
11127 
tracefs_uprobe_events(void)11128 static const char *tracefs_uprobe_events(void)
11129 {
11130 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11131 }
11132 
tracefs_available_filter_functions(void)11133 static const char *tracefs_available_filter_functions(void)
11134 {
11135 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11136 			     : TRACEFS"/available_filter_functions";
11137 }
11138 
tracefs_available_filter_functions_addrs(void)11139 static const char *tracefs_available_filter_functions_addrs(void)
11140 {
11141 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11142 			     : TRACEFS"/available_filter_functions_addrs";
11143 }
11144 
gen_probe_legacy_event_name(char * buf,size_t buf_sz,const char * name,size_t offset)11145 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11146 					const char *name, size_t offset)
11147 {
11148 	static int index = 0;
11149 	int i;
11150 
11151 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11152 		 __sync_fetch_and_add(&index, 1), name, offset);
11153 
11154 	/* sanitize name in the probe name */
11155 	for (i = 0; buf[i]; i++) {
11156 		if (!isalnum(buf[i]))
11157 			buf[i] = '_';
11158 	}
11159 }
11160 
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)11161 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11162 				   const char *kfunc_name, size_t offset)
11163 {
11164 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11165 			      retprobe ? 'r' : 'p',
11166 			      retprobe ? "kretprobes" : "kprobes",
11167 			      probe_name, kfunc_name, offset);
11168 }
11169 
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)11170 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11171 {
11172 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11173 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11174 }
11175 
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)11176 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11177 {
11178 	char file[256];
11179 
11180 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11181 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11182 
11183 	return parse_uint_from_file(file, "%d\n");
11184 }
11185 
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)11186 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11187 					 const char *kfunc_name, size_t offset, int pid)
11188 {
11189 	const size_t attr_sz = sizeof(struct perf_event_attr);
11190 	struct perf_event_attr attr;
11191 	int type, pfd, err;
11192 
11193 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11194 	if (err < 0) {
11195 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11196 			kfunc_name, offset,
11197 			errstr(err));
11198 		return err;
11199 	}
11200 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11201 	if (type < 0) {
11202 		err = type;
11203 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11204 			kfunc_name, offset,
11205 			errstr(err));
11206 		goto err_clean_legacy;
11207 	}
11208 
11209 	memset(&attr, 0, attr_sz);
11210 	attr.size = attr_sz;
11211 	attr.config = type;
11212 	attr.type = PERF_TYPE_TRACEPOINT;
11213 
11214 	pfd = syscall(__NR_perf_event_open, &attr,
11215 		      pid < 0 ? -1 : pid, /* pid */
11216 		      pid == -1 ? 0 : -1, /* cpu */
11217 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11218 	if (pfd < 0) {
11219 		err = -errno;
11220 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11221 			errstr(err));
11222 		goto err_clean_legacy;
11223 	}
11224 	return pfd;
11225 
11226 err_clean_legacy:
11227 	/* Clear the newly added legacy kprobe_event */
11228 	remove_kprobe_event_legacy(probe_name, retprobe);
11229 	return err;
11230 }
11231 
arch_specific_syscall_pfx(void)11232 static const char *arch_specific_syscall_pfx(void)
11233 {
11234 #if defined(__x86_64__)
11235 	return "x64";
11236 #elif defined(__i386__)
11237 	return "ia32";
11238 #elif defined(__s390x__)
11239 	return "s390x";
11240 #elif defined(__s390__)
11241 	return "s390";
11242 #elif defined(__arm__)
11243 	return "arm";
11244 #elif defined(__aarch64__)
11245 	return "arm64";
11246 #elif defined(__mips__)
11247 	return "mips";
11248 #elif defined(__riscv)
11249 	return "riscv";
11250 #elif defined(__powerpc__)
11251 	return "powerpc";
11252 #elif defined(__powerpc64__)
11253 	return "powerpc64";
11254 #else
11255 	return NULL;
11256 #endif
11257 }
11258 
probe_kern_syscall_wrapper(int token_fd)11259 int probe_kern_syscall_wrapper(int token_fd)
11260 {
11261 	char syscall_name[64];
11262 	const char *ksys_pfx;
11263 
11264 	ksys_pfx = arch_specific_syscall_pfx();
11265 	if (!ksys_pfx)
11266 		return 0;
11267 
11268 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11269 
11270 	if (determine_kprobe_perf_type() >= 0) {
11271 		int pfd;
11272 
11273 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11274 		if (pfd >= 0)
11275 			close(pfd);
11276 
11277 		return pfd >= 0 ? 1 : 0;
11278 	} else { /* legacy mode */
11279 		char probe_name[MAX_EVENT_NAME_LEN];
11280 
11281 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11282 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11283 			return 0;
11284 
11285 		(void)remove_kprobe_event_legacy(probe_name, false);
11286 		return 1;
11287 	}
11288 }
11289 
11290 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)11291 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11292 				const char *func_name,
11293 				const struct bpf_kprobe_opts *opts)
11294 {
11295 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11296 	enum probe_attach_mode attach_mode;
11297 	char *legacy_probe = NULL;
11298 	struct bpf_link *link;
11299 	size_t offset;
11300 	bool retprobe, legacy;
11301 	int pfd, err;
11302 
11303 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11304 		return libbpf_err_ptr(-EINVAL);
11305 
11306 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11307 	retprobe = OPTS_GET(opts, retprobe, false);
11308 	offset = OPTS_GET(opts, offset, 0);
11309 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11310 
11311 	legacy = determine_kprobe_perf_type() < 0;
11312 	switch (attach_mode) {
11313 	case PROBE_ATTACH_MODE_LEGACY:
11314 		legacy = true;
11315 		pe_opts.force_ioctl_attach = true;
11316 		break;
11317 	case PROBE_ATTACH_MODE_PERF:
11318 		if (legacy)
11319 			return libbpf_err_ptr(-ENOTSUP);
11320 		pe_opts.force_ioctl_attach = true;
11321 		break;
11322 	case PROBE_ATTACH_MODE_LINK:
11323 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11324 			return libbpf_err_ptr(-ENOTSUP);
11325 		break;
11326 	case PROBE_ATTACH_MODE_DEFAULT:
11327 		break;
11328 	default:
11329 		return libbpf_err_ptr(-EINVAL);
11330 	}
11331 
11332 	if (!legacy) {
11333 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11334 					    func_name, offset,
11335 					    -1 /* pid */, 0 /* ref_ctr_off */);
11336 	} else {
11337 		char probe_name[MAX_EVENT_NAME_LEN];
11338 
11339 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11340 					    func_name, offset);
11341 
11342 		legacy_probe = strdup(probe_name);
11343 		if (!legacy_probe)
11344 			return libbpf_err_ptr(-ENOMEM);
11345 
11346 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11347 						    offset, -1 /* pid */);
11348 	}
11349 	if (pfd < 0) {
11350 		err = -errno;
11351 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11352 			prog->name, retprobe ? "kretprobe" : "kprobe",
11353 			func_name, offset,
11354 			errstr(err));
11355 		goto err_out;
11356 	}
11357 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11358 	err = libbpf_get_error(link);
11359 	if (err) {
11360 		close(pfd);
11361 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11362 			prog->name, retprobe ? "kretprobe" : "kprobe",
11363 			func_name, offset,
11364 			errstr(err));
11365 		goto err_clean_legacy;
11366 	}
11367 	if (legacy) {
11368 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11369 
11370 		perf_link->legacy_probe_name = legacy_probe;
11371 		perf_link->legacy_is_kprobe = true;
11372 		perf_link->legacy_is_retprobe = retprobe;
11373 	}
11374 
11375 	return link;
11376 
11377 err_clean_legacy:
11378 	if (legacy)
11379 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11380 err_out:
11381 	free(legacy_probe);
11382 	return libbpf_err_ptr(err);
11383 }
11384 
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)11385 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11386 					    bool retprobe,
11387 					    const char *func_name)
11388 {
11389 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11390 		.retprobe = retprobe,
11391 	);
11392 
11393 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11394 }
11395 
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)11396 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11397 					      const char *syscall_name,
11398 					      const struct bpf_ksyscall_opts *opts)
11399 {
11400 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11401 	char func_name[128];
11402 
11403 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11404 		return libbpf_err_ptr(-EINVAL);
11405 
11406 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11407 		/* arch_specific_syscall_pfx() should never return NULL here
11408 		 * because it is guarded by kernel_supports(). However, since
11409 		 * compiler does not know that we have an explicit conditional
11410 		 * as well.
11411 		 */
11412 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11413 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11414 	} else {
11415 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11416 	}
11417 
11418 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11419 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11420 
11421 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11422 }
11423 
11424 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)11425 bool glob_match(const char *str, const char *pat)
11426 {
11427 	while (*str && *pat && *pat != '*') {
11428 		if (*pat == '?') {      /* Matches any single character */
11429 			str++;
11430 			pat++;
11431 			continue;
11432 		}
11433 		if (*str != *pat)
11434 			return false;
11435 		str++;
11436 		pat++;
11437 	}
11438 	/* Check wild card */
11439 	if (*pat == '*') {
11440 		while (*pat == '*')
11441 			pat++;
11442 		if (!*pat) /* Tail wild card matches all */
11443 			return true;
11444 		while (*str)
11445 			if (glob_match(str++, pat))
11446 				return true;
11447 	}
11448 	return !*str && !*pat;
11449 }
11450 
11451 struct kprobe_multi_resolve {
11452 	const char *pattern;
11453 	unsigned long *addrs;
11454 	size_t cap;
11455 	size_t cnt;
11456 };
11457 
11458 struct avail_kallsyms_data {
11459 	char **syms;
11460 	size_t cnt;
11461 	struct kprobe_multi_resolve *res;
11462 };
11463 
avail_func_cmp(const void * a,const void * b)11464 static int avail_func_cmp(const void *a, const void *b)
11465 {
11466 	return strcmp(*(const char **)a, *(const char **)b);
11467 }
11468 
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)11469 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11470 			     const char *sym_name, void *ctx)
11471 {
11472 	struct avail_kallsyms_data *data = ctx;
11473 	struct kprobe_multi_resolve *res = data->res;
11474 	int err;
11475 
11476 	if (!glob_match(sym_name, res->pattern))
11477 		return 0;
11478 
11479 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11480 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11481 		 * function names reported in available_filter_functions, but
11482 		 * don't do so for kallsyms. While this is clearly a kernel
11483 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11484 		 * make multi-kprobe usability a bit better: if no match is
11485 		 * found, we will strip .llvm. suffix and try one more time.
11486 		 *
11487 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11488 		 */
11489 		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11490 
11491 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11492 			return 0;
11493 
11494 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11495 		 * coercion differences and get proper `const char **` pointer
11496 		 * which avail_func_cmp() expects
11497 		 */
11498 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11499 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11500 			return 0;
11501 	}
11502 
11503 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11504 	if (err)
11505 		return err;
11506 
11507 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11508 	return 0;
11509 }
11510 
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)11511 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11512 {
11513 	const char *available_functions_file = tracefs_available_filter_functions();
11514 	struct avail_kallsyms_data data;
11515 	char sym_name[500];
11516 	FILE *f;
11517 	int err = 0, ret, i;
11518 	char **syms = NULL;
11519 	size_t cap = 0, cnt = 0;
11520 
11521 	f = fopen(available_functions_file, "re");
11522 	if (!f) {
11523 		err = -errno;
11524 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11525 		return err;
11526 	}
11527 
11528 	while (true) {
11529 		char *name;
11530 
11531 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11532 		if (ret == EOF && feof(f))
11533 			break;
11534 
11535 		if (ret != 1) {
11536 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11537 			err = -EINVAL;
11538 			goto cleanup;
11539 		}
11540 
11541 		if (!glob_match(sym_name, res->pattern))
11542 			continue;
11543 
11544 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11545 		if (err)
11546 			goto cleanup;
11547 
11548 		name = strdup(sym_name);
11549 		if (!name) {
11550 			err = -errno;
11551 			goto cleanup;
11552 		}
11553 
11554 		syms[cnt++] = name;
11555 	}
11556 
11557 	/* no entries found, bail out */
11558 	if (cnt == 0) {
11559 		err = -ENOENT;
11560 		goto cleanup;
11561 	}
11562 
11563 	/* sort available functions */
11564 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11565 
11566 	data.syms = syms;
11567 	data.res = res;
11568 	data.cnt = cnt;
11569 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11570 
11571 	if (res->cnt == 0)
11572 		err = -ENOENT;
11573 
11574 cleanup:
11575 	for (i = 0; i < cnt; i++)
11576 		free((char *)syms[i]);
11577 	free(syms);
11578 
11579 	fclose(f);
11580 	return err;
11581 }
11582 
has_available_filter_functions_addrs(void)11583 static bool has_available_filter_functions_addrs(void)
11584 {
11585 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11586 }
11587 
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)11588 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11589 {
11590 	const char *available_path = tracefs_available_filter_functions_addrs();
11591 	char sym_name[500];
11592 	FILE *f;
11593 	int ret, err = 0;
11594 	unsigned long long sym_addr;
11595 
11596 	f = fopen(available_path, "re");
11597 	if (!f) {
11598 		err = -errno;
11599 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11600 		return err;
11601 	}
11602 
11603 	while (true) {
11604 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11605 		if (ret == EOF && feof(f))
11606 			break;
11607 
11608 		if (ret != 2) {
11609 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11610 				ret);
11611 			err = -EINVAL;
11612 			goto cleanup;
11613 		}
11614 
11615 		if (!glob_match(sym_name, res->pattern))
11616 			continue;
11617 
11618 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11619 					sizeof(*res->addrs), res->cnt + 1);
11620 		if (err)
11621 			goto cleanup;
11622 
11623 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11624 	}
11625 
11626 	if (res->cnt == 0)
11627 		err = -ENOENT;
11628 
11629 cleanup:
11630 	fclose(f);
11631 	return err;
11632 }
11633 
11634 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)11635 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11636 				      const char *pattern,
11637 				      const struct bpf_kprobe_multi_opts *opts)
11638 {
11639 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11640 	struct kprobe_multi_resolve res = {
11641 		.pattern = pattern,
11642 	};
11643 	enum bpf_attach_type attach_type;
11644 	struct bpf_link *link = NULL;
11645 	const unsigned long *addrs;
11646 	int err, link_fd, prog_fd;
11647 	bool retprobe, session, unique_match;
11648 	const __u64 *cookies;
11649 	const char **syms;
11650 	size_t cnt;
11651 
11652 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11653 		return libbpf_err_ptr(-EINVAL);
11654 
11655 	prog_fd = bpf_program__fd(prog);
11656 	if (prog_fd < 0) {
11657 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11658 			prog->name);
11659 		return libbpf_err_ptr(-EINVAL);
11660 	}
11661 
11662 	syms    = OPTS_GET(opts, syms, false);
11663 	addrs   = OPTS_GET(opts, addrs, false);
11664 	cnt     = OPTS_GET(opts, cnt, false);
11665 	cookies = OPTS_GET(opts, cookies, false);
11666 	unique_match = OPTS_GET(opts, unique_match, false);
11667 
11668 	if (!pattern && !addrs && !syms)
11669 		return libbpf_err_ptr(-EINVAL);
11670 	if (pattern && (addrs || syms || cookies || cnt))
11671 		return libbpf_err_ptr(-EINVAL);
11672 	if (!pattern && !cnt)
11673 		return libbpf_err_ptr(-EINVAL);
11674 	if (!pattern && unique_match)
11675 		return libbpf_err_ptr(-EINVAL);
11676 	if (addrs && syms)
11677 		return libbpf_err_ptr(-EINVAL);
11678 
11679 	if (pattern) {
11680 		if (has_available_filter_functions_addrs())
11681 			err = libbpf_available_kprobes_parse(&res);
11682 		else
11683 			err = libbpf_available_kallsyms_parse(&res);
11684 		if (err)
11685 			goto error;
11686 
11687 		if (unique_match && res.cnt != 1) {
11688 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11689 				prog->name, pattern, res.cnt);
11690 			err = -EINVAL;
11691 			goto error;
11692 		}
11693 
11694 		addrs = res.addrs;
11695 		cnt = res.cnt;
11696 	}
11697 
11698 	retprobe = OPTS_GET(opts, retprobe, false);
11699 	session  = OPTS_GET(opts, session, false);
11700 
11701 	if (retprobe && session)
11702 		return libbpf_err_ptr(-EINVAL);
11703 
11704 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11705 
11706 	lopts.kprobe_multi.syms = syms;
11707 	lopts.kprobe_multi.addrs = addrs;
11708 	lopts.kprobe_multi.cookies = cookies;
11709 	lopts.kprobe_multi.cnt = cnt;
11710 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11711 
11712 	link = calloc(1, sizeof(*link));
11713 	if (!link) {
11714 		err = -ENOMEM;
11715 		goto error;
11716 	}
11717 	link->detach = &bpf_link__detach_fd;
11718 
11719 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11720 	if (link_fd < 0) {
11721 		err = -errno;
11722 		pr_warn("prog '%s': failed to attach: %s\n",
11723 			prog->name, errstr(err));
11724 		goto error;
11725 	}
11726 	link->fd = link_fd;
11727 	free(res.addrs);
11728 	return link;
11729 
11730 error:
11731 	free(link);
11732 	free(res.addrs);
11733 	return libbpf_err_ptr(err);
11734 }
11735 
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11736 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11737 {
11738 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11739 	unsigned long offset = 0;
11740 	const char *func_name;
11741 	char *func;
11742 	int n;
11743 
11744 	*link = NULL;
11745 
11746 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11747 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11748 		return 0;
11749 
11750 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11751 	if (opts.retprobe)
11752 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11753 	else
11754 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11755 
11756 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11757 	if (n < 1) {
11758 		pr_warn("kprobe name is invalid: %s\n", func_name);
11759 		return -EINVAL;
11760 	}
11761 	if (opts.retprobe && offset != 0) {
11762 		free(func);
11763 		pr_warn("kretprobes do not support offset specification\n");
11764 		return -EINVAL;
11765 	}
11766 
11767 	opts.offset = offset;
11768 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11769 	free(func);
11770 	return libbpf_get_error(*link);
11771 }
11772 
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11773 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11774 {
11775 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11776 	const char *syscall_name;
11777 
11778 	*link = NULL;
11779 
11780 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11781 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11782 		return 0;
11783 
11784 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11785 	if (opts.retprobe)
11786 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11787 	else
11788 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11789 
11790 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11791 	return *link ? 0 : -errno;
11792 }
11793 
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11794 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11795 {
11796 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11797 	const char *spec;
11798 	char *pattern;
11799 	int n;
11800 
11801 	*link = NULL;
11802 
11803 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11804 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11805 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11806 		return 0;
11807 
11808 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11809 	if (opts.retprobe)
11810 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11811 	else
11812 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11813 
11814 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11815 	if (n < 1) {
11816 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11817 		return -EINVAL;
11818 	}
11819 
11820 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11821 	free(pattern);
11822 	return libbpf_get_error(*link);
11823 }
11824 
attach_kprobe_session(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11825 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11826 				 struct bpf_link **link)
11827 {
11828 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11829 	const char *spec;
11830 	char *pattern;
11831 	int n;
11832 
11833 	*link = NULL;
11834 
11835 	/* no auto-attach for SEC("kprobe.session") */
11836 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11837 		return 0;
11838 
11839 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11840 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11841 	if (n < 1) {
11842 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11843 		return -EINVAL;
11844 	}
11845 
11846 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11847 	free(pattern);
11848 	return *link ? 0 : -errno;
11849 }
11850 
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11851 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11852 {
11853 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11854 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11855 	int n, ret = -EINVAL;
11856 
11857 	*link = NULL;
11858 
11859 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11860 		   &probe_type, &binary_path, &func_name);
11861 	switch (n) {
11862 	case 1:
11863 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11864 		ret = 0;
11865 		break;
11866 	case 3:
11867 		opts.session = str_has_pfx(probe_type, "uprobe.session");
11868 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11869 
11870 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11871 		ret = libbpf_get_error(*link);
11872 		break;
11873 	default:
11874 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11875 			prog->sec_name);
11876 		break;
11877 	}
11878 	free(probe_type);
11879 	free(binary_path);
11880 	free(func_name);
11881 	return ret;
11882 }
11883 
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)11884 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11885 					  const char *binary_path, size_t offset)
11886 {
11887 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11888 			      retprobe ? 'r' : 'p',
11889 			      retprobe ? "uretprobes" : "uprobes",
11890 			      probe_name, binary_path, offset);
11891 }
11892 
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)11893 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11894 {
11895 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11896 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11897 }
11898 
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)11899 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11900 {
11901 	char file[512];
11902 
11903 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11904 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11905 
11906 	return parse_uint_from_file(file, "%d\n");
11907 }
11908 
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)11909 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11910 					 const char *binary_path, size_t offset, int pid)
11911 {
11912 	const size_t attr_sz = sizeof(struct perf_event_attr);
11913 	struct perf_event_attr attr;
11914 	int type, pfd, err;
11915 
11916 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11917 	if (err < 0) {
11918 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
11919 			binary_path, (size_t)offset, errstr(err));
11920 		return err;
11921 	}
11922 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11923 	if (type < 0) {
11924 		err = type;
11925 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
11926 			binary_path, offset, errstr(err));
11927 		goto err_clean_legacy;
11928 	}
11929 
11930 	memset(&attr, 0, attr_sz);
11931 	attr.size = attr_sz;
11932 	attr.config = type;
11933 	attr.type = PERF_TYPE_TRACEPOINT;
11934 
11935 	pfd = syscall(__NR_perf_event_open, &attr,
11936 		      pid < 0 ? -1 : pid, /* pid */
11937 		      pid == -1 ? 0 : -1, /* cpu */
11938 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11939 	if (pfd < 0) {
11940 		err = -errno;
11941 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
11942 		goto err_clean_legacy;
11943 	}
11944 	return pfd;
11945 
11946 err_clean_legacy:
11947 	/* Clear the newly added legacy uprobe_event */
11948 	remove_uprobe_event_legacy(probe_name, retprobe);
11949 	return err;
11950 }
11951 
11952 /* Find offset of function name in archive specified by path. Currently
11953  * supported are .zip files that do not compress their contents, as used on
11954  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11955  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11956  * library functions.
11957  *
11958  * An overview of the APK format specifically provided here:
11959  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11960  */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)11961 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11962 					      const char *func_name)
11963 {
11964 	struct zip_archive *archive;
11965 	struct zip_entry entry;
11966 	long ret;
11967 	Elf *elf;
11968 
11969 	archive = zip_archive_open(archive_path);
11970 	if (IS_ERR(archive)) {
11971 		ret = PTR_ERR(archive);
11972 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11973 		return ret;
11974 	}
11975 
11976 	ret = zip_archive_find_entry(archive, file_name, &entry);
11977 	if (ret) {
11978 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11979 			archive_path, ret);
11980 		goto out;
11981 	}
11982 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11983 		 (unsigned long)entry.data_offset);
11984 
11985 	if (entry.compression) {
11986 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11987 			archive_path);
11988 		ret = -LIBBPF_ERRNO__FORMAT;
11989 		goto out;
11990 	}
11991 
11992 	elf = elf_memory((void *)entry.data, entry.data_length);
11993 	if (!elf) {
11994 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11995 			elf_errmsg(-1));
11996 		ret = -LIBBPF_ERRNO__LIBELF;
11997 		goto out;
11998 	}
11999 
12000 	ret = elf_find_func_offset(elf, file_name, func_name);
12001 	if (ret > 0) {
12002 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12003 			 func_name, file_name, archive_path, entry.data_offset, ret,
12004 			 ret + entry.data_offset);
12005 		ret += entry.data_offset;
12006 	}
12007 	elf_end(elf);
12008 
12009 out:
12010 	zip_archive_close(archive);
12011 	return ret;
12012 }
12013 
arch_specific_lib_paths(void)12014 static const char *arch_specific_lib_paths(void)
12015 {
12016 	/*
12017 	 * Based on https://packages.debian.org/sid/libc6.
12018 	 *
12019 	 * Assume that the traced program is built for the same architecture
12020 	 * as libbpf, which should cover the vast majority of cases.
12021 	 */
12022 #if defined(__x86_64__)
12023 	return "/lib/x86_64-linux-gnu";
12024 #elif defined(__i386__)
12025 	return "/lib/i386-linux-gnu";
12026 #elif defined(__s390x__)
12027 	return "/lib/s390x-linux-gnu";
12028 #elif defined(__s390__)
12029 	return "/lib/s390-linux-gnu";
12030 #elif defined(__arm__) && defined(__SOFTFP__)
12031 	return "/lib/arm-linux-gnueabi";
12032 #elif defined(__arm__) && !defined(__SOFTFP__)
12033 	return "/lib/arm-linux-gnueabihf";
12034 #elif defined(__aarch64__)
12035 	return "/lib/aarch64-linux-gnu";
12036 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12037 	return "/lib/mips64el-linux-gnuabi64";
12038 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12039 	return "/lib/mipsel-linux-gnu";
12040 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12041 	return "/lib/powerpc64le-linux-gnu";
12042 #elif defined(__sparc__) && defined(__arch64__)
12043 	return "/lib/sparc64-linux-gnu";
12044 #elif defined(__riscv) && __riscv_xlen == 64
12045 	return "/lib/riscv64-linux-gnu";
12046 #else
12047 	return NULL;
12048 #endif
12049 }
12050 
12051 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)12052 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12053 {
12054 	const char *search_paths[3] = {};
12055 	int i, perm;
12056 
12057 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12058 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12059 		search_paths[1] = "/usr/lib64:/usr/lib";
12060 		search_paths[2] = arch_specific_lib_paths();
12061 		perm = R_OK;
12062 	} else {
12063 		search_paths[0] = getenv("PATH");
12064 		search_paths[1] = "/usr/bin:/usr/sbin";
12065 		perm = R_OK | X_OK;
12066 	}
12067 
12068 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12069 		const char *s;
12070 
12071 		if (!search_paths[i])
12072 			continue;
12073 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12074 			char *next_path;
12075 			int seg_len;
12076 
12077 			if (s[0] == ':')
12078 				s++;
12079 			next_path = strchr(s, ':');
12080 			seg_len = next_path ? next_path - s : strlen(s);
12081 			if (!seg_len)
12082 				continue;
12083 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12084 			/* ensure it has required permissions */
12085 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12086 				continue;
12087 			pr_debug("resolved '%s' to '%s'\n", file, result);
12088 			return 0;
12089 		}
12090 	}
12091 	return -ENOENT;
12092 }
12093 
12094 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)12095 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12096 				 pid_t pid,
12097 				 const char *path,
12098 				 const char *func_pattern,
12099 				 const struct bpf_uprobe_multi_opts *opts)
12100 {
12101 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12102 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12103 	unsigned long *resolved_offsets = NULL;
12104 	enum bpf_attach_type attach_type;
12105 	int err = 0, link_fd, prog_fd;
12106 	struct bpf_link *link = NULL;
12107 	char full_path[PATH_MAX];
12108 	bool retprobe, session;
12109 	const __u64 *cookies;
12110 	const char **syms;
12111 	size_t cnt;
12112 
12113 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12114 		return libbpf_err_ptr(-EINVAL);
12115 
12116 	prog_fd = bpf_program__fd(prog);
12117 	if (prog_fd < 0) {
12118 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12119 			prog->name);
12120 		return libbpf_err_ptr(-EINVAL);
12121 	}
12122 
12123 	syms = OPTS_GET(opts, syms, NULL);
12124 	offsets = OPTS_GET(opts, offsets, NULL);
12125 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12126 	cookies = OPTS_GET(opts, cookies, NULL);
12127 	cnt = OPTS_GET(opts, cnt, 0);
12128 	retprobe = OPTS_GET(opts, retprobe, false);
12129 	session  = OPTS_GET(opts, session, false);
12130 
12131 	/*
12132 	 * User can specify 2 mutually exclusive set of inputs:
12133 	 *
12134 	 * 1) use only path/func_pattern/pid arguments
12135 	 *
12136 	 * 2) use path/pid with allowed combinations of:
12137 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12138 	 *
12139 	 *    - syms and offsets are mutually exclusive
12140 	 *    - ref_ctr_offsets and cookies are optional
12141 	 *
12142 	 * Any other usage results in error.
12143 	 */
12144 
12145 	if (!path)
12146 		return libbpf_err_ptr(-EINVAL);
12147 	if (!func_pattern && cnt == 0)
12148 		return libbpf_err_ptr(-EINVAL);
12149 
12150 	if (func_pattern) {
12151 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12152 			return libbpf_err_ptr(-EINVAL);
12153 	} else {
12154 		if (!!syms == !!offsets)
12155 			return libbpf_err_ptr(-EINVAL);
12156 	}
12157 
12158 	if (retprobe && session)
12159 		return libbpf_err_ptr(-EINVAL);
12160 
12161 	if (func_pattern) {
12162 		if (!strchr(path, '/')) {
12163 			err = resolve_full_path(path, full_path, sizeof(full_path));
12164 			if (err) {
12165 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12166 					prog->name, path, errstr(err));
12167 				return libbpf_err_ptr(err);
12168 			}
12169 			path = full_path;
12170 		}
12171 
12172 		err = elf_resolve_pattern_offsets(path, func_pattern,
12173 						  &resolved_offsets, &cnt);
12174 		if (err < 0)
12175 			return libbpf_err_ptr(err);
12176 		offsets = resolved_offsets;
12177 	} else if (syms) {
12178 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12179 		if (err < 0)
12180 			return libbpf_err_ptr(err);
12181 		offsets = resolved_offsets;
12182 	}
12183 
12184 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12185 
12186 	lopts.uprobe_multi.path = path;
12187 	lopts.uprobe_multi.offsets = offsets;
12188 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12189 	lopts.uprobe_multi.cookies = cookies;
12190 	lopts.uprobe_multi.cnt = cnt;
12191 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12192 
12193 	if (pid == 0)
12194 		pid = getpid();
12195 	if (pid > 0)
12196 		lopts.uprobe_multi.pid = pid;
12197 
12198 	link = calloc(1, sizeof(*link));
12199 	if (!link) {
12200 		err = -ENOMEM;
12201 		goto error;
12202 	}
12203 	link->detach = &bpf_link__detach_fd;
12204 
12205 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12206 	if (link_fd < 0) {
12207 		err = -errno;
12208 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12209 			prog->name, errstr(err));
12210 		goto error;
12211 	}
12212 	link->fd = link_fd;
12213 	free(resolved_offsets);
12214 	return link;
12215 
12216 error:
12217 	free(resolved_offsets);
12218 	free(link);
12219 	return libbpf_err_ptr(err);
12220 }
12221 
12222 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)12223 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12224 				const char *binary_path, size_t func_offset,
12225 				const struct bpf_uprobe_opts *opts)
12226 {
12227 	const char *archive_path = NULL, *archive_sep = NULL;
12228 	char *legacy_probe = NULL;
12229 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12230 	enum probe_attach_mode attach_mode;
12231 	char full_path[PATH_MAX];
12232 	struct bpf_link *link;
12233 	size_t ref_ctr_off;
12234 	int pfd, err;
12235 	bool retprobe, legacy;
12236 	const char *func_name;
12237 
12238 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12239 		return libbpf_err_ptr(-EINVAL);
12240 
12241 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12242 	retprobe = OPTS_GET(opts, retprobe, false);
12243 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12244 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12245 
12246 	if (!binary_path)
12247 		return libbpf_err_ptr(-EINVAL);
12248 
12249 	/* Check if "binary_path" refers to an archive. */
12250 	archive_sep = strstr(binary_path, "!/");
12251 	if (archive_sep) {
12252 		full_path[0] = '\0';
12253 		libbpf_strlcpy(full_path, binary_path,
12254 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12255 		archive_path = full_path;
12256 		binary_path = archive_sep + 2;
12257 	} else if (!strchr(binary_path, '/')) {
12258 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12259 		if (err) {
12260 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12261 				prog->name, binary_path, errstr(err));
12262 			return libbpf_err_ptr(err);
12263 		}
12264 		binary_path = full_path;
12265 	}
12266 	func_name = OPTS_GET(opts, func_name, NULL);
12267 	if (func_name) {
12268 		long sym_off;
12269 
12270 		if (archive_path) {
12271 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12272 								    func_name);
12273 			binary_path = archive_path;
12274 		} else {
12275 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12276 		}
12277 		if (sym_off < 0)
12278 			return libbpf_err_ptr(sym_off);
12279 		func_offset += sym_off;
12280 	}
12281 
12282 	legacy = determine_uprobe_perf_type() < 0;
12283 	switch (attach_mode) {
12284 	case PROBE_ATTACH_MODE_LEGACY:
12285 		legacy = true;
12286 		pe_opts.force_ioctl_attach = true;
12287 		break;
12288 	case PROBE_ATTACH_MODE_PERF:
12289 		if (legacy)
12290 			return libbpf_err_ptr(-ENOTSUP);
12291 		pe_opts.force_ioctl_attach = true;
12292 		break;
12293 	case PROBE_ATTACH_MODE_LINK:
12294 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12295 			return libbpf_err_ptr(-ENOTSUP);
12296 		break;
12297 	case PROBE_ATTACH_MODE_DEFAULT:
12298 		break;
12299 	default:
12300 		return libbpf_err_ptr(-EINVAL);
12301 	}
12302 
12303 	if (!legacy) {
12304 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12305 					    func_offset, pid, ref_ctr_off);
12306 	} else {
12307 		char probe_name[MAX_EVENT_NAME_LEN];
12308 
12309 		if (ref_ctr_off)
12310 			return libbpf_err_ptr(-EINVAL);
12311 
12312 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12313 					    strrchr(binary_path, '/') ? : binary_path,
12314 					    func_offset);
12315 
12316 		legacy_probe = strdup(probe_name);
12317 		if (!legacy_probe)
12318 			return libbpf_err_ptr(-ENOMEM);
12319 
12320 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12321 						    binary_path, func_offset, pid);
12322 	}
12323 	if (pfd < 0) {
12324 		err = -errno;
12325 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12326 			prog->name, retprobe ? "uretprobe" : "uprobe",
12327 			binary_path, func_offset,
12328 			errstr(err));
12329 		goto err_out;
12330 	}
12331 
12332 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12333 	err = libbpf_get_error(link);
12334 	if (err) {
12335 		close(pfd);
12336 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12337 			prog->name, retprobe ? "uretprobe" : "uprobe",
12338 			binary_path, func_offset,
12339 			errstr(err));
12340 		goto err_clean_legacy;
12341 	}
12342 	if (legacy) {
12343 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12344 
12345 		perf_link->legacy_probe_name = legacy_probe;
12346 		perf_link->legacy_is_kprobe = false;
12347 		perf_link->legacy_is_retprobe = retprobe;
12348 	}
12349 	return link;
12350 
12351 err_clean_legacy:
12352 	if (legacy)
12353 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12354 err_out:
12355 	free(legacy_probe);
12356 	return libbpf_err_ptr(err);
12357 }
12358 
12359 /* Format of u[ret]probe section definition supporting auto-attach:
12360  * u[ret]probe/binary:function[+offset]
12361  *
12362  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12363  * full binary path via bpf_program__attach_uprobe_opts.
12364  *
12365  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12366  * specified (and auto-attach is not possible) or the above format is specified for
12367  * auto-attach.
12368  */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12369 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12370 {
12371 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12372 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12373 	int n, c, ret = -EINVAL;
12374 	long offset = 0;
12375 
12376 	*link = NULL;
12377 
12378 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12379 		   &probe_type, &binary_path, &func_name);
12380 	switch (n) {
12381 	case 1:
12382 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12383 		ret = 0;
12384 		break;
12385 	case 2:
12386 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12387 			prog->name, prog->sec_name);
12388 		break;
12389 	case 3:
12390 		/* check if user specifies `+offset`, if yes, this should be
12391 		 * the last part of the string, make sure sscanf read to EOL
12392 		 */
12393 		func_off = strrchr(func_name, '+');
12394 		if (func_off) {
12395 			n = sscanf(func_off, "+%li%n", &offset, &c);
12396 			if (n == 1 && *(func_off + c) == '\0')
12397 				func_off[0] = '\0';
12398 			else
12399 				offset = 0;
12400 		}
12401 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12402 				strcmp(probe_type, "uretprobe.s") == 0;
12403 		if (opts.retprobe && offset != 0) {
12404 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12405 				prog->name);
12406 			break;
12407 		}
12408 		opts.func_name = func_name;
12409 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12410 		ret = libbpf_get_error(*link);
12411 		break;
12412 	default:
12413 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12414 			prog->sec_name);
12415 		break;
12416 	}
12417 	free(probe_type);
12418 	free(binary_path);
12419 	free(func_name);
12420 
12421 	return ret;
12422 }
12423 
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)12424 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12425 					    bool retprobe, pid_t pid,
12426 					    const char *binary_path,
12427 					    size_t func_offset)
12428 {
12429 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12430 
12431 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12432 }
12433 
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)12434 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12435 					  pid_t pid, const char *binary_path,
12436 					  const char *usdt_provider, const char *usdt_name,
12437 					  const struct bpf_usdt_opts *opts)
12438 {
12439 	char resolved_path[512];
12440 	struct bpf_object *obj = prog->obj;
12441 	struct bpf_link *link;
12442 	__u64 usdt_cookie;
12443 	int err;
12444 
12445 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12446 		return libbpf_err_ptr(-EINVAL);
12447 
12448 	if (bpf_program__fd(prog) < 0) {
12449 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12450 			prog->name);
12451 		return libbpf_err_ptr(-EINVAL);
12452 	}
12453 
12454 	if (!binary_path)
12455 		return libbpf_err_ptr(-EINVAL);
12456 
12457 	if (!strchr(binary_path, '/')) {
12458 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12459 		if (err) {
12460 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12461 				prog->name, binary_path, errstr(err));
12462 			return libbpf_err_ptr(err);
12463 		}
12464 		binary_path = resolved_path;
12465 	}
12466 
12467 	/* USDT manager is instantiated lazily on first USDT attach. It will
12468 	 * be destroyed together with BPF object in bpf_object__close().
12469 	 */
12470 	if (IS_ERR(obj->usdt_man))
12471 		return libbpf_ptr(obj->usdt_man);
12472 	if (!obj->usdt_man) {
12473 		obj->usdt_man = usdt_manager_new(obj);
12474 		if (IS_ERR(obj->usdt_man))
12475 			return libbpf_ptr(obj->usdt_man);
12476 	}
12477 
12478 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12479 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12480 					usdt_provider, usdt_name, usdt_cookie);
12481 	err = libbpf_get_error(link);
12482 	if (err)
12483 		return libbpf_err_ptr(err);
12484 	return link;
12485 }
12486 
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12487 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12488 {
12489 	char *path = NULL, *provider = NULL, *name = NULL;
12490 	const char *sec_name;
12491 	int n, err;
12492 
12493 	sec_name = bpf_program__section_name(prog);
12494 	if (strcmp(sec_name, "usdt") == 0) {
12495 		/* no auto-attach for just SEC("usdt") */
12496 		*link = NULL;
12497 		return 0;
12498 	}
12499 
12500 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12501 	if (n != 3) {
12502 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12503 			sec_name);
12504 		err = -EINVAL;
12505 	} else {
12506 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12507 						 provider, name, NULL);
12508 		err = libbpf_get_error(*link);
12509 	}
12510 	free(path);
12511 	free(provider);
12512 	free(name);
12513 	return err;
12514 }
12515 
determine_tracepoint_id(const char * tp_category,const char * tp_name)12516 static int determine_tracepoint_id(const char *tp_category,
12517 				   const char *tp_name)
12518 {
12519 	char file[PATH_MAX];
12520 	int ret;
12521 
12522 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12523 		       tracefs_path(), tp_category, tp_name);
12524 	if (ret < 0)
12525 		return -errno;
12526 	if (ret >= sizeof(file)) {
12527 		pr_debug("tracepoint %s/%s path is too long\n",
12528 			 tp_category, tp_name);
12529 		return -E2BIG;
12530 	}
12531 	return parse_uint_from_file(file, "%d\n");
12532 }
12533 
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)12534 static int perf_event_open_tracepoint(const char *tp_category,
12535 				      const char *tp_name)
12536 {
12537 	const size_t attr_sz = sizeof(struct perf_event_attr);
12538 	struct perf_event_attr attr;
12539 	int tp_id, pfd, err;
12540 
12541 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12542 	if (tp_id < 0) {
12543 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12544 			tp_category, tp_name,
12545 			errstr(tp_id));
12546 		return tp_id;
12547 	}
12548 
12549 	memset(&attr, 0, attr_sz);
12550 	attr.type = PERF_TYPE_TRACEPOINT;
12551 	attr.size = attr_sz;
12552 	attr.config = tp_id;
12553 
12554 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12555 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12556 	if (pfd < 0) {
12557 		err = -errno;
12558 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12559 			tp_category, tp_name,
12560 			errstr(err));
12561 		return err;
12562 	}
12563 	return pfd;
12564 }
12565 
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)12566 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12567 						     const char *tp_category,
12568 						     const char *tp_name,
12569 						     const struct bpf_tracepoint_opts *opts)
12570 {
12571 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12572 	struct bpf_link *link;
12573 	int pfd, err;
12574 
12575 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12576 		return libbpf_err_ptr(-EINVAL);
12577 
12578 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12579 
12580 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12581 	if (pfd < 0) {
12582 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12583 			prog->name, tp_category, tp_name,
12584 			errstr(pfd));
12585 		return libbpf_err_ptr(pfd);
12586 	}
12587 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12588 	err = libbpf_get_error(link);
12589 	if (err) {
12590 		close(pfd);
12591 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12592 			prog->name, tp_category, tp_name,
12593 			errstr(err));
12594 		return libbpf_err_ptr(err);
12595 	}
12596 	return link;
12597 }
12598 
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)12599 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12600 						const char *tp_category,
12601 						const char *tp_name)
12602 {
12603 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12604 }
12605 
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12606 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12607 {
12608 	char *sec_name, *tp_cat, *tp_name;
12609 
12610 	*link = NULL;
12611 
12612 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12613 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12614 		return 0;
12615 
12616 	sec_name = strdup(prog->sec_name);
12617 	if (!sec_name)
12618 		return -ENOMEM;
12619 
12620 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12621 	if (str_has_pfx(prog->sec_name, "tp/"))
12622 		tp_cat = sec_name + sizeof("tp/") - 1;
12623 	else
12624 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12625 	tp_name = strchr(tp_cat, '/');
12626 	if (!tp_name) {
12627 		free(sec_name);
12628 		return -EINVAL;
12629 	}
12630 	*tp_name = '\0';
12631 	tp_name++;
12632 
12633 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12634 	free(sec_name);
12635 	return libbpf_get_error(*link);
12636 }
12637 
12638 struct bpf_link *
bpf_program__attach_raw_tracepoint_opts(const struct bpf_program * prog,const char * tp_name,struct bpf_raw_tracepoint_opts * opts)12639 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12640 					const char *tp_name,
12641 					struct bpf_raw_tracepoint_opts *opts)
12642 {
12643 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12644 	struct bpf_link *link;
12645 	int prog_fd, pfd;
12646 
12647 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12648 		return libbpf_err_ptr(-EINVAL);
12649 
12650 	prog_fd = bpf_program__fd(prog);
12651 	if (prog_fd < 0) {
12652 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12653 		return libbpf_err_ptr(-EINVAL);
12654 	}
12655 
12656 	link = calloc(1, sizeof(*link));
12657 	if (!link)
12658 		return libbpf_err_ptr(-ENOMEM);
12659 	link->detach = &bpf_link__detach_fd;
12660 
12661 	raw_opts.tp_name = tp_name;
12662 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12663 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12664 	if (pfd < 0) {
12665 		pfd = -errno;
12666 		free(link);
12667 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12668 			prog->name, tp_name, errstr(pfd));
12669 		return libbpf_err_ptr(pfd);
12670 	}
12671 	link->fd = pfd;
12672 	return link;
12673 }
12674 
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)12675 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12676 						    const char *tp_name)
12677 {
12678 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12679 }
12680 
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12681 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12682 {
12683 	static const char *const prefixes[] = {
12684 		"raw_tp",
12685 		"raw_tracepoint",
12686 		"raw_tp.w",
12687 		"raw_tracepoint.w",
12688 	};
12689 	size_t i;
12690 	const char *tp_name = NULL;
12691 
12692 	*link = NULL;
12693 
12694 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12695 		size_t pfx_len;
12696 
12697 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12698 			continue;
12699 
12700 		pfx_len = strlen(prefixes[i]);
12701 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12702 		if (prog->sec_name[pfx_len] == '\0')
12703 			return 0;
12704 
12705 		if (prog->sec_name[pfx_len] != '/')
12706 			continue;
12707 
12708 		tp_name = prog->sec_name + pfx_len + 1;
12709 		break;
12710 	}
12711 
12712 	if (!tp_name) {
12713 		pr_warn("prog '%s': invalid section name '%s'\n",
12714 			prog->name, prog->sec_name);
12715 		return -EINVAL;
12716 	}
12717 
12718 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12719 	return libbpf_get_error(*link);
12720 }
12721 
12722 /* 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)12723 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12724 						   const struct bpf_trace_opts *opts)
12725 {
12726 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12727 	struct bpf_link *link;
12728 	int prog_fd, pfd;
12729 
12730 	if (!OPTS_VALID(opts, bpf_trace_opts))
12731 		return libbpf_err_ptr(-EINVAL);
12732 
12733 	prog_fd = bpf_program__fd(prog);
12734 	if (prog_fd < 0) {
12735 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12736 		return libbpf_err_ptr(-EINVAL);
12737 	}
12738 
12739 	link = calloc(1, sizeof(*link));
12740 	if (!link)
12741 		return libbpf_err_ptr(-ENOMEM);
12742 	link->detach = &bpf_link__detach_fd;
12743 
12744 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12745 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12746 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12747 	if (pfd < 0) {
12748 		pfd = -errno;
12749 		free(link);
12750 		pr_warn("prog '%s': failed to attach: %s\n",
12751 			prog->name, errstr(pfd));
12752 		return libbpf_err_ptr(pfd);
12753 	}
12754 	link->fd = pfd;
12755 	return link;
12756 }
12757 
bpf_program__attach_trace(const struct bpf_program * prog)12758 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12759 {
12760 	return bpf_program__attach_btf_id(prog, NULL);
12761 }
12762 
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)12763 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12764 						const struct bpf_trace_opts *opts)
12765 {
12766 	return bpf_program__attach_btf_id(prog, opts);
12767 }
12768 
bpf_program__attach_lsm(const struct bpf_program * prog)12769 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12770 {
12771 	return bpf_program__attach_btf_id(prog, NULL);
12772 }
12773 
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12774 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12775 {
12776 	*link = bpf_program__attach_trace(prog);
12777 	return libbpf_get_error(*link);
12778 }
12779 
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12780 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12781 {
12782 	*link = bpf_program__attach_lsm(prog);
12783 	return libbpf_get_error(*link);
12784 }
12785 
12786 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)12787 bpf_program_attach_fd(const struct bpf_program *prog,
12788 		      int target_fd, const char *target_name,
12789 		      const struct bpf_link_create_opts *opts)
12790 {
12791 	enum bpf_attach_type attach_type;
12792 	struct bpf_link *link;
12793 	int prog_fd, link_fd;
12794 
12795 	prog_fd = bpf_program__fd(prog);
12796 	if (prog_fd < 0) {
12797 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12798 		return libbpf_err_ptr(-EINVAL);
12799 	}
12800 
12801 	link = calloc(1, sizeof(*link));
12802 	if (!link)
12803 		return libbpf_err_ptr(-ENOMEM);
12804 	link->detach = &bpf_link__detach_fd;
12805 
12806 	attach_type = bpf_program__expected_attach_type(prog);
12807 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12808 	if (link_fd < 0) {
12809 		link_fd = -errno;
12810 		free(link);
12811 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12812 			prog->name, target_name,
12813 			errstr(link_fd));
12814 		return libbpf_err_ptr(link_fd);
12815 	}
12816 	link->fd = link_fd;
12817 	return link;
12818 }
12819 
12820 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)12821 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12822 {
12823 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12824 }
12825 
12826 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)12827 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12828 {
12829 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12830 }
12831 
12832 struct bpf_link *
bpf_program__attach_sockmap(const struct bpf_program * prog,int map_fd)12833 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12834 {
12835 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12836 }
12837 
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)12838 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12839 {
12840 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12841 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12842 }
12843 
12844 struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)12845 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12846 			const struct bpf_tcx_opts *opts)
12847 {
12848 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12849 	__u32 relative_id;
12850 	int relative_fd;
12851 
12852 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12853 		return libbpf_err_ptr(-EINVAL);
12854 
12855 	relative_id = OPTS_GET(opts, relative_id, 0);
12856 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12857 
12858 	/* validate we don't have unexpected combinations of non-zero fields */
12859 	if (!ifindex) {
12860 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12861 			prog->name);
12862 		return libbpf_err_ptr(-EINVAL);
12863 	}
12864 	if (relative_fd && relative_id) {
12865 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12866 			prog->name);
12867 		return libbpf_err_ptr(-EINVAL);
12868 	}
12869 
12870 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12871 	link_create_opts.tcx.relative_fd = relative_fd;
12872 	link_create_opts.tcx.relative_id = relative_id;
12873 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12874 
12875 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12876 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12877 }
12878 
12879 struct bpf_link *
bpf_program__attach_netkit(const struct bpf_program * prog,int ifindex,const struct bpf_netkit_opts * opts)12880 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12881 			   const struct bpf_netkit_opts *opts)
12882 {
12883 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12884 	__u32 relative_id;
12885 	int relative_fd;
12886 
12887 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12888 		return libbpf_err_ptr(-EINVAL);
12889 
12890 	relative_id = OPTS_GET(opts, relative_id, 0);
12891 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12892 
12893 	/* validate we don't have unexpected combinations of non-zero fields */
12894 	if (!ifindex) {
12895 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12896 			prog->name);
12897 		return libbpf_err_ptr(-EINVAL);
12898 	}
12899 	if (relative_fd && relative_id) {
12900 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12901 			prog->name);
12902 		return libbpf_err_ptr(-EINVAL);
12903 	}
12904 
12905 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12906 	link_create_opts.netkit.relative_fd = relative_fd;
12907 	link_create_opts.netkit.relative_id = relative_id;
12908 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12909 
12910 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12911 }
12912 
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)12913 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12914 					      int target_fd,
12915 					      const char *attach_func_name)
12916 {
12917 	int btf_id;
12918 
12919 	if (!!target_fd != !!attach_func_name) {
12920 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12921 			prog->name);
12922 		return libbpf_err_ptr(-EINVAL);
12923 	}
12924 
12925 	if (prog->type != BPF_PROG_TYPE_EXT) {
12926 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12927 			prog->name);
12928 		return libbpf_err_ptr(-EINVAL);
12929 	}
12930 
12931 	if (target_fd) {
12932 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12933 
12934 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
12935 		if (btf_id < 0)
12936 			return libbpf_err_ptr(btf_id);
12937 
12938 		target_opts.target_btf_id = btf_id;
12939 
12940 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12941 					     &target_opts);
12942 	} else {
12943 		/* no target, so use raw_tracepoint_open for compatibility
12944 		 * with old kernels
12945 		 */
12946 		return bpf_program__attach_trace(prog);
12947 	}
12948 }
12949 
12950 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)12951 bpf_program__attach_iter(const struct bpf_program *prog,
12952 			 const struct bpf_iter_attach_opts *opts)
12953 {
12954 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12955 	struct bpf_link *link;
12956 	int prog_fd, link_fd;
12957 	__u32 target_fd = 0;
12958 
12959 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12960 		return libbpf_err_ptr(-EINVAL);
12961 
12962 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12963 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12964 
12965 	prog_fd = bpf_program__fd(prog);
12966 	if (prog_fd < 0) {
12967 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12968 		return libbpf_err_ptr(-EINVAL);
12969 	}
12970 
12971 	link = calloc(1, sizeof(*link));
12972 	if (!link)
12973 		return libbpf_err_ptr(-ENOMEM);
12974 	link->detach = &bpf_link__detach_fd;
12975 
12976 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12977 				  &link_create_opts);
12978 	if (link_fd < 0) {
12979 		link_fd = -errno;
12980 		free(link);
12981 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12982 			prog->name, errstr(link_fd));
12983 		return libbpf_err_ptr(link_fd);
12984 	}
12985 	link->fd = link_fd;
12986 	return link;
12987 }
12988 
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12989 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12990 {
12991 	*link = bpf_program__attach_iter(prog, NULL);
12992 	return libbpf_get_error(*link);
12993 }
12994 
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)12995 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12996 					       const struct bpf_netfilter_opts *opts)
12997 {
12998 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12999 	struct bpf_link *link;
13000 	int prog_fd, link_fd;
13001 
13002 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13003 		return libbpf_err_ptr(-EINVAL);
13004 
13005 	prog_fd = bpf_program__fd(prog);
13006 	if (prog_fd < 0) {
13007 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13008 		return libbpf_err_ptr(-EINVAL);
13009 	}
13010 
13011 	link = calloc(1, sizeof(*link));
13012 	if (!link)
13013 		return libbpf_err_ptr(-ENOMEM);
13014 
13015 	link->detach = &bpf_link__detach_fd;
13016 
13017 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13018 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13019 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13020 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13021 
13022 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13023 	if (link_fd < 0) {
13024 		link_fd = -errno;
13025 		free(link);
13026 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13027 			prog->name, errstr(link_fd));
13028 		return libbpf_err_ptr(link_fd);
13029 	}
13030 	link->fd = link_fd;
13031 
13032 	return link;
13033 }
13034 
bpf_program__attach(const struct bpf_program * prog)13035 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13036 {
13037 	struct bpf_link *link = NULL;
13038 	int err;
13039 
13040 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13041 		return libbpf_err_ptr(-EOPNOTSUPP);
13042 
13043 	if (bpf_program__fd(prog) < 0) {
13044 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13045 			prog->name);
13046 		return libbpf_err_ptr(-EINVAL);
13047 	}
13048 
13049 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13050 	if (err)
13051 		return libbpf_err_ptr(err);
13052 
13053 	/* When calling bpf_program__attach() explicitly, auto-attach support
13054 	 * is expected to work, so NULL returned link is considered an error.
13055 	 * This is different for skeleton's attach, see comment in
13056 	 * bpf_object__attach_skeleton().
13057 	 */
13058 	if (!link)
13059 		return libbpf_err_ptr(-EOPNOTSUPP);
13060 
13061 	return link;
13062 }
13063 
13064 struct bpf_link_struct_ops {
13065 	struct bpf_link link;
13066 	int map_fd;
13067 };
13068 
bpf_link__detach_struct_ops(struct bpf_link * link)13069 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13070 {
13071 	struct bpf_link_struct_ops *st_link;
13072 	__u32 zero = 0;
13073 
13074 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13075 
13076 	if (st_link->map_fd < 0)
13077 		/* w/o a real link */
13078 		return bpf_map_delete_elem(link->fd, &zero);
13079 
13080 	return close(link->fd);
13081 }
13082 
bpf_map__attach_struct_ops(const struct bpf_map * map)13083 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13084 {
13085 	struct bpf_link_struct_ops *link;
13086 	__u32 zero = 0;
13087 	int err, fd;
13088 
13089 	if (!bpf_map__is_struct_ops(map)) {
13090 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13091 		return libbpf_err_ptr(-EINVAL);
13092 	}
13093 
13094 	if (map->fd < 0) {
13095 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13096 		return libbpf_err_ptr(-EINVAL);
13097 	}
13098 
13099 	link = calloc(1, sizeof(*link));
13100 	if (!link)
13101 		return libbpf_err_ptr(-EINVAL);
13102 
13103 	/* kern_vdata should be prepared during the loading phase. */
13104 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13105 	/* It can be EBUSY if the map has been used to create or
13106 	 * update a link before.  We don't allow updating the value of
13107 	 * a struct_ops once it is set.  That ensures that the value
13108 	 * never changed.  So, it is safe to skip EBUSY.
13109 	 */
13110 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13111 		free(link);
13112 		return libbpf_err_ptr(err);
13113 	}
13114 
13115 	link->link.detach = bpf_link__detach_struct_ops;
13116 
13117 	if (!(map->def.map_flags & BPF_F_LINK)) {
13118 		/* w/o a real link */
13119 		link->link.fd = map->fd;
13120 		link->map_fd = -1;
13121 		return &link->link;
13122 	}
13123 
13124 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13125 	if (fd < 0) {
13126 		free(link);
13127 		return libbpf_err_ptr(fd);
13128 	}
13129 
13130 	link->link.fd = fd;
13131 	link->map_fd = map->fd;
13132 
13133 	return &link->link;
13134 }
13135 
13136 /*
13137  * Swap the back struct_ops of a link with a new struct_ops map.
13138  */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)13139 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13140 {
13141 	struct bpf_link_struct_ops *st_ops_link;
13142 	__u32 zero = 0;
13143 	int err;
13144 
13145 	if (!bpf_map__is_struct_ops(map))
13146 		return libbpf_err(-EINVAL);
13147 
13148 	if (map->fd < 0) {
13149 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13150 		return libbpf_err(-EINVAL);
13151 	}
13152 
13153 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13154 	/* Ensure the type of a link is correct */
13155 	if (st_ops_link->map_fd < 0)
13156 		return libbpf_err(-EINVAL);
13157 
13158 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13159 	/* It can be EBUSY if the map has been used to create or
13160 	 * update a link before.  We don't allow updating the value of
13161 	 * a struct_ops once it is set.  That ensures that the value
13162 	 * never changed.  So, it is safe to skip EBUSY.
13163 	 */
13164 	if (err && err != -EBUSY)
13165 		return err;
13166 
13167 	err = bpf_link_update(link->fd, map->fd, NULL);
13168 	if (err < 0)
13169 		return err;
13170 
13171 	st_ops_link->map_fd = map->fd;
13172 
13173 	return 0;
13174 }
13175 
13176 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13177 							  void *private_data);
13178 
13179 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)13180 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13181 		       void **copy_mem, size_t *copy_size,
13182 		       bpf_perf_event_print_t fn, void *private_data)
13183 {
13184 	struct perf_event_mmap_page *header = mmap_mem;
13185 	__u64 data_head = ring_buffer_read_head(header);
13186 	__u64 data_tail = header->data_tail;
13187 	void *base = ((__u8 *)header) + page_size;
13188 	int ret = LIBBPF_PERF_EVENT_CONT;
13189 	struct perf_event_header *ehdr;
13190 	size_t ehdr_size;
13191 
13192 	while (data_head != data_tail) {
13193 		ehdr = base + (data_tail & (mmap_size - 1));
13194 		ehdr_size = ehdr->size;
13195 
13196 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13197 			void *copy_start = ehdr;
13198 			size_t len_first = base + mmap_size - copy_start;
13199 			size_t len_secnd = ehdr_size - len_first;
13200 
13201 			if (*copy_size < ehdr_size) {
13202 				free(*copy_mem);
13203 				*copy_mem = malloc(ehdr_size);
13204 				if (!*copy_mem) {
13205 					*copy_size = 0;
13206 					ret = LIBBPF_PERF_EVENT_ERROR;
13207 					break;
13208 				}
13209 				*copy_size = ehdr_size;
13210 			}
13211 
13212 			memcpy(*copy_mem, copy_start, len_first);
13213 			memcpy(*copy_mem + len_first, base, len_secnd);
13214 			ehdr = *copy_mem;
13215 		}
13216 
13217 		ret = fn(ehdr, private_data);
13218 		data_tail += ehdr_size;
13219 		if (ret != LIBBPF_PERF_EVENT_CONT)
13220 			break;
13221 	}
13222 
13223 	ring_buffer_write_tail(header, data_tail);
13224 	return libbpf_err(ret);
13225 }
13226 
13227 struct perf_buffer;
13228 
13229 struct perf_buffer_params {
13230 	struct perf_event_attr *attr;
13231 	/* if event_cb is specified, it takes precendence */
13232 	perf_buffer_event_fn event_cb;
13233 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13234 	perf_buffer_sample_fn sample_cb;
13235 	perf_buffer_lost_fn lost_cb;
13236 	void *ctx;
13237 	int cpu_cnt;
13238 	int *cpus;
13239 	int *map_keys;
13240 };
13241 
13242 struct perf_cpu_buf {
13243 	struct perf_buffer *pb;
13244 	void *base; /* mmap()'ed memory */
13245 	void *buf; /* for reconstructing segmented data */
13246 	size_t buf_size;
13247 	int fd;
13248 	int cpu;
13249 	int map_key;
13250 };
13251 
13252 struct perf_buffer {
13253 	perf_buffer_event_fn event_cb;
13254 	perf_buffer_sample_fn sample_cb;
13255 	perf_buffer_lost_fn lost_cb;
13256 	void *ctx; /* passed into callbacks */
13257 
13258 	size_t page_size;
13259 	size_t mmap_size;
13260 	struct perf_cpu_buf **cpu_bufs;
13261 	struct epoll_event *events;
13262 	int cpu_cnt; /* number of allocated CPU buffers */
13263 	int epoll_fd; /* perf event FD */
13264 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13265 };
13266 
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)13267 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13268 				      struct perf_cpu_buf *cpu_buf)
13269 {
13270 	if (!cpu_buf)
13271 		return;
13272 	if (cpu_buf->base &&
13273 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13274 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13275 	if (cpu_buf->fd >= 0) {
13276 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13277 		close(cpu_buf->fd);
13278 	}
13279 	free(cpu_buf->buf);
13280 	free(cpu_buf);
13281 }
13282 
perf_buffer__free(struct perf_buffer * pb)13283 void perf_buffer__free(struct perf_buffer *pb)
13284 {
13285 	int i;
13286 
13287 	if (IS_ERR_OR_NULL(pb))
13288 		return;
13289 	if (pb->cpu_bufs) {
13290 		for (i = 0; i < pb->cpu_cnt; i++) {
13291 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13292 
13293 			if (!cpu_buf)
13294 				continue;
13295 
13296 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13297 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13298 		}
13299 		free(pb->cpu_bufs);
13300 	}
13301 	if (pb->epoll_fd >= 0)
13302 		close(pb->epoll_fd);
13303 	free(pb->events);
13304 	free(pb);
13305 }
13306 
13307 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)13308 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13309 			  int cpu, int map_key)
13310 {
13311 	struct perf_cpu_buf *cpu_buf;
13312 	int err;
13313 
13314 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13315 	if (!cpu_buf)
13316 		return ERR_PTR(-ENOMEM);
13317 
13318 	cpu_buf->pb = pb;
13319 	cpu_buf->cpu = cpu;
13320 	cpu_buf->map_key = map_key;
13321 
13322 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13323 			      -1, PERF_FLAG_FD_CLOEXEC);
13324 	if (cpu_buf->fd < 0) {
13325 		err = -errno;
13326 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13327 			cpu, errstr(err));
13328 		goto error;
13329 	}
13330 
13331 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13332 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13333 			     cpu_buf->fd, 0);
13334 	if (cpu_buf->base == MAP_FAILED) {
13335 		cpu_buf->base = NULL;
13336 		err = -errno;
13337 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13338 			cpu, errstr(err));
13339 		goto error;
13340 	}
13341 
13342 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13343 		err = -errno;
13344 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13345 			cpu, errstr(err));
13346 		goto error;
13347 	}
13348 
13349 	return cpu_buf;
13350 
13351 error:
13352 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13353 	return (struct perf_cpu_buf *)ERR_PTR(err);
13354 }
13355 
13356 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13357 					      struct perf_buffer_params *p);
13358 
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)13359 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13360 				     perf_buffer_sample_fn sample_cb,
13361 				     perf_buffer_lost_fn lost_cb,
13362 				     void *ctx,
13363 				     const struct perf_buffer_opts *opts)
13364 {
13365 	const size_t attr_sz = sizeof(struct perf_event_attr);
13366 	struct perf_buffer_params p = {};
13367 	struct perf_event_attr attr;
13368 	__u32 sample_period;
13369 
13370 	if (!OPTS_VALID(opts, perf_buffer_opts))
13371 		return libbpf_err_ptr(-EINVAL);
13372 
13373 	sample_period = OPTS_GET(opts, sample_period, 1);
13374 	if (!sample_period)
13375 		sample_period = 1;
13376 
13377 	memset(&attr, 0, attr_sz);
13378 	attr.size = attr_sz;
13379 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13380 	attr.type = PERF_TYPE_SOFTWARE;
13381 	attr.sample_type = PERF_SAMPLE_RAW;
13382 	attr.wakeup_events = sample_period;
13383 
13384 	p.attr = &attr;
13385 	p.sample_cb = sample_cb;
13386 	p.lost_cb = lost_cb;
13387 	p.ctx = ctx;
13388 
13389 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13390 }
13391 
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)13392 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13393 					 struct perf_event_attr *attr,
13394 					 perf_buffer_event_fn event_cb, void *ctx,
13395 					 const struct perf_buffer_raw_opts *opts)
13396 {
13397 	struct perf_buffer_params p = {};
13398 
13399 	if (!attr)
13400 		return libbpf_err_ptr(-EINVAL);
13401 
13402 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13403 		return libbpf_err_ptr(-EINVAL);
13404 
13405 	p.attr = attr;
13406 	p.event_cb = event_cb;
13407 	p.ctx = ctx;
13408 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13409 	p.cpus = OPTS_GET(opts, cpus, NULL);
13410 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13411 
13412 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13413 }
13414 
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)13415 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13416 					      struct perf_buffer_params *p)
13417 {
13418 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13419 	struct bpf_map_info map;
13420 	struct perf_buffer *pb;
13421 	bool *online = NULL;
13422 	__u32 map_info_len;
13423 	int err, i, j, n;
13424 
13425 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13426 		pr_warn("page count should be power of two, but is %zu\n",
13427 			page_cnt);
13428 		return ERR_PTR(-EINVAL);
13429 	}
13430 
13431 	/* best-effort sanity checks */
13432 	memset(&map, 0, sizeof(map));
13433 	map_info_len = sizeof(map);
13434 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13435 	if (err) {
13436 		err = -errno;
13437 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13438 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13439 		 */
13440 		if (err != -EINVAL) {
13441 			pr_warn("failed to get map info for map FD %d: %s\n",
13442 				map_fd, errstr(err));
13443 			return ERR_PTR(err);
13444 		}
13445 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13446 			 map_fd);
13447 	} else {
13448 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13449 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13450 				map.name);
13451 			return ERR_PTR(-EINVAL);
13452 		}
13453 	}
13454 
13455 	pb = calloc(1, sizeof(*pb));
13456 	if (!pb)
13457 		return ERR_PTR(-ENOMEM);
13458 
13459 	pb->event_cb = p->event_cb;
13460 	pb->sample_cb = p->sample_cb;
13461 	pb->lost_cb = p->lost_cb;
13462 	pb->ctx = p->ctx;
13463 
13464 	pb->page_size = getpagesize();
13465 	pb->mmap_size = pb->page_size * page_cnt;
13466 	pb->map_fd = map_fd;
13467 
13468 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13469 	if (pb->epoll_fd < 0) {
13470 		err = -errno;
13471 		pr_warn("failed to create epoll instance: %s\n",
13472 			errstr(err));
13473 		goto error;
13474 	}
13475 
13476 	if (p->cpu_cnt > 0) {
13477 		pb->cpu_cnt = p->cpu_cnt;
13478 	} else {
13479 		pb->cpu_cnt = libbpf_num_possible_cpus();
13480 		if (pb->cpu_cnt < 0) {
13481 			err = pb->cpu_cnt;
13482 			goto error;
13483 		}
13484 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13485 			pb->cpu_cnt = map.max_entries;
13486 	}
13487 
13488 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13489 	if (!pb->events) {
13490 		err = -ENOMEM;
13491 		pr_warn("failed to allocate events: out of memory\n");
13492 		goto error;
13493 	}
13494 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13495 	if (!pb->cpu_bufs) {
13496 		err = -ENOMEM;
13497 		pr_warn("failed to allocate buffers: out of memory\n");
13498 		goto error;
13499 	}
13500 
13501 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13502 	if (err) {
13503 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13504 		goto error;
13505 	}
13506 
13507 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13508 		struct perf_cpu_buf *cpu_buf;
13509 		int cpu, map_key;
13510 
13511 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13512 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13513 
13514 		/* in case user didn't explicitly requested particular CPUs to
13515 		 * be attached to, skip offline/not present CPUs
13516 		 */
13517 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13518 			continue;
13519 
13520 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13521 		if (IS_ERR(cpu_buf)) {
13522 			err = PTR_ERR(cpu_buf);
13523 			goto error;
13524 		}
13525 
13526 		pb->cpu_bufs[j] = cpu_buf;
13527 
13528 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13529 					  &cpu_buf->fd, 0);
13530 		if (err) {
13531 			err = -errno;
13532 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13533 				cpu, map_key, cpu_buf->fd,
13534 				errstr(err));
13535 			goto error;
13536 		}
13537 
13538 		pb->events[j].events = EPOLLIN;
13539 		pb->events[j].data.ptr = cpu_buf;
13540 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13541 			      &pb->events[j]) < 0) {
13542 			err = -errno;
13543 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13544 				cpu, cpu_buf->fd,
13545 				errstr(err));
13546 			goto error;
13547 		}
13548 		j++;
13549 	}
13550 	pb->cpu_cnt = j;
13551 	free(online);
13552 
13553 	return pb;
13554 
13555 error:
13556 	free(online);
13557 	if (pb)
13558 		perf_buffer__free(pb);
13559 	return ERR_PTR(err);
13560 }
13561 
13562 struct perf_sample_raw {
13563 	struct perf_event_header header;
13564 	uint32_t size;
13565 	char data[];
13566 };
13567 
13568 struct perf_sample_lost {
13569 	struct perf_event_header header;
13570 	uint64_t id;
13571 	uint64_t lost;
13572 	uint64_t sample_id;
13573 };
13574 
13575 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)13576 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13577 {
13578 	struct perf_cpu_buf *cpu_buf = ctx;
13579 	struct perf_buffer *pb = cpu_buf->pb;
13580 	void *data = e;
13581 
13582 	/* user wants full control over parsing perf event */
13583 	if (pb->event_cb)
13584 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13585 
13586 	switch (e->type) {
13587 	case PERF_RECORD_SAMPLE: {
13588 		struct perf_sample_raw *s = data;
13589 
13590 		if (pb->sample_cb)
13591 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13592 		break;
13593 	}
13594 	case PERF_RECORD_LOST: {
13595 		struct perf_sample_lost *s = data;
13596 
13597 		if (pb->lost_cb)
13598 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13599 		break;
13600 	}
13601 	default:
13602 		pr_warn("unknown perf sample type %d\n", e->type);
13603 		return LIBBPF_PERF_EVENT_ERROR;
13604 	}
13605 	return LIBBPF_PERF_EVENT_CONT;
13606 }
13607 
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)13608 static int perf_buffer__process_records(struct perf_buffer *pb,
13609 					struct perf_cpu_buf *cpu_buf)
13610 {
13611 	enum bpf_perf_event_ret ret;
13612 
13613 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13614 				     pb->page_size, &cpu_buf->buf,
13615 				     &cpu_buf->buf_size,
13616 				     perf_buffer__process_record, cpu_buf);
13617 	if (ret != LIBBPF_PERF_EVENT_CONT)
13618 		return ret;
13619 	return 0;
13620 }
13621 
perf_buffer__epoll_fd(const struct perf_buffer * pb)13622 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13623 {
13624 	return pb->epoll_fd;
13625 }
13626 
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)13627 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13628 {
13629 	int i, cnt, err;
13630 
13631 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13632 	if (cnt < 0)
13633 		return -errno;
13634 
13635 	for (i = 0; i < cnt; i++) {
13636 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13637 
13638 		err = perf_buffer__process_records(pb, cpu_buf);
13639 		if (err) {
13640 			pr_warn("error while processing records: %s\n", errstr(err));
13641 			return libbpf_err(err);
13642 		}
13643 	}
13644 	return cnt;
13645 }
13646 
13647 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13648  * manager.
13649  */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)13650 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13651 {
13652 	return pb->cpu_cnt;
13653 }
13654 
13655 /*
13656  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13657  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13658  * select()/poll()/epoll() Linux syscalls.
13659  */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)13660 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13661 {
13662 	struct perf_cpu_buf *cpu_buf;
13663 
13664 	if (buf_idx >= pb->cpu_cnt)
13665 		return libbpf_err(-EINVAL);
13666 
13667 	cpu_buf = pb->cpu_bufs[buf_idx];
13668 	if (!cpu_buf)
13669 		return libbpf_err(-ENOENT);
13670 
13671 	return cpu_buf->fd;
13672 }
13673 
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)13674 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13675 {
13676 	struct perf_cpu_buf *cpu_buf;
13677 
13678 	if (buf_idx >= pb->cpu_cnt)
13679 		return libbpf_err(-EINVAL);
13680 
13681 	cpu_buf = pb->cpu_bufs[buf_idx];
13682 	if (!cpu_buf)
13683 		return libbpf_err(-ENOENT);
13684 
13685 	*buf = cpu_buf->base;
13686 	*buf_size = pb->mmap_size;
13687 	return 0;
13688 }
13689 
13690 /*
13691  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13692  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13693  * consume, do nothing and return success.
13694  * Returns:
13695  *   - 0 on success;
13696  *   - <0 on failure.
13697  */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)13698 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13699 {
13700 	struct perf_cpu_buf *cpu_buf;
13701 
13702 	if (buf_idx >= pb->cpu_cnt)
13703 		return libbpf_err(-EINVAL);
13704 
13705 	cpu_buf = pb->cpu_bufs[buf_idx];
13706 	if (!cpu_buf)
13707 		return libbpf_err(-ENOENT);
13708 
13709 	return perf_buffer__process_records(pb, cpu_buf);
13710 }
13711 
perf_buffer__consume(struct perf_buffer * pb)13712 int perf_buffer__consume(struct perf_buffer *pb)
13713 {
13714 	int i, err;
13715 
13716 	for (i = 0; i < pb->cpu_cnt; i++) {
13717 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13718 
13719 		if (!cpu_buf)
13720 			continue;
13721 
13722 		err = perf_buffer__process_records(pb, cpu_buf);
13723 		if (err) {
13724 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13725 				i, errstr(err));
13726 			return libbpf_err(err);
13727 		}
13728 	}
13729 	return 0;
13730 }
13731 
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)13732 int bpf_program__set_attach_target(struct bpf_program *prog,
13733 				   int attach_prog_fd,
13734 				   const char *attach_func_name)
13735 {
13736 	int btf_obj_fd = 0, btf_id = 0, err;
13737 
13738 	if (!prog || attach_prog_fd < 0)
13739 		return libbpf_err(-EINVAL);
13740 
13741 	if (prog->obj->state >= OBJ_LOADED)
13742 		return libbpf_err(-EINVAL);
13743 
13744 	if (attach_prog_fd && !attach_func_name) {
13745 		/* remember attach_prog_fd and let bpf_program__load() find
13746 		 * BTF ID during the program load
13747 		 */
13748 		prog->attach_prog_fd = attach_prog_fd;
13749 		return 0;
13750 	}
13751 
13752 	if (attach_prog_fd) {
13753 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13754 						 attach_prog_fd, prog->obj->token_fd);
13755 		if (btf_id < 0)
13756 			return libbpf_err(btf_id);
13757 	} else {
13758 		if (!attach_func_name)
13759 			return libbpf_err(-EINVAL);
13760 
13761 		/* load btf_vmlinux, if not yet */
13762 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13763 		if (err)
13764 			return libbpf_err(err);
13765 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13766 					 prog->expected_attach_type,
13767 					 &btf_obj_fd, &btf_id);
13768 		if (err)
13769 			return libbpf_err(err);
13770 	}
13771 
13772 	prog->attach_btf_id = btf_id;
13773 	prog->attach_btf_obj_fd = btf_obj_fd;
13774 	prog->attach_prog_fd = attach_prog_fd;
13775 	return 0;
13776 }
13777 
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)13778 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13779 {
13780 	int err = 0, n, len, start, end = -1;
13781 	bool *tmp;
13782 
13783 	*mask = NULL;
13784 	*mask_sz = 0;
13785 
13786 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13787 	while (*s) {
13788 		if (*s == ',' || *s == '\n') {
13789 			s++;
13790 			continue;
13791 		}
13792 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13793 		if (n <= 0 || n > 2) {
13794 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13795 			err = -EINVAL;
13796 			goto cleanup;
13797 		} else if (n == 1) {
13798 			end = start;
13799 		}
13800 		if (start < 0 || start > end) {
13801 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13802 				start, end, s);
13803 			err = -EINVAL;
13804 			goto cleanup;
13805 		}
13806 		tmp = realloc(*mask, end + 1);
13807 		if (!tmp) {
13808 			err = -ENOMEM;
13809 			goto cleanup;
13810 		}
13811 		*mask = tmp;
13812 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13813 		memset(tmp + start, 1, end - start + 1);
13814 		*mask_sz = end + 1;
13815 		s += len;
13816 	}
13817 	if (!*mask_sz) {
13818 		pr_warn("Empty CPU range\n");
13819 		return -EINVAL;
13820 	}
13821 	return 0;
13822 cleanup:
13823 	free(*mask);
13824 	*mask = NULL;
13825 	return err;
13826 }
13827 
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)13828 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13829 {
13830 	int fd, err = 0, len;
13831 	char buf[128];
13832 
13833 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13834 	if (fd < 0) {
13835 		err = -errno;
13836 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13837 		return err;
13838 	}
13839 	len = read(fd, buf, sizeof(buf));
13840 	close(fd);
13841 	if (len <= 0) {
13842 		err = len ? -errno : -EINVAL;
13843 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13844 		return err;
13845 	}
13846 	if (len >= sizeof(buf)) {
13847 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13848 		return -E2BIG;
13849 	}
13850 	buf[len] = '\0';
13851 
13852 	return parse_cpu_mask_str(buf, mask, mask_sz);
13853 }
13854 
libbpf_num_possible_cpus(void)13855 int libbpf_num_possible_cpus(void)
13856 {
13857 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13858 	static int cpus;
13859 	int err, n, i, tmp_cpus;
13860 	bool *mask;
13861 
13862 	tmp_cpus = READ_ONCE(cpus);
13863 	if (tmp_cpus > 0)
13864 		return tmp_cpus;
13865 
13866 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13867 	if (err)
13868 		return libbpf_err(err);
13869 
13870 	tmp_cpus = 0;
13871 	for (i = 0; i < n; i++) {
13872 		if (mask[i])
13873 			tmp_cpus++;
13874 	}
13875 	free(mask);
13876 
13877 	WRITE_ONCE(cpus, tmp_cpus);
13878 	return tmp_cpus;
13879 }
13880 
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt,size_t map_skel_sz)13881 static int populate_skeleton_maps(const struct bpf_object *obj,
13882 				  struct bpf_map_skeleton *maps,
13883 				  size_t map_cnt, size_t map_skel_sz)
13884 {
13885 	int i;
13886 
13887 	for (i = 0; i < map_cnt; i++) {
13888 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13889 		struct bpf_map **map = map_skel->map;
13890 		const char *name = map_skel->name;
13891 		void **mmaped = map_skel->mmaped;
13892 
13893 		*map = bpf_object__find_map_by_name(obj, name);
13894 		if (!*map) {
13895 			pr_warn("failed to find skeleton map '%s'\n", name);
13896 			return -ESRCH;
13897 		}
13898 
13899 		/* externs shouldn't be pre-setup from user code */
13900 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13901 			*mmaped = (*map)->mmaped;
13902 	}
13903 	return 0;
13904 }
13905 
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt,size_t prog_skel_sz)13906 static int populate_skeleton_progs(const struct bpf_object *obj,
13907 				   struct bpf_prog_skeleton *progs,
13908 				   size_t prog_cnt, size_t prog_skel_sz)
13909 {
13910 	int i;
13911 
13912 	for (i = 0; i < prog_cnt; i++) {
13913 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13914 		struct bpf_program **prog = prog_skel->prog;
13915 		const char *name = prog_skel->name;
13916 
13917 		*prog = bpf_object__find_program_by_name(obj, name);
13918 		if (!*prog) {
13919 			pr_warn("failed to find skeleton program '%s'\n", name);
13920 			return -ESRCH;
13921 		}
13922 	}
13923 	return 0;
13924 }
13925 
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)13926 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13927 			      const struct bpf_object_open_opts *opts)
13928 {
13929 	struct bpf_object *obj;
13930 	int err;
13931 
13932 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13933 	if (IS_ERR(obj)) {
13934 		err = PTR_ERR(obj);
13935 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
13936 			s->name, errstr(err));
13937 		return libbpf_err(err);
13938 	}
13939 
13940 	*s->obj = obj;
13941 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13942 	if (err) {
13943 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
13944 		return libbpf_err(err);
13945 	}
13946 
13947 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13948 	if (err) {
13949 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
13950 		return libbpf_err(err);
13951 	}
13952 
13953 	return 0;
13954 }
13955 
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13956 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13957 {
13958 	int err, len, var_idx, i;
13959 	const char *var_name;
13960 	const struct bpf_map *map;
13961 	struct btf *btf;
13962 	__u32 map_type_id;
13963 	const struct btf_type *map_type, *var_type;
13964 	const struct bpf_var_skeleton *var_skel;
13965 	struct btf_var_secinfo *var;
13966 
13967 	if (!s->obj)
13968 		return libbpf_err(-EINVAL);
13969 
13970 	btf = bpf_object__btf(s->obj);
13971 	if (!btf) {
13972 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13973 			bpf_object__name(s->obj));
13974 		return libbpf_err(-errno);
13975 	}
13976 
13977 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
13978 	if (err) {
13979 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13980 		return libbpf_err(err);
13981 	}
13982 
13983 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13984 	if (err) {
13985 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13986 		return libbpf_err(err);
13987 	}
13988 
13989 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13990 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
13991 		map = *var_skel->map;
13992 		map_type_id = bpf_map__btf_value_type_id(map);
13993 		map_type = btf__type_by_id(btf, map_type_id);
13994 
13995 		if (!btf_is_datasec(map_type)) {
13996 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
13997 				bpf_map__name(map),
13998 				__btf_kind_str(btf_kind(map_type)));
13999 			return libbpf_err(-EINVAL);
14000 		}
14001 
14002 		len = btf_vlen(map_type);
14003 		var = btf_var_secinfos(map_type);
14004 		for (i = 0; i < len; i++, var++) {
14005 			var_type = btf__type_by_id(btf, var->type);
14006 			var_name = btf__name_by_offset(btf, var_type->name_off);
14007 			if (strcmp(var_name, var_skel->name) == 0) {
14008 				*var_skel->addr = map->mmaped + var->offset;
14009 				break;
14010 			}
14011 		}
14012 	}
14013 	return 0;
14014 }
14015 
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)14016 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14017 {
14018 	if (!s)
14019 		return;
14020 	free(s->maps);
14021 	free(s->progs);
14022 	free(s->vars);
14023 	free(s);
14024 }
14025 
bpf_object__load_skeleton(struct bpf_object_skeleton * s)14026 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14027 {
14028 	int i, err;
14029 
14030 	err = bpf_object__load(*s->obj);
14031 	if (err) {
14032 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14033 		return libbpf_err(err);
14034 	}
14035 
14036 	for (i = 0; i < s->map_cnt; i++) {
14037 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14038 		struct bpf_map *map = *map_skel->map;
14039 
14040 		if (!map_skel->mmaped)
14041 			continue;
14042 
14043 		*map_skel->mmaped = map->mmaped;
14044 	}
14045 
14046 	return 0;
14047 }
14048 
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)14049 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14050 {
14051 	int i, err;
14052 
14053 	for (i = 0; i < s->prog_cnt; i++) {
14054 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14055 		struct bpf_program *prog = *prog_skel->prog;
14056 		struct bpf_link **link = prog_skel->link;
14057 
14058 		if (!prog->autoload || !prog->autoattach)
14059 			continue;
14060 
14061 		/* auto-attaching not supported for this program */
14062 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14063 			continue;
14064 
14065 		/* if user already set the link manually, don't attempt auto-attach */
14066 		if (*link)
14067 			continue;
14068 
14069 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14070 		if (err) {
14071 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14072 				bpf_program__name(prog), errstr(err));
14073 			return libbpf_err(err);
14074 		}
14075 
14076 		/* It's possible that for some SEC() definitions auto-attach
14077 		 * is supported in some cases (e.g., if definition completely
14078 		 * specifies target information), but is not in other cases.
14079 		 * SEC("uprobe") is one such case. If user specified target
14080 		 * binary and function name, such BPF program can be
14081 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14082 		 * attach to fail. It should just be skipped.
14083 		 * attach_fn signals such case with returning 0 (no error) and
14084 		 * setting link to NULL.
14085 		 */
14086 	}
14087 
14088 
14089 	for (i = 0; i < s->map_cnt; i++) {
14090 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14091 		struct bpf_map *map = *map_skel->map;
14092 		struct bpf_link **link;
14093 
14094 		if (!map->autocreate || !map->autoattach)
14095 			continue;
14096 
14097 		/* only struct_ops maps can be attached */
14098 		if (!bpf_map__is_struct_ops(map))
14099 			continue;
14100 
14101 		/* skeleton is created with earlier version of bpftool, notify user */
14102 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14103 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14104 				bpf_map__name(map));
14105 			continue;
14106 		}
14107 
14108 		link = map_skel->link;
14109 		if (!link) {
14110 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14111 				bpf_map__name(map));
14112 			continue;
14113 		}
14114 
14115 		if (*link)
14116 			continue;
14117 
14118 		*link = bpf_map__attach_struct_ops(map);
14119 		if (!*link) {
14120 			err = -errno;
14121 			pr_warn("map '%s': failed to auto-attach: %s\n",
14122 				bpf_map__name(map), errstr(err));
14123 			return libbpf_err(err);
14124 		}
14125 	}
14126 
14127 	return 0;
14128 }
14129 
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)14130 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14131 {
14132 	int i;
14133 
14134 	for (i = 0; i < s->prog_cnt; i++) {
14135 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14136 		struct bpf_link **link = prog_skel->link;
14137 
14138 		bpf_link__destroy(*link);
14139 		*link = NULL;
14140 	}
14141 
14142 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14143 		return;
14144 
14145 	for (i = 0; i < s->map_cnt; i++) {
14146 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14147 		struct bpf_link **link = map_skel->link;
14148 
14149 		if (link) {
14150 			bpf_link__destroy(*link);
14151 			*link = NULL;
14152 		}
14153 	}
14154 }
14155 
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)14156 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14157 {
14158 	if (!s)
14159 		return;
14160 
14161 	bpf_object__detach_skeleton(s);
14162 	if (s->obj)
14163 		bpf_object__close(*s->obj);
14164 	free(s->maps);
14165 	free(s->progs);
14166 	free(s);
14167 }
14168