• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.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 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73 
74 static const char * const attach_type_name[] = {
75 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
76 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
77 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
78 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
79 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
80 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
81 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
82 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
83 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
84 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
85 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
86 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
87 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
88 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
89 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
90 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
91 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
92 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
93 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
94 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
95 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
96 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
97 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
98 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
99 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
100 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
101 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
102 	[BPF_LIRC_MODE2]		= "lirc_mode2",
103 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
104 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
105 	[BPF_TRACE_FENTRY]		= "trace_fentry",
106 	[BPF_TRACE_FEXIT]		= "trace_fexit",
107 	[BPF_MODIFY_RETURN]		= "modify_return",
108 	[BPF_LSM_MAC]			= "lsm_mac",
109 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
110 	[BPF_SK_LOOKUP]			= "sk_lookup",
111 	[BPF_TRACE_ITER]		= "trace_iter",
112 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
113 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
114 	[BPF_XDP]			= "xdp",
115 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
116 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
117 	[BPF_PERF_EVENT]		= "perf_event",
118 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
119 };
120 
121 static const char * const link_type_name[] = {
122 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
123 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
124 	[BPF_LINK_TYPE_TRACING]			= "tracing",
125 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
126 	[BPF_LINK_TYPE_ITER]			= "iter",
127 	[BPF_LINK_TYPE_NETNS]			= "netns",
128 	[BPF_LINK_TYPE_XDP]			= "xdp",
129 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
130 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
131 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
132 };
133 
134 static const char * const map_type_name[] = {
135 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
136 	[BPF_MAP_TYPE_HASH]			= "hash",
137 	[BPF_MAP_TYPE_ARRAY]			= "array",
138 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
139 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
140 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
141 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
142 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
143 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
144 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
145 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
146 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
147 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
148 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
149 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
150 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
151 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
152 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
153 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
154 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
155 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
156 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
157 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
158 	[BPF_MAP_TYPE_QUEUE]			= "queue",
159 	[BPF_MAP_TYPE_STACK]			= "stack",
160 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
161 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
162 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
163 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
164 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
165 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
166 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
167 };
168 
169 static const char * const prog_type_name[] = {
170 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
171 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
172 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
173 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
174 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
175 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
176 	[BPF_PROG_TYPE_XDP]			= "xdp",
177 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
178 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
179 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
180 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
181 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
182 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
183 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
184 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
185 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
186 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
187 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
188 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
189 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
190 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
191 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
192 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
193 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
194 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
195 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
196 	[BPF_PROG_TYPE_TRACING]			= "tracing",
197 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
198 	[BPF_PROG_TYPE_EXT]			= "ext",
199 	[BPF_PROG_TYPE_LSM]			= "lsm",
200 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
201 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
202 };
203 
__base_pr(enum libbpf_print_level level,const char * format,va_list args)204 static int __base_pr(enum libbpf_print_level level, const char *format,
205 		     va_list args)
206 {
207 	if (level == LIBBPF_DEBUG)
208 		return 0;
209 
210 	return vfprintf(stderr, format, args);
211 }
212 
213 static libbpf_print_fn_t __libbpf_pr = __base_pr;
214 
libbpf_set_print(libbpf_print_fn_t fn)215 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
216 {
217 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
218 
219 	__libbpf_pr = fn;
220 	return old_print_fn;
221 }
222 
223 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)224 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
225 {
226 	va_list args;
227 	int old_errno;
228 
229 	if (!__libbpf_pr)
230 		return;
231 
232 	old_errno = errno;
233 
234 	va_start(args, format);
235 	__libbpf_pr(level, format, args);
236 	va_end(args);
237 
238 	errno = old_errno;
239 }
240 
pr_perm_msg(int err)241 static void pr_perm_msg(int err)
242 {
243 	struct rlimit limit;
244 	char buf[100];
245 
246 	if (err != -EPERM || geteuid() != 0)
247 		return;
248 
249 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
250 	if (err)
251 		return;
252 
253 	if (limit.rlim_cur == RLIM_INFINITY)
254 		return;
255 
256 	if (limit.rlim_cur < 1024)
257 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
258 	else if (limit.rlim_cur < 1024*1024)
259 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
260 	else
261 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
262 
263 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
264 		buf);
265 }
266 
267 #define STRERR_BUFSIZE  128
268 
269 /* Copied from tools/perf/util/util.h */
270 #ifndef zfree
271 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
272 #endif
273 
274 #ifndef zclose
275 # define zclose(fd) ({			\
276 	int ___err = 0;			\
277 	if ((fd) >= 0)			\
278 		___err = close((fd));	\
279 	fd = -1;			\
280 	___err; })
281 #endif
282 
ptr_to_u64(const void * ptr)283 static inline __u64 ptr_to_u64(const void *ptr)
284 {
285 	return (__u64) (unsigned long) ptr;
286 }
287 
libbpf_set_strict_mode(enum libbpf_strict_mode mode)288 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
289 {
290 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
291 	return 0;
292 }
293 
libbpf_major_version(void)294 __u32 libbpf_major_version(void)
295 {
296 	return LIBBPF_MAJOR_VERSION;
297 }
298 
libbpf_minor_version(void)299 __u32 libbpf_minor_version(void)
300 {
301 	return LIBBPF_MINOR_VERSION;
302 }
303 
libbpf_version_string(void)304 const char *libbpf_version_string(void)
305 {
306 #define __S(X) #X
307 #define _S(X) __S(X)
308 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
309 #undef _S
310 #undef __S
311 }
312 
313 enum reloc_type {
314 	RELO_LD64,
315 	RELO_CALL,
316 	RELO_DATA,
317 	RELO_EXTERN_VAR,
318 	RELO_EXTERN_FUNC,
319 	RELO_SUBPROG_ADDR,
320 	RELO_CORE,
321 };
322 
323 struct reloc_desc {
324 	enum reloc_type type;
325 	int insn_idx;
326 	union {
327 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
328 		struct {
329 			int map_idx;
330 			int sym_off;
331 		};
332 	};
333 };
334 
335 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
336 enum sec_def_flags {
337 	SEC_NONE = 0,
338 	/* expected_attach_type is optional, if kernel doesn't support that */
339 	SEC_EXP_ATTACH_OPT = 1,
340 	/* legacy, only used by libbpf_get_type_names() and
341 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
342 	 * This used to be associated with cgroup (and few other) BPF programs
343 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
344 	 * meaningless nowadays, though.
345 	 */
346 	SEC_ATTACHABLE = 2,
347 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
348 	/* attachment target is specified through BTF ID in either kernel or
349 	 * other BPF program's BTF object */
350 	SEC_ATTACH_BTF = 4,
351 	/* BPF program type allows sleeping/blocking in kernel */
352 	SEC_SLEEPABLE = 8,
353 	/* BPF program support non-linear XDP buffer */
354 	SEC_XDP_FRAGS = 16,
355 };
356 
357 struct bpf_sec_def {
358 	char *sec;
359 	enum bpf_prog_type prog_type;
360 	enum bpf_attach_type expected_attach_type;
361 	long cookie;
362 	int handler_id;
363 
364 	libbpf_prog_setup_fn_t prog_setup_fn;
365 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
366 	libbpf_prog_attach_fn_t prog_attach_fn;
367 };
368 
369 /*
370  * bpf_prog should be a better name but it has been used in
371  * linux/filter.h.
372  */
373 struct bpf_program {
374 	char *name;
375 	char *sec_name;
376 	size_t sec_idx;
377 	const struct bpf_sec_def *sec_def;
378 	/* this program's instruction offset (in number of instructions)
379 	 * within its containing ELF section
380 	 */
381 	size_t sec_insn_off;
382 	/* number of original instructions in ELF section belonging to this
383 	 * program, not taking into account subprogram instructions possible
384 	 * appended later during relocation
385 	 */
386 	size_t sec_insn_cnt;
387 	/* Offset (in number of instructions) of the start of instruction
388 	 * belonging to this BPF program  within its containing main BPF
389 	 * program. For the entry-point (main) BPF program, this is always
390 	 * zero. For a sub-program, this gets reset before each of main BPF
391 	 * programs are processed and relocated and is used to determined
392 	 * whether sub-program was already appended to the main program, and
393 	 * if yes, at which instruction offset.
394 	 */
395 	size_t sub_insn_off;
396 
397 	/* instructions that belong to BPF program; insns[0] is located at
398 	 * sec_insn_off instruction within its ELF section in ELF file, so
399 	 * when mapping ELF file instruction index to the local instruction,
400 	 * one needs to subtract sec_insn_off; and vice versa.
401 	 */
402 	struct bpf_insn *insns;
403 	/* actual number of instruction in this BPF program's image; for
404 	 * entry-point BPF programs this includes the size of main program
405 	 * itself plus all the used sub-programs, appended at the end
406 	 */
407 	size_t insns_cnt;
408 
409 	struct reloc_desc *reloc_desc;
410 	int nr_reloc;
411 
412 	/* BPF verifier log settings */
413 	char *log_buf;
414 	size_t log_size;
415 	__u32 log_level;
416 
417 	struct bpf_object *obj;
418 
419 	int fd;
420 	bool autoload;
421 	bool autoattach;
422 	bool mark_btf_static;
423 	enum bpf_prog_type type;
424 	enum bpf_attach_type expected_attach_type;
425 
426 	int prog_ifindex;
427 	__u32 attach_btf_obj_fd;
428 	__u32 attach_btf_id;
429 	__u32 attach_prog_fd;
430 
431 	void *func_info;
432 	__u32 func_info_rec_size;
433 	__u32 func_info_cnt;
434 
435 	void *line_info;
436 	__u32 line_info_rec_size;
437 	__u32 line_info_cnt;
438 	__u32 prog_flags;
439 };
440 
441 struct bpf_struct_ops {
442 	const char *tname;
443 	const struct btf_type *type;
444 	struct bpf_program **progs;
445 	__u32 *kern_func_off;
446 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
447 	void *data;
448 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
449 	 *      btf_vmlinux's format.
450 	 * struct bpf_struct_ops_tcp_congestion_ops {
451 	 *	[... some other kernel fields ...]
452 	 *	struct tcp_congestion_ops data;
453 	 * }
454 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
455 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
456 	 * from "data".
457 	 */
458 	void *kern_vdata;
459 	__u32 type_id;
460 };
461 
462 #define DATA_SEC ".data"
463 #define BSS_SEC ".bss"
464 #define RODATA_SEC ".rodata"
465 #define KCONFIG_SEC ".kconfig"
466 #define KSYMS_SEC ".ksyms"
467 #define STRUCT_OPS_SEC ".struct_ops"
468 
469 enum libbpf_map_type {
470 	LIBBPF_MAP_UNSPEC,
471 	LIBBPF_MAP_DATA,
472 	LIBBPF_MAP_BSS,
473 	LIBBPF_MAP_RODATA,
474 	LIBBPF_MAP_KCONFIG,
475 };
476 
477 struct bpf_map_def {
478 	unsigned int type;
479 	unsigned int key_size;
480 	unsigned int value_size;
481 	unsigned int max_entries;
482 	unsigned int map_flags;
483 };
484 
485 struct bpf_map {
486 	struct bpf_object *obj;
487 	char *name;
488 	/* real_name is defined for special internal maps (.rodata*,
489 	 * .data*, .bss, .kconfig) and preserves their original ELF section
490 	 * name. This is important to be be able to find corresponding BTF
491 	 * DATASEC information.
492 	 */
493 	char *real_name;
494 	int fd;
495 	int sec_idx;
496 	size_t sec_offset;
497 	int map_ifindex;
498 	int inner_map_fd;
499 	struct bpf_map_def def;
500 	__u32 numa_node;
501 	__u32 btf_var_idx;
502 	__u32 btf_key_type_id;
503 	__u32 btf_value_type_id;
504 	__u32 btf_vmlinux_value_type_id;
505 	enum libbpf_map_type libbpf_type;
506 	void *mmaped;
507 	struct bpf_struct_ops *st_ops;
508 	struct bpf_map *inner_map;
509 	void **init_slots;
510 	int init_slots_sz;
511 	char *pin_path;
512 	bool pinned;
513 	bool reused;
514 	bool autocreate;
515 	__u64 map_extra;
516 };
517 
518 enum extern_type {
519 	EXT_UNKNOWN,
520 	EXT_KCFG,
521 	EXT_KSYM,
522 };
523 
524 enum kcfg_type {
525 	KCFG_UNKNOWN,
526 	KCFG_CHAR,
527 	KCFG_BOOL,
528 	KCFG_INT,
529 	KCFG_TRISTATE,
530 	KCFG_CHAR_ARR,
531 };
532 
533 struct extern_desc {
534 	enum extern_type type;
535 	int sym_idx;
536 	int btf_id;
537 	int sec_btf_id;
538 	const char *name;
539 	bool is_set;
540 	bool is_weak;
541 	union {
542 		struct {
543 			enum kcfg_type type;
544 			int sz;
545 			int align;
546 			int data_off;
547 			bool is_signed;
548 		} kcfg;
549 		struct {
550 			unsigned long long addr;
551 
552 			/* target btf_id of the corresponding kernel var. */
553 			int kernel_btf_obj_fd;
554 			int kernel_btf_id;
555 
556 			/* local btf_id of the ksym extern's type. */
557 			__u32 type_id;
558 			/* BTF fd index to be patched in for insn->off, this is
559 			 * 0 for vmlinux BTF, index in obj->fd_array for module
560 			 * BTF
561 			 */
562 			__s16 btf_fd_idx;
563 		} ksym;
564 	};
565 };
566 
567 struct module_btf {
568 	struct btf *btf;
569 	char *name;
570 	__u32 id;
571 	int fd;
572 	int fd_array_idx;
573 };
574 
575 enum sec_type {
576 	SEC_UNUSED = 0,
577 	SEC_RELO,
578 	SEC_BSS,
579 	SEC_DATA,
580 	SEC_RODATA,
581 };
582 
583 struct elf_sec_desc {
584 	enum sec_type sec_type;
585 	Elf64_Shdr *shdr;
586 	Elf_Data *data;
587 };
588 
589 struct elf_state {
590 	int fd;
591 	const void *obj_buf;
592 	size_t obj_buf_sz;
593 	Elf *elf;
594 	Elf64_Ehdr *ehdr;
595 	Elf_Data *symbols;
596 	Elf_Data *st_ops_data;
597 	size_t shstrndx; /* section index for section name strings */
598 	size_t strtabidx;
599 	struct elf_sec_desc *secs;
600 	size_t sec_cnt;
601 	int btf_maps_shndx;
602 	__u32 btf_maps_sec_btf_id;
603 	int text_shndx;
604 	int symbols_shndx;
605 	int st_ops_shndx;
606 };
607 
608 struct usdt_manager;
609 
610 struct bpf_object {
611 	char name[BPF_OBJ_NAME_LEN];
612 	char license[64];
613 	__u32 kern_version;
614 
615 	struct bpf_program *programs;
616 	size_t nr_programs;
617 	struct bpf_map *maps;
618 	size_t nr_maps;
619 	size_t maps_cap;
620 
621 	char *kconfig;
622 	struct extern_desc *externs;
623 	int nr_extern;
624 	int kconfig_map_idx;
625 
626 	bool loaded;
627 	bool has_subcalls;
628 	bool has_rodata;
629 
630 	struct bpf_gen *gen_loader;
631 
632 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
633 	struct elf_state efile;
634 
635 	struct btf *btf;
636 	struct btf_ext *btf_ext;
637 
638 	/* Parse and load BTF vmlinux if any of the programs in the object need
639 	 * it at load time.
640 	 */
641 	struct btf *btf_vmlinux;
642 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
643 	 * override for vmlinux BTF.
644 	 */
645 	char *btf_custom_path;
646 	/* vmlinux BTF override for CO-RE relocations */
647 	struct btf *btf_vmlinux_override;
648 	/* Lazily initialized kernel module BTFs */
649 	struct module_btf *btf_modules;
650 	bool btf_modules_loaded;
651 	size_t btf_module_cnt;
652 	size_t btf_module_cap;
653 
654 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
655 	char *log_buf;
656 	size_t log_size;
657 	__u32 log_level;
658 
659 	int *fd_array;
660 	size_t fd_array_cap;
661 	size_t fd_array_cnt;
662 
663 	struct usdt_manager *usdt_man;
664 
665 	char path[];
666 };
667 
668 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
669 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
670 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
671 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
672 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
673 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
674 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
675 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
676 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
677 
bpf_program__unload(struct bpf_program * prog)678 void bpf_program__unload(struct bpf_program *prog)
679 {
680 	if (!prog)
681 		return;
682 
683 	zclose(prog->fd);
684 
685 	zfree(&prog->func_info);
686 	zfree(&prog->line_info);
687 }
688 
bpf_program__exit(struct bpf_program * prog)689 static void bpf_program__exit(struct bpf_program *prog)
690 {
691 	if (!prog)
692 		return;
693 
694 	bpf_program__unload(prog);
695 	zfree(&prog->name);
696 	zfree(&prog->sec_name);
697 	zfree(&prog->insns);
698 	zfree(&prog->reloc_desc);
699 
700 	prog->nr_reloc = 0;
701 	prog->insns_cnt = 0;
702 	prog->sec_idx = -1;
703 }
704 
insn_is_subprog_call(const struct bpf_insn * insn)705 static bool insn_is_subprog_call(const struct bpf_insn *insn)
706 {
707 	return BPF_CLASS(insn->code) == BPF_JMP &&
708 	       BPF_OP(insn->code) == BPF_CALL &&
709 	       BPF_SRC(insn->code) == BPF_K &&
710 	       insn->src_reg == BPF_PSEUDO_CALL &&
711 	       insn->dst_reg == 0 &&
712 	       insn->off == 0;
713 }
714 
is_call_insn(const struct bpf_insn * insn)715 static bool is_call_insn(const struct bpf_insn *insn)
716 {
717 	return insn->code == (BPF_JMP | BPF_CALL);
718 }
719 
insn_is_pseudo_func(struct bpf_insn * insn)720 static bool insn_is_pseudo_func(struct bpf_insn *insn)
721 {
722 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
723 }
724 
725 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)726 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
727 		      const char *name, size_t sec_idx, const char *sec_name,
728 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
729 {
730 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
731 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
732 			sec_name, name, sec_off, insn_data_sz);
733 		return -EINVAL;
734 	}
735 
736 	memset(prog, 0, sizeof(*prog));
737 	prog->obj = obj;
738 
739 	prog->sec_idx = sec_idx;
740 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
741 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
742 	/* insns_cnt can later be increased by appending used subprograms */
743 	prog->insns_cnt = prog->sec_insn_cnt;
744 
745 	prog->type = BPF_PROG_TYPE_UNSPEC;
746 	prog->fd = -1;
747 
748 	/* libbpf's convention for SEC("?abc...") is that it's just like
749 	 * SEC("abc...") but the corresponding bpf_program starts out with
750 	 * autoload set to false.
751 	 */
752 	if (sec_name[0] == '?') {
753 		prog->autoload = false;
754 		/* from now on forget there was ? in section name */
755 		sec_name++;
756 	} else {
757 		prog->autoload = true;
758 	}
759 
760 	prog->autoattach = true;
761 
762 	/* inherit object's log_level */
763 	prog->log_level = obj->log_level;
764 
765 	prog->sec_name = strdup(sec_name);
766 	if (!prog->sec_name)
767 		goto errout;
768 
769 	prog->name = strdup(name);
770 	if (!prog->name)
771 		goto errout;
772 
773 	prog->insns = malloc(insn_data_sz);
774 	if (!prog->insns)
775 		goto errout;
776 	memcpy(prog->insns, insn_data, insn_data_sz);
777 
778 	return 0;
779 errout:
780 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
781 	bpf_program__exit(prog);
782 	return -ENOMEM;
783 }
784 
785 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)786 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
787 			 const char *sec_name, int sec_idx)
788 {
789 	Elf_Data *symbols = obj->efile.symbols;
790 	struct bpf_program *prog, *progs;
791 	void *data = sec_data->d_buf;
792 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
793 	int nr_progs, err, i;
794 	const char *name;
795 	Elf64_Sym *sym;
796 
797 	progs = obj->programs;
798 	nr_progs = obj->nr_programs;
799 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
800 	sec_off = 0;
801 
802 	for (i = 0; i < nr_syms; i++) {
803 		sym = elf_sym_by_idx(obj, i);
804 
805 		if (sym->st_shndx != sec_idx)
806 			continue;
807 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
808 			continue;
809 
810 		prog_sz = sym->st_size;
811 		sec_off = sym->st_value;
812 
813 		name = elf_sym_str(obj, sym->st_name);
814 		if (!name) {
815 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
816 				sec_name, sec_off);
817 			return -LIBBPF_ERRNO__FORMAT;
818 		}
819 
820 		if (sec_off + prog_sz > sec_sz) {
821 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
822 				sec_name, sec_off);
823 			return -LIBBPF_ERRNO__FORMAT;
824 		}
825 
826 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
827 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
828 			return -ENOTSUP;
829 		}
830 
831 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
832 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
833 
834 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
835 		if (!progs) {
836 			/*
837 			 * In this case the original obj->programs
838 			 * is still valid, so don't need special treat for
839 			 * bpf_close_object().
840 			 */
841 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
842 				sec_name, name);
843 			return -ENOMEM;
844 		}
845 		obj->programs = progs;
846 
847 		prog = &progs[nr_progs];
848 
849 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
850 					    sec_off, data + sec_off, prog_sz);
851 		if (err)
852 			return err;
853 
854 		/* if function is a global/weak symbol, but has restricted
855 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
856 		 * as static to enable more permissive BPF verification mode
857 		 * with more outside context available to BPF verifier
858 		 */
859 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
860 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
861 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
862 			prog->mark_btf_static = true;
863 
864 		nr_progs++;
865 		obj->nr_programs = nr_progs;
866 	}
867 
868 	return 0;
869 }
870 
get_kernel_version(void)871 __u32 get_kernel_version(void)
872 {
873 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
874 	 * but Ubuntu provides /proc/version_signature file, as described at
875 	 * https://ubuntu.com/kernel, with an example contents below, which we
876 	 * can use to get a proper LINUX_VERSION_CODE.
877 	 *
878 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
879 	 *
880 	 * In the above, 5.4.8 is what kernel is actually expecting, while
881 	 * uname() call will return 5.4.0 in info.release.
882 	 */
883 	const char *ubuntu_kver_file = "/proc/version_signature";
884 	__u32 major, minor, patch;
885 	struct utsname info;
886 
887 	if (faccessat(AT_FDCWD, ubuntu_kver_file, R_OK, AT_EACCESS) == 0) {
888 		FILE *f;
889 
890 		f = fopen(ubuntu_kver_file, "r");
891 		if (f) {
892 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
893 				fclose(f);
894 				return KERNEL_VERSION(major, minor, patch);
895 			}
896 			fclose(f);
897 		}
898 		/* something went wrong, fall back to uname() approach */
899 	}
900 
901 	uname(&info);
902 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
903 		return 0;
904 	return KERNEL_VERSION(major, minor, patch);
905 }
906 
907 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)908 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
909 {
910 	struct btf_member *m;
911 	int i;
912 
913 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
914 		if (btf_member_bit_offset(t, i) == bit_offset)
915 			return m;
916 	}
917 
918 	return NULL;
919 }
920 
921 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)922 find_member_by_name(const struct btf *btf, const struct btf_type *t,
923 		    const char *name)
924 {
925 	struct btf_member *m;
926 	int i;
927 
928 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
929 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
930 			return m;
931 	}
932 
933 	return NULL;
934 }
935 
936 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
937 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
938 				   const char *name, __u32 kind);
939 
940 static int
find_struct_ops_kern_types(const struct btf * btf,const char * tname,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)941 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
942 			   const struct btf_type **type, __u32 *type_id,
943 			   const struct btf_type **vtype, __u32 *vtype_id,
944 			   const struct btf_member **data_member)
945 {
946 	const struct btf_type *kern_type, *kern_vtype;
947 	const struct btf_member *kern_data_member;
948 	__s32 kern_vtype_id, kern_type_id;
949 	__u32 i;
950 
951 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
952 	if (kern_type_id < 0) {
953 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
954 			tname);
955 		return kern_type_id;
956 	}
957 	kern_type = btf__type_by_id(btf, kern_type_id);
958 
959 	/* Find the corresponding "map_value" type that will be used
960 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
961 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
962 	 * btf_vmlinux.
963 	 */
964 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
965 						tname, BTF_KIND_STRUCT);
966 	if (kern_vtype_id < 0) {
967 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
968 			STRUCT_OPS_VALUE_PREFIX, tname);
969 		return kern_vtype_id;
970 	}
971 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
972 
973 	/* Find "struct tcp_congestion_ops" from
974 	 * struct bpf_struct_ops_tcp_congestion_ops {
975 	 *	[ ... ]
976 	 *	struct tcp_congestion_ops data;
977 	 * }
978 	 */
979 	kern_data_member = btf_members(kern_vtype);
980 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
981 		if (kern_data_member->type == kern_type_id)
982 			break;
983 	}
984 	if (i == btf_vlen(kern_vtype)) {
985 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
986 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
987 		return -EINVAL;
988 	}
989 
990 	*type = kern_type;
991 	*type_id = kern_type_id;
992 	*vtype = kern_vtype;
993 	*vtype_id = kern_vtype_id;
994 	*data_member = kern_data_member;
995 
996 	return 0;
997 }
998 
bpf_map__is_struct_ops(const struct bpf_map * map)999 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1000 {
1001 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1002 }
1003 
1004 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map,const struct btf * btf,const struct btf * kern_btf)1005 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1006 					 const struct btf *btf,
1007 					 const struct btf *kern_btf)
1008 {
1009 	const struct btf_member *member, *kern_member, *kern_data_member;
1010 	const struct btf_type *type, *kern_type, *kern_vtype;
1011 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1012 	struct bpf_struct_ops *st_ops;
1013 	void *data, *kern_data;
1014 	const char *tname;
1015 	int err;
1016 
1017 	st_ops = map->st_ops;
1018 	type = st_ops->type;
1019 	tname = st_ops->tname;
1020 	err = find_struct_ops_kern_types(kern_btf, tname,
1021 					 &kern_type, &kern_type_id,
1022 					 &kern_vtype, &kern_vtype_id,
1023 					 &kern_data_member);
1024 	if (err)
1025 		return err;
1026 
1027 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1028 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1029 
1030 	map->def.value_size = kern_vtype->size;
1031 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1032 
1033 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1034 	if (!st_ops->kern_vdata)
1035 		return -ENOMEM;
1036 
1037 	data = st_ops->data;
1038 	kern_data_off = kern_data_member->offset / 8;
1039 	kern_data = st_ops->kern_vdata + kern_data_off;
1040 
1041 	member = btf_members(type);
1042 	for (i = 0; i < btf_vlen(type); i++, member++) {
1043 		const struct btf_type *mtype, *kern_mtype;
1044 		__u32 mtype_id, kern_mtype_id;
1045 		void *mdata, *kern_mdata;
1046 		__s64 msize, kern_msize;
1047 		__u32 moff, kern_moff;
1048 		__u32 kern_member_idx;
1049 		const char *mname;
1050 
1051 		mname = btf__name_by_offset(btf, member->name_off);
1052 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1053 		if (!kern_member) {
1054 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1055 				map->name, mname);
1056 			return -ENOTSUP;
1057 		}
1058 
1059 		kern_member_idx = kern_member - btf_members(kern_type);
1060 		if (btf_member_bitfield_size(type, i) ||
1061 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1062 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1063 				map->name, mname);
1064 			return -ENOTSUP;
1065 		}
1066 
1067 		moff = member->offset / 8;
1068 		kern_moff = kern_member->offset / 8;
1069 
1070 		mdata = data + moff;
1071 		kern_mdata = kern_data + kern_moff;
1072 
1073 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1074 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1075 						    &kern_mtype_id);
1076 		if (BTF_INFO_KIND(mtype->info) !=
1077 		    BTF_INFO_KIND(kern_mtype->info)) {
1078 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1079 				map->name, mname, BTF_INFO_KIND(mtype->info),
1080 				BTF_INFO_KIND(kern_mtype->info));
1081 			return -ENOTSUP;
1082 		}
1083 
1084 		if (btf_is_ptr(mtype)) {
1085 			struct bpf_program *prog;
1086 
1087 			prog = st_ops->progs[i];
1088 			if (!prog)
1089 				continue;
1090 
1091 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1092 							    kern_mtype->type,
1093 							    &kern_mtype_id);
1094 
1095 			/* mtype->type must be a func_proto which was
1096 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1097 			 * so only check kern_mtype for func_proto here.
1098 			 */
1099 			if (!btf_is_func_proto(kern_mtype)) {
1100 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1101 					map->name, mname);
1102 				return -ENOTSUP;
1103 			}
1104 
1105 			prog->attach_btf_id = kern_type_id;
1106 			prog->expected_attach_type = kern_member_idx;
1107 
1108 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1109 
1110 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1111 				 map->name, mname, prog->name, moff,
1112 				 kern_moff);
1113 
1114 			continue;
1115 		}
1116 
1117 		msize = btf__resolve_size(btf, mtype_id);
1118 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1119 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1120 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1121 				map->name, mname, (ssize_t)msize,
1122 				(ssize_t)kern_msize);
1123 			return -ENOTSUP;
1124 		}
1125 
1126 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1127 			 map->name, mname, (unsigned int)msize,
1128 			 moff, kern_moff);
1129 		memcpy(kern_mdata, mdata, msize);
1130 	}
1131 
1132 	return 0;
1133 }
1134 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1135 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1136 {
1137 	struct bpf_map *map;
1138 	size_t i;
1139 	int err;
1140 
1141 	for (i = 0; i < obj->nr_maps; i++) {
1142 		map = &obj->maps[i];
1143 
1144 		if (!bpf_map__is_struct_ops(map))
1145 			continue;
1146 
1147 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1148 						    obj->btf_vmlinux);
1149 		if (err)
1150 			return err;
1151 	}
1152 
1153 	return 0;
1154 }
1155 
bpf_object__init_struct_ops_maps(struct bpf_object * obj)1156 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1157 {
1158 	const struct btf_type *type, *datasec;
1159 	const struct btf_var_secinfo *vsi;
1160 	struct bpf_struct_ops *st_ops;
1161 	const char *tname, *var_name;
1162 	__s32 type_id, datasec_id;
1163 	const struct btf *btf;
1164 	struct bpf_map *map;
1165 	__u32 i;
1166 
1167 	if (obj->efile.st_ops_shndx == -1)
1168 		return 0;
1169 
1170 	btf = obj->btf;
1171 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1172 					    BTF_KIND_DATASEC);
1173 	if (datasec_id < 0) {
1174 		pr_warn("struct_ops init: DATASEC %s not found\n",
1175 			STRUCT_OPS_SEC);
1176 		return -EINVAL;
1177 	}
1178 
1179 	datasec = btf__type_by_id(btf, datasec_id);
1180 	vsi = btf_var_secinfos(datasec);
1181 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1182 		type = btf__type_by_id(obj->btf, vsi->type);
1183 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1184 
1185 		type_id = btf__resolve_type(obj->btf, vsi->type);
1186 		if (type_id < 0) {
1187 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1188 				vsi->type, STRUCT_OPS_SEC);
1189 			return -EINVAL;
1190 		}
1191 
1192 		type = btf__type_by_id(obj->btf, type_id);
1193 		tname = btf__name_by_offset(obj->btf, type->name_off);
1194 		if (!tname[0]) {
1195 			pr_warn("struct_ops init: anonymous type is not supported\n");
1196 			return -ENOTSUP;
1197 		}
1198 		if (!btf_is_struct(type)) {
1199 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1200 			return -EINVAL;
1201 		}
1202 
1203 		map = bpf_object__add_map(obj);
1204 		if (IS_ERR(map))
1205 			return PTR_ERR(map);
1206 
1207 		map->sec_idx = obj->efile.st_ops_shndx;
1208 		map->sec_offset = vsi->offset;
1209 		map->name = strdup(var_name);
1210 		if (!map->name)
1211 			return -ENOMEM;
1212 
1213 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1214 		map->def.key_size = sizeof(int);
1215 		map->def.value_size = type->size;
1216 		map->def.max_entries = 1;
1217 
1218 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1219 		if (!map->st_ops)
1220 			return -ENOMEM;
1221 		st_ops = map->st_ops;
1222 		st_ops->data = malloc(type->size);
1223 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1224 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1225 					       sizeof(*st_ops->kern_func_off));
1226 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1227 			return -ENOMEM;
1228 
1229 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1230 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1231 				var_name, STRUCT_OPS_SEC);
1232 			return -EINVAL;
1233 		}
1234 
1235 		memcpy(st_ops->data,
1236 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1237 		       type->size);
1238 		st_ops->tname = tname;
1239 		st_ops->type = type;
1240 		st_ops->type_id = type_id;
1241 
1242 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1243 			 tname, type_id, var_name, vsi->offset);
1244 	}
1245 
1246 	return 0;
1247 }
1248 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1249 static struct bpf_object *bpf_object__new(const char *path,
1250 					  const void *obj_buf,
1251 					  size_t obj_buf_sz,
1252 					  const char *obj_name)
1253 {
1254 	struct bpf_object *obj;
1255 	char *end;
1256 
1257 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1258 	if (!obj) {
1259 		pr_warn("alloc memory failed for %s\n", path);
1260 		return ERR_PTR(-ENOMEM);
1261 	}
1262 
1263 	strcpy(obj->path, path);
1264 	if (obj_name) {
1265 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1266 	} else {
1267 		/* Using basename() GNU version which doesn't modify arg. */
1268 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1269 		end = strchr(obj->name, '.');
1270 		if (end)
1271 			*end = 0;
1272 	}
1273 
1274 	obj->efile.fd = -1;
1275 	/*
1276 	 * Caller of this function should also call
1277 	 * bpf_object__elf_finish() after data collection to return
1278 	 * obj_buf to user. If not, we should duplicate the buffer to
1279 	 * avoid user freeing them before elf finish.
1280 	 */
1281 	obj->efile.obj_buf = obj_buf;
1282 	obj->efile.obj_buf_sz = obj_buf_sz;
1283 	obj->efile.btf_maps_shndx = -1;
1284 	obj->efile.st_ops_shndx = -1;
1285 	obj->kconfig_map_idx = -1;
1286 
1287 	obj->kern_version = get_kernel_version();
1288 	obj->loaded = false;
1289 
1290 	return obj;
1291 }
1292 
bpf_object__elf_finish(struct bpf_object * obj)1293 static void bpf_object__elf_finish(struct bpf_object *obj)
1294 {
1295 	if (!obj->efile.elf)
1296 		return;
1297 
1298 	elf_end(obj->efile.elf);
1299 	obj->efile.elf = NULL;
1300 	obj->efile.symbols = NULL;
1301 	obj->efile.st_ops_data = NULL;
1302 
1303 	zfree(&obj->efile.secs);
1304 	obj->efile.sec_cnt = 0;
1305 	zclose(obj->efile.fd);
1306 	obj->efile.obj_buf = NULL;
1307 	obj->efile.obj_buf_sz = 0;
1308 }
1309 
bpf_object__elf_init(struct bpf_object * obj)1310 static int bpf_object__elf_init(struct bpf_object *obj)
1311 {
1312 	Elf64_Ehdr *ehdr;
1313 	int err = 0;
1314 	Elf *elf;
1315 
1316 	if (obj->efile.elf) {
1317 		pr_warn("elf: init internal error\n");
1318 		return -LIBBPF_ERRNO__LIBELF;
1319 	}
1320 
1321 	if (obj->efile.obj_buf_sz > 0) {
1322 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1323 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1324 	} else {
1325 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1326 		if (obj->efile.fd < 0) {
1327 			char errmsg[STRERR_BUFSIZE], *cp;
1328 
1329 			err = -errno;
1330 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1331 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1332 			return err;
1333 		}
1334 
1335 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1336 	}
1337 
1338 	if (!elf) {
1339 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1340 		err = -LIBBPF_ERRNO__LIBELF;
1341 		goto errout;
1342 	}
1343 
1344 	obj->efile.elf = elf;
1345 
1346 	if (elf_kind(elf) != ELF_K_ELF) {
1347 		err = -LIBBPF_ERRNO__FORMAT;
1348 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1349 		goto errout;
1350 	}
1351 
1352 	if (gelf_getclass(elf) != ELFCLASS64) {
1353 		err = -LIBBPF_ERRNO__FORMAT;
1354 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1355 		goto errout;
1356 	}
1357 
1358 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1359 	if (!obj->efile.ehdr) {
1360 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1361 		err = -LIBBPF_ERRNO__FORMAT;
1362 		goto errout;
1363 	}
1364 
1365 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1366 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1367 			obj->path, elf_errmsg(-1));
1368 		err = -LIBBPF_ERRNO__FORMAT;
1369 		goto errout;
1370 	}
1371 
1372 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1373 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1374 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1375 			obj->path, elf_errmsg(-1));
1376 		err = -LIBBPF_ERRNO__FORMAT;
1377 		goto errout;
1378 	}
1379 
1380 	/* Old LLVM set e_machine to EM_NONE */
1381 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1382 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1383 		err = -LIBBPF_ERRNO__FORMAT;
1384 		goto errout;
1385 	}
1386 
1387 	return 0;
1388 errout:
1389 	bpf_object__elf_finish(obj);
1390 	return err;
1391 }
1392 
bpf_object__check_endianness(struct bpf_object * obj)1393 static int bpf_object__check_endianness(struct bpf_object *obj)
1394 {
1395 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1396 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1397 		return 0;
1398 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1399 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1400 		return 0;
1401 #else
1402 # error "Unrecognized __BYTE_ORDER__"
1403 #endif
1404 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1405 	return -LIBBPF_ERRNO__ENDIAN;
1406 }
1407 
1408 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1409 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1410 {
1411 	if (!data) {
1412 		pr_warn("invalid license section in %s\n", obj->path);
1413 		return -LIBBPF_ERRNO__FORMAT;
1414 	}
1415 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1416 	 * go over allowed ELF data section buffer
1417 	 */
1418 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1419 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1420 	return 0;
1421 }
1422 
1423 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1424 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1425 {
1426 	__u32 kver;
1427 
1428 	if (!data || size != sizeof(kver)) {
1429 		pr_warn("invalid kver section in %s\n", obj->path);
1430 		return -LIBBPF_ERRNO__FORMAT;
1431 	}
1432 	memcpy(&kver, data, sizeof(kver));
1433 	obj->kern_version = kver;
1434 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1435 	return 0;
1436 }
1437 
bpf_map_type__is_map_in_map(enum bpf_map_type type)1438 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1439 {
1440 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1441 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1442 		return true;
1443 	return false;
1444 }
1445 
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1446 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1447 {
1448 	Elf_Data *data;
1449 	Elf_Scn *scn;
1450 
1451 	if (!name)
1452 		return -EINVAL;
1453 
1454 	scn = elf_sec_by_name(obj, name);
1455 	data = elf_sec_data(obj, scn);
1456 	if (data) {
1457 		*size = data->d_size;
1458 		return 0; /* found it */
1459 	}
1460 
1461 	return -ENOENT;
1462 }
1463 
find_elf_var_offset(const struct bpf_object * obj,const char * name,__u32 * off)1464 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1465 {
1466 	Elf_Data *symbols = obj->efile.symbols;
1467 	const char *sname;
1468 	size_t si;
1469 
1470 	if (!name || !off)
1471 		return -EINVAL;
1472 
1473 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1474 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1475 
1476 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1477 			continue;
1478 
1479 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1480 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1481 			continue;
1482 
1483 		sname = elf_sym_str(obj, sym->st_name);
1484 		if (!sname) {
1485 			pr_warn("failed to get sym name string for var %s\n", name);
1486 			return -EIO;
1487 		}
1488 		if (strcmp(name, sname) == 0) {
1489 			*off = sym->st_value;
1490 			return 0;
1491 		}
1492 	}
1493 
1494 	return -ENOENT;
1495 }
1496 
bpf_object__add_map(struct bpf_object * obj)1497 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1498 {
1499 	struct bpf_map *map;
1500 	int err;
1501 
1502 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1503 				sizeof(*obj->maps), obj->nr_maps + 1);
1504 	if (err)
1505 		return ERR_PTR(err);
1506 
1507 	map = &obj->maps[obj->nr_maps++];
1508 	map->obj = obj;
1509 	map->fd = -1;
1510 	map->inner_map_fd = -1;
1511 	map->autocreate = true;
1512 
1513 	return map;
1514 }
1515 
bpf_map_mmap_sz(const struct bpf_map * map)1516 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1517 {
1518 	long page_sz = sysconf(_SC_PAGE_SIZE);
1519 	size_t map_sz;
1520 
1521 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1522 	map_sz = roundup(map_sz, page_sz);
1523 	return map_sz;
1524 }
1525 
internal_map_name(struct bpf_object * obj,const char * real_name)1526 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1527 {
1528 	char map_name[BPF_OBJ_NAME_LEN], *p;
1529 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1530 
1531 	/* This is one of the more confusing parts of libbpf for various
1532 	 * reasons, some of which are historical. The original idea for naming
1533 	 * internal names was to include as much of BPF object name prefix as
1534 	 * possible, so that it can be distinguished from similar internal
1535 	 * maps of a different BPF object.
1536 	 * As an example, let's say we have bpf_object named 'my_object_name'
1537 	 * and internal map corresponding to '.rodata' ELF section. The final
1538 	 * map name advertised to user and to the kernel will be
1539 	 * 'my_objec.rodata', taking first 8 characters of object name and
1540 	 * entire 7 characters of '.rodata'.
1541 	 * Somewhat confusingly, if internal map ELF section name is shorter
1542 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1543 	 * for the suffix, even though we only have 4 actual characters, and
1544 	 * resulting map will be called 'my_objec.bss', not even using all 15
1545 	 * characters allowed by the kernel. Oh well, at least the truncated
1546 	 * object name is somewhat consistent in this case. But if the map
1547 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1548 	 * (8 chars) and thus will be left with only first 7 characters of the
1549 	 * object name ('my_obje'). Happy guessing, user, that the final map
1550 	 * name will be "my_obje.kconfig".
1551 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1552 	 * and .data.* data sections, it's possible that ELF section name is
1553 	 * longer than allowed 15 chars, so we now need to be careful to take
1554 	 * only up to 15 first characters of ELF name, taking no BPF object
1555 	 * name characters at all. So '.rodata.abracadabra' will result in
1556 	 * '.rodata.abracad' kernel and user-visible name.
1557 	 * We need to keep this convoluted logic intact for .data, .bss and
1558 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1559 	 * maps we use their ELF names as is, not prepending bpf_object name
1560 	 * in front. We still need to truncate them to 15 characters for the
1561 	 * kernel. Full name can be recovered for such maps by using DATASEC
1562 	 * BTF type associated with such map's value type, though.
1563 	 */
1564 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1565 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1566 
1567 	/* if there are two or more dots in map name, it's a custom dot map */
1568 	if (strchr(real_name + 1, '.') != NULL)
1569 		pfx_len = 0;
1570 	else
1571 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1572 
1573 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1574 		 sfx_len, real_name);
1575 
1576 	/* sanitise map name to characters allowed by kernel */
1577 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1578 		if (!isalnum(*p) && *p != '_' && *p != '.')
1579 			*p = '_';
1580 
1581 	return strdup(map_name);
1582 }
1583 
1584 static int
1585 bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1586 
1587 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)1588 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1589 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1590 {
1591 	struct bpf_map_def *def;
1592 	struct bpf_map *map;
1593 	int err;
1594 
1595 	map = bpf_object__add_map(obj);
1596 	if (IS_ERR(map))
1597 		return PTR_ERR(map);
1598 
1599 	map->libbpf_type = type;
1600 	map->sec_idx = sec_idx;
1601 	map->sec_offset = 0;
1602 	map->real_name = strdup(real_name);
1603 	map->name = internal_map_name(obj, real_name);
1604 	if (!map->real_name || !map->name) {
1605 		zfree(&map->real_name);
1606 		zfree(&map->name);
1607 		return -ENOMEM;
1608 	}
1609 
1610 	def = &map->def;
1611 	def->type = BPF_MAP_TYPE_ARRAY;
1612 	def->key_size = sizeof(int);
1613 	def->value_size = data_sz;
1614 	def->max_entries = 1;
1615 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1616 			 ? BPF_F_RDONLY_PROG : 0;
1617 	def->map_flags |= BPF_F_MMAPABLE;
1618 
1619 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1620 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1621 
1622 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1623 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1624 	if (map->mmaped == MAP_FAILED) {
1625 		err = -errno;
1626 		map->mmaped = NULL;
1627 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1628 			map->name, err);
1629 		zfree(&map->real_name);
1630 		zfree(&map->name);
1631 		return err;
1632 	}
1633 
1634 	/* failures are fine because of maps like .rodata.str1.1 */
1635 	(void) bpf_map_find_btf_info(obj, map);
1636 
1637 	if (data)
1638 		memcpy(map->mmaped, data, data_sz);
1639 
1640 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1641 	return 0;
1642 }
1643 
bpf_object__init_global_data_maps(struct bpf_object * obj)1644 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1645 {
1646 	struct elf_sec_desc *sec_desc;
1647 	const char *sec_name;
1648 	int err = 0, sec_idx;
1649 
1650 	/*
1651 	 * Populate obj->maps with libbpf internal maps.
1652 	 */
1653 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1654 		sec_desc = &obj->efile.secs[sec_idx];
1655 
1656 		/* Skip recognized sections with size 0. */
1657 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1658 			continue;
1659 
1660 		switch (sec_desc->sec_type) {
1661 		case SEC_DATA:
1662 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1663 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1664 							    sec_name, sec_idx,
1665 							    sec_desc->data->d_buf,
1666 							    sec_desc->data->d_size);
1667 			break;
1668 		case SEC_RODATA:
1669 			obj->has_rodata = true;
1670 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1671 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1672 							    sec_name, sec_idx,
1673 							    sec_desc->data->d_buf,
1674 							    sec_desc->data->d_size);
1675 			break;
1676 		case SEC_BSS:
1677 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1678 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1679 							    sec_name, sec_idx,
1680 							    NULL,
1681 							    sec_desc->data->d_size);
1682 			break;
1683 		default:
1684 			/* skip */
1685 			break;
1686 		}
1687 		if (err)
1688 			return err;
1689 	}
1690 	return 0;
1691 }
1692 
1693 
find_extern_by_name(const struct bpf_object * obj,const void * name)1694 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1695 					       const void *name)
1696 {
1697 	int i;
1698 
1699 	for (i = 0; i < obj->nr_extern; i++) {
1700 		if (strcmp(obj->externs[i].name, name) == 0)
1701 			return &obj->externs[i];
1702 	}
1703 	return NULL;
1704 }
1705 
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)1706 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1707 			      char value)
1708 {
1709 	switch (ext->kcfg.type) {
1710 	case KCFG_BOOL:
1711 		if (value == 'm') {
1712 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1713 				ext->name, value);
1714 			return -EINVAL;
1715 		}
1716 		*(bool *)ext_val = value == 'y' ? true : false;
1717 		break;
1718 	case KCFG_TRISTATE:
1719 		if (value == 'y')
1720 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1721 		else if (value == 'm')
1722 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1723 		else /* value == 'n' */
1724 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1725 		break;
1726 	case KCFG_CHAR:
1727 		*(char *)ext_val = value;
1728 		break;
1729 	case KCFG_UNKNOWN:
1730 	case KCFG_INT:
1731 	case KCFG_CHAR_ARR:
1732 	default:
1733 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1734 			ext->name, value);
1735 		return -EINVAL;
1736 	}
1737 	ext->is_set = true;
1738 	return 0;
1739 }
1740 
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)1741 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1742 			      const char *value)
1743 {
1744 	size_t len;
1745 
1746 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1747 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1748 			ext->name, value);
1749 		return -EINVAL;
1750 	}
1751 
1752 	len = strlen(value);
1753 	if (value[len - 1] != '"') {
1754 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1755 			ext->name, value);
1756 		return -EINVAL;
1757 	}
1758 
1759 	/* strip quotes */
1760 	len -= 2;
1761 	if (len >= ext->kcfg.sz) {
1762 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1763 			ext->name, value, len, ext->kcfg.sz - 1);
1764 		len = ext->kcfg.sz - 1;
1765 	}
1766 	memcpy(ext_val, value + 1, len);
1767 	ext_val[len] = '\0';
1768 	ext->is_set = true;
1769 	return 0;
1770 }
1771 
parse_u64(const char * value,__u64 * res)1772 static int parse_u64(const char *value, __u64 *res)
1773 {
1774 	char *value_end;
1775 	int err;
1776 
1777 	errno = 0;
1778 	*res = strtoull(value, &value_end, 0);
1779 	if (errno) {
1780 		err = -errno;
1781 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1782 		return err;
1783 	}
1784 	if (*value_end) {
1785 		pr_warn("failed to parse '%s' as integer completely\n", value);
1786 		return -EINVAL;
1787 	}
1788 	return 0;
1789 }
1790 
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)1791 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1792 {
1793 	int bit_sz = ext->kcfg.sz * 8;
1794 
1795 	if (ext->kcfg.sz == 8)
1796 		return true;
1797 
1798 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1799 	 * bytes size without any loss of information. If the target integer
1800 	 * is signed, we rely on the following limits of integer type of
1801 	 * Y bits and subsequent transformation:
1802 	 *
1803 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1804 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1805 	 *            0 <= X + 2^(Y-1) <  2^Y
1806 	 *
1807 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1808 	 *  zero.
1809 	 */
1810 	if (ext->kcfg.is_signed)
1811 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1812 	else
1813 		return (v >> bit_sz) == 0;
1814 }
1815 
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)1816 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1817 			      __u64 value)
1818 {
1819 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1820 	    ext->kcfg.type != KCFG_BOOL) {
1821 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1822 			ext->name, (unsigned long long)value);
1823 		return -EINVAL;
1824 	}
1825 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1826 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1827 			ext->name, (unsigned long long)value);
1828 		return -EINVAL;
1829 
1830 	}
1831 	if (!is_kcfg_value_in_range(ext, value)) {
1832 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1833 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1834 		return -ERANGE;
1835 	}
1836 	switch (ext->kcfg.sz) {
1837 		case 1: *(__u8 *)ext_val = value; break;
1838 		case 2: *(__u16 *)ext_val = value; break;
1839 		case 4: *(__u32 *)ext_val = value; break;
1840 		case 8: *(__u64 *)ext_val = value; break;
1841 		default:
1842 			return -EINVAL;
1843 	}
1844 	ext->is_set = true;
1845 	return 0;
1846 }
1847 
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)1848 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1849 					    char *buf, void *data)
1850 {
1851 	struct extern_desc *ext;
1852 	char *sep, *value;
1853 	int len, err = 0;
1854 	void *ext_val;
1855 	__u64 num;
1856 
1857 	if (!str_has_pfx(buf, "CONFIG_"))
1858 		return 0;
1859 
1860 	sep = strchr(buf, '=');
1861 	if (!sep) {
1862 		pr_warn("failed to parse '%s': no separator\n", buf);
1863 		return -EINVAL;
1864 	}
1865 
1866 	/* Trim ending '\n' */
1867 	len = strlen(buf);
1868 	if (buf[len - 1] == '\n')
1869 		buf[len - 1] = '\0';
1870 	/* Split on '=' and ensure that a value is present. */
1871 	*sep = '\0';
1872 	if (!sep[1]) {
1873 		*sep = '=';
1874 		pr_warn("failed to parse '%s': no value\n", buf);
1875 		return -EINVAL;
1876 	}
1877 
1878 	ext = find_extern_by_name(obj, buf);
1879 	if (!ext || ext->is_set)
1880 		return 0;
1881 
1882 	ext_val = data + ext->kcfg.data_off;
1883 	value = sep + 1;
1884 
1885 	switch (*value) {
1886 	case 'y': case 'n': case 'm':
1887 		err = set_kcfg_value_tri(ext, ext_val, *value);
1888 		break;
1889 	case '"':
1890 		err = set_kcfg_value_str(ext, ext_val, value);
1891 		break;
1892 	default:
1893 		/* assume integer */
1894 		err = parse_u64(value, &num);
1895 		if (err) {
1896 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1897 			return err;
1898 		}
1899 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1900 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1901 			return -EINVAL;
1902 		}
1903 		err = set_kcfg_value_num(ext, ext_val, num);
1904 		break;
1905 	}
1906 	if (err)
1907 		return err;
1908 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1909 	return 0;
1910 }
1911 
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)1912 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1913 {
1914 	char buf[PATH_MAX];
1915 	struct utsname uts;
1916 	int len, err = 0;
1917 	gzFile file;
1918 
1919 	uname(&uts);
1920 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1921 	if (len < 0)
1922 		return -EINVAL;
1923 	else if (len >= PATH_MAX)
1924 		return -ENAMETOOLONG;
1925 
1926 	/* gzopen also accepts uncompressed files. */
1927 	file = gzopen(buf, "r");
1928 	if (!file)
1929 		file = gzopen("/proc/config.gz", "r");
1930 
1931 	if (!file) {
1932 		pr_warn("failed to open system Kconfig\n");
1933 		return -ENOENT;
1934 	}
1935 
1936 	while (gzgets(file, buf, sizeof(buf))) {
1937 		err = bpf_object__process_kconfig_line(obj, buf, data);
1938 		if (err) {
1939 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1940 				buf, err);
1941 			goto out;
1942 		}
1943 	}
1944 
1945 out:
1946 	gzclose(file);
1947 	return err;
1948 }
1949 
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)1950 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1951 					const char *config, void *data)
1952 {
1953 	char buf[PATH_MAX];
1954 	int err = 0;
1955 	FILE *file;
1956 
1957 	file = fmemopen((void *)config, strlen(config), "r");
1958 	if (!file) {
1959 		err = -errno;
1960 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1961 		return err;
1962 	}
1963 
1964 	while (fgets(buf, sizeof(buf), file)) {
1965 		err = bpf_object__process_kconfig_line(obj, buf, data);
1966 		if (err) {
1967 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1968 				buf, err);
1969 			break;
1970 		}
1971 	}
1972 
1973 	fclose(file);
1974 	return err;
1975 }
1976 
bpf_object__init_kconfig_map(struct bpf_object * obj)1977 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1978 {
1979 	struct extern_desc *last_ext = NULL, *ext;
1980 	size_t map_sz;
1981 	int i, err;
1982 
1983 	for (i = 0; i < obj->nr_extern; i++) {
1984 		ext = &obj->externs[i];
1985 		if (ext->type == EXT_KCFG)
1986 			last_ext = ext;
1987 	}
1988 
1989 	if (!last_ext)
1990 		return 0;
1991 
1992 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1993 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1994 					    ".kconfig", obj->efile.symbols_shndx,
1995 					    NULL, map_sz);
1996 	if (err)
1997 		return err;
1998 
1999 	obj->kconfig_map_idx = obj->nr_maps - 1;
2000 
2001 	return 0;
2002 }
2003 
2004 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2005 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2006 {
2007 	const struct btf_type *t = btf__type_by_id(btf, id);
2008 
2009 	if (res_id)
2010 		*res_id = id;
2011 
2012 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2013 		if (res_id)
2014 			*res_id = t->type;
2015 		t = btf__type_by_id(btf, t->type);
2016 	}
2017 
2018 	return t;
2019 }
2020 
2021 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2022 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2023 {
2024 	const struct btf_type *t;
2025 
2026 	t = skip_mods_and_typedefs(btf, id, NULL);
2027 	if (!btf_is_ptr(t))
2028 		return NULL;
2029 
2030 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2031 
2032 	return btf_is_func_proto(t) ? t : NULL;
2033 }
2034 
__btf_kind_str(__u16 kind)2035 static const char *__btf_kind_str(__u16 kind)
2036 {
2037 	switch (kind) {
2038 	case BTF_KIND_UNKN: return "void";
2039 	case BTF_KIND_INT: return "int";
2040 	case BTF_KIND_PTR: return "ptr";
2041 	case BTF_KIND_ARRAY: return "array";
2042 	case BTF_KIND_STRUCT: return "struct";
2043 	case BTF_KIND_UNION: return "union";
2044 	case BTF_KIND_ENUM: return "enum";
2045 	case BTF_KIND_FWD: return "fwd";
2046 	case BTF_KIND_TYPEDEF: return "typedef";
2047 	case BTF_KIND_VOLATILE: return "volatile";
2048 	case BTF_KIND_CONST: return "const";
2049 	case BTF_KIND_RESTRICT: return "restrict";
2050 	case BTF_KIND_FUNC: return "func";
2051 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2052 	case BTF_KIND_VAR: return "var";
2053 	case BTF_KIND_DATASEC: return "datasec";
2054 	case BTF_KIND_FLOAT: return "float";
2055 	case BTF_KIND_DECL_TAG: return "decl_tag";
2056 	case BTF_KIND_TYPE_TAG: return "type_tag";
2057 	case BTF_KIND_ENUM64: return "enum64";
2058 	default: return "unknown";
2059 	}
2060 }
2061 
btf_kind_str(const struct btf_type * t)2062 const char *btf_kind_str(const struct btf_type *t)
2063 {
2064 	return __btf_kind_str(btf_kind(t));
2065 }
2066 
2067 /*
2068  * Fetch integer attribute of BTF map definition. Such attributes are
2069  * represented using a pointer to an array, in which dimensionality of array
2070  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2071  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2072  * type definition, while using only sizeof(void *) space in ELF data section.
2073  */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2074 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2075 			      const struct btf_member *m, __u32 *res)
2076 {
2077 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2078 	const char *name = btf__name_by_offset(btf, m->name_off);
2079 	const struct btf_array *arr_info;
2080 	const struct btf_type *arr_t;
2081 
2082 	if (!btf_is_ptr(t)) {
2083 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2084 			map_name, name, btf_kind_str(t));
2085 		return false;
2086 	}
2087 
2088 	arr_t = btf__type_by_id(btf, t->type);
2089 	if (!arr_t) {
2090 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2091 			map_name, name, t->type);
2092 		return false;
2093 	}
2094 	if (!btf_is_array(arr_t)) {
2095 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2096 			map_name, name, btf_kind_str(arr_t));
2097 		return false;
2098 	}
2099 	arr_info = btf_array(arr_t);
2100 	*res = arr_info->nelems;
2101 	return true;
2102 }
2103 
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2104 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2105 {
2106 	int len;
2107 
2108 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2109 	if (len < 0)
2110 		return -EINVAL;
2111 	if (len >= buf_sz)
2112 		return -ENAMETOOLONG;
2113 
2114 	return 0;
2115 }
2116 
build_map_pin_path(struct bpf_map * map,const char * path)2117 static int build_map_pin_path(struct bpf_map *map, const char *path)
2118 {
2119 	char buf[PATH_MAX];
2120 	int err;
2121 
2122 	if (!path)
2123 		path = "/sys/fs/bpf";
2124 
2125 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2126 	if (err)
2127 		return err;
2128 
2129 	return bpf_map__set_pin_path(map, buf);
2130 }
2131 
2132 /* should match definition in bpf_helpers.h */
2133 enum libbpf_pin_type {
2134 	LIBBPF_PIN_NONE,
2135 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2136 	LIBBPF_PIN_BY_NAME,
2137 };
2138 
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)2139 int parse_btf_map_def(const char *map_name, struct btf *btf,
2140 		      const struct btf_type *def_t, bool strict,
2141 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2142 {
2143 	const struct btf_type *t;
2144 	const struct btf_member *m;
2145 	bool is_inner = inner_def == NULL;
2146 	int vlen, i;
2147 
2148 	vlen = btf_vlen(def_t);
2149 	m = btf_members(def_t);
2150 	for (i = 0; i < vlen; i++, m++) {
2151 		const char *name = btf__name_by_offset(btf, m->name_off);
2152 
2153 		if (!name) {
2154 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2155 			return -EINVAL;
2156 		}
2157 		if (strcmp(name, "type") == 0) {
2158 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2159 				return -EINVAL;
2160 			map_def->parts |= MAP_DEF_MAP_TYPE;
2161 		} else if (strcmp(name, "max_entries") == 0) {
2162 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2163 				return -EINVAL;
2164 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2165 		} else if (strcmp(name, "map_flags") == 0) {
2166 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2167 				return -EINVAL;
2168 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2169 		} else if (strcmp(name, "numa_node") == 0) {
2170 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2171 				return -EINVAL;
2172 			map_def->parts |= MAP_DEF_NUMA_NODE;
2173 		} else if (strcmp(name, "key_size") == 0) {
2174 			__u32 sz;
2175 
2176 			if (!get_map_field_int(map_name, btf, m, &sz))
2177 				return -EINVAL;
2178 			if (map_def->key_size && map_def->key_size != sz) {
2179 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2180 					map_name, map_def->key_size, sz);
2181 				return -EINVAL;
2182 			}
2183 			map_def->key_size = sz;
2184 			map_def->parts |= MAP_DEF_KEY_SIZE;
2185 		} else if (strcmp(name, "key") == 0) {
2186 			__s64 sz;
2187 
2188 			t = btf__type_by_id(btf, m->type);
2189 			if (!t) {
2190 				pr_warn("map '%s': key type [%d] not found.\n",
2191 					map_name, m->type);
2192 				return -EINVAL;
2193 			}
2194 			if (!btf_is_ptr(t)) {
2195 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2196 					map_name, btf_kind_str(t));
2197 				return -EINVAL;
2198 			}
2199 			sz = btf__resolve_size(btf, t->type);
2200 			if (sz < 0) {
2201 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2202 					map_name, t->type, (ssize_t)sz);
2203 				return sz;
2204 			}
2205 			if (map_def->key_size && map_def->key_size != sz) {
2206 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2207 					map_name, map_def->key_size, (ssize_t)sz);
2208 				return -EINVAL;
2209 			}
2210 			map_def->key_size = sz;
2211 			map_def->key_type_id = t->type;
2212 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2213 		} else if (strcmp(name, "value_size") == 0) {
2214 			__u32 sz;
2215 
2216 			if (!get_map_field_int(map_name, btf, m, &sz))
2217 				return -EINVAL;
2218 			if (map_def->value_size && map_def->value_size != sz) {
2219 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2220 					map_name, map_def->value_size, sz);
2221 				return -EINVAL;
2222 			}
2223 			map_def->value_size = sz;
2224 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2225 		} else if (strcmp(name, "value") == 0) {
2226 			__s64 sz;
2227 
2228 			t = btf__type_by_id(btf, m->type);
2229 			if (!t) {
2230 				pr_warn("map '%s': value type [%d] not found.\n",
2231 					map_name, m->type);
2232 				return -EINVAL;
2233 			}
2234 			if (!btf_is_ptr(t)) {
2235 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2236 					map_name, btf_kind_str(t));
2237 				return -EINVAL;
2238 			}
2239 			sz = btf__resolve_size(btf, t->type);
2240 			if (sz < 0) {
2241 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2242 					map_name, t->type, (ssize_t)sz);
2243 				return sz;
2244 			}
2245 			if (map_def->value_size && map_def->value_size != sz) {
2246 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2247 					map_name, map_def->value_size, (ssize_t)sz);
2248 				return -EINVAL;
2249 			}
2250 			map_def->value_size = sz;
2251 			map_def->value_type_id = t->type;
2252 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2253 		}
2254 		else if (strcmp(name, "values") == 0) {
2255 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2256 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2257 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2258 			char inner_map_name[128];
2259 			int err;
2260 
2261 			if (is_inner) {
2262 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2263 					map_name);
2264 				return -ENOTSUP;
2265 			}
2266 			if (i != vlen - 1) {
2267 				pr_warn("map '%s': '%s' member should be last.\n",
2268 					map_name, name);
2269 				return -EINVAL;
2270 			}
2271 			if (!is_map_in_map && !is_prog_array) {
2272 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2273 					map_name);
2274 				return -ENOTSUP;
2275 			}
2276 			if (map_def->value_size && map_def->value_size != 4) {
2277 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2278 					map_name, map_def->value_size);
2279 				return -EINVAL;
2280 			}
2281 			map_def->value_size = 4;
2282 			t = btf__type_by_id(btf, m->type);
2283 			if (!t) {
2284 				pr_warn("map '%s': %s type [%d] not found.\n",
2285 					map_name, desc, m->type);
2286 				return -EINVAL;
2287 			}
2288 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2289 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2290 					map_name, desc);
2291 				return -EINVAL;
2292 			}
2293 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2294 			if (!btf_is_ptr(t)) {
2295 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2296 					map_name, desc, btf_kind_str(t));
2297 				return -EINVAL;
2298 			}
2299 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2300 			if (is_prog_array) {
2301 				if (!btf_is_func_proto(t)) {
2302 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2303 						map_name, btf_kind_str(t));
2304 					return -EINVAL;
2305 				}
2306 				continue;
2307 			}
2308 			if (!btf_is_struct(t)) {
2309 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2310 					map_name, btf_kind_str(t));
2311 				return -EINVAL;
2312 			}
2313 
2314 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2315 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2316 			if (err)
2317 				return err;
2318 
2319 			map_def->parts |= MAP_DEF_INNER_MAP;
2320 		} else if (strcmp(name, "pinning") == 0) {
2321 			__u32 val;
2322 
2323 			if (is_inner) {
2324 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2325 				return -EINVAL;
2326 			}
2327 			if (!get_map_field_int(map_name, btf, m, &val))
2328 				return -EINVAL;
2329 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2330 				pr_warn("map '%s': invalid pinning value %u.\n",
2331 					map_name, val);
2332 				return -EINVAL;
2333 			}
2334 			map_def->pinning = val;
2335 			map_def->parts |= MAP_DEF_PINNING;
2336 		} else if (strcmp(name, "map_extra") == 0) {
2337 			__u32 map_extra;
2338 
2339 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2340 				return -EINVAL;
2341 			map_def->map_extra = map_extra;
2342 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2343 		} else {
2344 			if (strict) {
2345 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2346 				return -ENOTSUP;
2347 			}
2348 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2349 		}
2350 	}
2351 
2352 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2353 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2354 		return -EINVAL;
2355 	}
2356 
2357 	return 0;
2358 }
2359 
adjust_ringbuf_sz(size_t sz)2360 static size_t adjust_ringbuf_sz(size_t sz)
2361 {
2362 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2363 	__u32 mul;
2364 
2365 	/* if user forgot to set any size, make sure they see error */
2366 	if (sz == 0)
2367 		return 0;
2368 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2369 	 * a power-of-2 multiple of kernel's page size. If user diligently
2370 	 * satisified these conditions, pass the size through.
2371 	 */
2372 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2373 		return sz;
2374 
2375 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2376 	 * user-set size to satisfy both user size request and kernel
2377 	 * requirements and substitute correct max_entries for map creation.
2378 	 */
2379 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2380 		if (mul * page_sz > sz)
2381 			return mul * page_sz;
2382 	}
2383 
2384 	/* if it's impossible to satisfy the conditions (i.e., user size is
2385 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2386 	 * page_size) then just return original size and let kernel reject it
2387 	 */
2388 	return sz;
2389 }
2390 
map_is_ringbuf(const struct bpf_map * map)2391 static bool map_is_ringbuf(const struct bpf_map *map)
2392 {
2393 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2394 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2395 }
2396 
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2397 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2398 {
2399 	map->def.type = def->map_type;
2400 	map->def.key_size = def->key_size;
2401 	map->def.value_size = def->value_size;
2402 	map->def.max_entries = def->max_entries;
2403 	map->def.map_flags = def->map_flags;
2404 	map->map_extra = def->map_extra;
2405 
2406 	map->numa_node = def->numa_node;
2407 	map->btf_key_type_id = def->key_type_id;
2408 	map->btf_value_type_id = def->value_type_id;
2409 
2410 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2411 	if (map_is_ringbuf(map))
2412 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2413 
2414 	if (def->parts & MAP_DEF_MAP_TYPE)
2415 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2416 
2417 	if (def->parts & MAP_DEF_KEY_TYPE)
2418 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2419 			 map->name, def->key_type_id, def->key_size);
2420 	else if (def->parts & MAP_DEF_KEY_SIZE)
2421 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2422 
2423 	if (def->parts & MAP_DEF_VALUE_TYPE)
2424 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2425 			 map->name, def->value_type_id, def->value_size);
2426 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2427 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2428 
2429 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2430 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2431 	if (def->parts & MAP_DEF_MAP_FLAGS)
2432 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2433 	if (def->parts & MAP_DEF_MAP_EXTRA)
2434 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2435 			 (unsigned long long)def->map_extra);
2436 	if (def->parts & MAP_DEF_PINNING)
2437 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2438 	if (def->parts & MAP_DEF_NUMA_NODE)
2439 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2440 
2441 	if (def->parts & MAP_DEF_INNER_MAP)
2442 		pr_debug("map '%s': found inner map definition.\n", map->name);
2443 }
2444 
btf_var_linkage_str(__u32 linkage)2445 static const char *btf_var_linkage_str(__u32 linkage)
2446 {
2447 	switch (linkage) {
2448 	case BTF_VAR_STATIC: return "static";
2449 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2450 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2451 	default: return "unknown";
2452 	}
2453 }
2454 
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)2455 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2456 					 const struct btf_type *sec,
2457 					 int var_idx, int sec_idx,
2458 					 const Elf_Data *data, bool strict,
2459 					 const char *pin_root_path)
2460 {
2461 	struct btf_map_def map_def = {}, inner_def = {};
2462 	const struct btf_type *var, *def;
2463 	const struct btf_var_secinfo *vi;
2464 	const struct btf_var *var_extra;
2465 	const char *map_name;
2466 	struct bpf_map *map;
2467 	int err;
2468 
2469 	vi = btf_var_secinfos(sec) + var_idx;
2470 	var = btf__type_by_id(obj->btf, vi->type);
2471 	var_extra = btf_var(var);
2472 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2473 
2474 	if (map_name == NULL || map_name[0] == '\0') {
2475 		pr_warn("map #%d: empty name.\n", var_idx);
2476 		return -EINVAL;
2477 	}
2478 	if ((__u64)vi->offset + vi->size > data->d_size) {
2479 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2480 		return -EINVAL;
2481 	}
2482 	if (!btf_is_var(var)) {
2483 		pr_warn("map '%s': unexpected var kind %s.\n",
2484 			map_name, btf_kind_str(var));
2485 		return -EINVAL;
2486 	}
2487 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2488 		pr_warn("map '%s': unsupported map linkage %s.\n",
2489 			map_name, btf_var_linkage_str(var_extra->linkage));
2490 		return -EOPNOTSUPP;
2491 	}
2492 
2493 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2494 	if (!btf_is_struct(def)) {
2495 		pr_warn("map '%s': unexpected def kind %s.\n",
2496 			map_name, btf_kind_str(var));
2497 		return -EINVAL;
2498 	}
2499 	if (def->size > vi->size) {
2500 		pr_warn("map '%s': invalid def size.\n", map_name);
2501 		return -EINVAL;
2502 	}
2503 
2504 	map = bpf_object__add_map(obj);
2505 	if (IS_ERR(map))
2506 		return PTR_ERR(map);
2507 	map->name = strdup(map_name);
2508 	if (!map->name) {
2509 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2510 		return -ENOMEM;
2511 	}
2512 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2513 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2514 	map->sec_idx = sec_idx;
2515 	map->sec_offset = vi->offset;
2516 	map->btf_var_idx = var_idx;
2517 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2518 		 map_name, map->sec_idx, map->sec_offset);
2519 
2520 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2521 	if (err)
2522 		return err;
2523 
2524 	fill_map_from_def(map, &map_def);
2525 
2526 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2527 		err = build_map_pin_path(map, pin_root_path);
2528 		if (err) {
2529 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2530 			return err;
2531 		}
2532 	}
2533 
2534 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2535 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2536 		if (!map->inner_map)
2537 			return -ENOMEM;
2538 		map->inner_map->fd = -1;
2539 		map->inner_map->sec_idx = sec_idx;
2540 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2541 		if (!map->inner_map->name)
2542 			return -ENOMEM;
2543 		sprintf(map->inner_map->name, "%s.inner", map_name);
2544 
2545 		fill_map_from_def(map->inner_map, &inner_def);
2546 	}
2547 
2548 	err = bpf_map_find_btf_info(obj, map);
2549 	if (err)
2550 		return err;
2551 
2552 	return 0;
2553 }
2554 
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2555 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2556 					  const char *pin_root_path)
2557 {
2558 	const struct btf_type *sec = NULL;
2559 	int nr_types, i, vlen, err;
2560 	const struct btf_type *t;
2561 	const char *name;
2562 	Elf_Data *data;
2563 	Elf_Scn *scn;
2564 
2565 	if (obj->efile.btf_maps_shndx < 0)
2566 		return 0;
2567 
2568 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2569 	data = elf_sec_data(obj, scn);
2570 	if (!scn || !data) {
2571 		pr_warn("elf: failed to get %s map definitions for %s\n",
2572 			MAPS_ELF_SEC, obj->path);
2573 		return -EINVAL;
2574 	}
2575 
2576 	nr_types = btf__type_cnt(obj->btf);
2577 	for (i = 1; i < nr_types; i++) {
2578 		t = btf__type_by_id(obj->btf, i);
2579 		if (!btf_is_datasec(t))
2580 			continue;
2581 		name = btf__name_by_offset(obj->btf, t->name_off);
2582 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2583 			sec = t;
2584 			obj->efile.btf_maps_sec_btf_id = i;
2585 			break;
2586 		}
2587 	}
2588 
2589 	if (!sec) {
2590 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2591 		return -ENOENT;
2592 	}
2593 
2594 	vlen = btf_vlen(sec);
2595 	for (i = 0; i < vlen; i++) {
2596 		err = bpf_object__init_user_btf_map(obj, sec, i,
2597 						    obj->efile.btf_maps_shndx,
2598 						    data, strict,
2599 						    pin_root_path);
2600 		if (err)
2601 			return err;
2602 	}
2603 
2604 	return 0;
2605 }
2606 
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)2607 static int bpf_object__init_maps(struct bpf_object *obj,
2608 				 const struct bpf_object_open_opts *opts)
2609 {
2610 	const char *pin_root_path;
2611 	bool strict;
2612 	int err = 0;
2613 
2614 	strict = !OPTS_GET(opts, relaxed_maps, false);
2615 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2616 
2617 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2618 	err = err ?: bpf_object__init_global_data_maps(obj);
2619 	err = err ?: bpf_object__init_kconfig_map(obj);
2620 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2621 
2622 	return err;
2623 }
2624 
section_have_execinstr(struct bpf_object * obj,int idx)2625 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2626 {
2627 	Elf64_Shdr *sh;
2628 
2629 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2630 	if (!sh)
2631 		return false;
2632 
2633 	return sh->sh_flags & SHF_EXECINSTR;
2634 }
2635 
btf_needs_sanitization(struct bpf_object * obj)2636 static bool btf_needs_sanitization(struct bpf_object *obj)
2637 {
2638 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2639 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2640 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2641 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2642 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2643 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2644 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2645 
2646 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2647 	       !has_decl_tag || !has_type_tag || !has_enum64;
2648 }
2649 
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)2650 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2651 {
2652 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2653 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2654 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2655 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2656 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2657 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2658 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2659 	int enum64_placeholder_id = 0;
2660 	struct btf_type *t;
2661 	int i, j, vlen;
2662 
2663 	for (i = 1; i < btf__type_cnt(btf); i++) {
2664 		t = (struct btf_type *)btf__type_by_id(btf, i);
2665 
2666 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2667 			/* replace VAR/DECL_TAG with INT */
2668 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2669 			/*
2670 			 * using size = 1 is the safest choice, 4 will be too
2671 			 * big and cause kernel BTF validation failure if
2672 			 * original variable took less than 4 bytes
2673 			 */
2674 			t->size = 1;
2675 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2676 		} else if (!has_datasec && btf_is_datasec(t)) {
2677 			/* replace DATASEC with STRUCT */
2678 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2679 			struct btf_member *m = btf_members(t);
2680 			struct btf_type *vt;
2681 			char *name;
2682 
2683 			name = (char *)btf__name_by_offset(btf, t->name_off);
2684 			while (*name) {
2685 				if (*name == '.')
2686 					*name = '_';
2687 				name++;
2688 			}
2689 
2690 			vlen = btf_vlen(t);
2691 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2692 			for (j = 0; j < vlen; j++, v++, m++) {
2693 				/* order of field assignments is important */
2694 				m->offset = v->offset * 8;
2695 				m->type = v->type;
2696 				/* preserve variable name as member name */
2697 				vt = (void *)btf__type_by_id(btf, v->type);
2698 				m->name_off = vt->name_off;
2699 			}
2700 		} else if (!has_func && btf_is_func_proto(t)) {
2701 			/* replace FUNC_PROTO with ENUM */
2702 			vlen = btf_vlen(t);
2703 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2704 			t->size = sizeof(__u32); /* kernel enforced */
2705 		} else if (!has_func && btf_is_func(t)) {
2706 			/* replace FUNC with TYPEDEF */
2707 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2708 		} else if (!has_func_global && btf_is_func(t)) {
2709 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2710 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2711 		} else if (!has_float && btf_is_float(t)) {
2712 			/* replace FLOAT with an equally-sized empty STRUCT;
2713 			 * since C compilers do not accept e.g. "float" as a
2714 			 * valid struct name, make it anonymous
2715 			 */
2716 			t->name_off = 0;
2717 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2718 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2719 			/* replace TYPE_TAG with a CONST */
2720 			t->name_off = 0;
2721 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2722 		} else if (!has_enum64 && btf_is_enum(t)) {
2723 			/* clear the kflag */
2724 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2725 		} else if (!has_enum64 && btf_is_enum64(t)) {
2726 			/* replace ENUM64 with a union */
2727 			struct btf_member *m;
2728 
2729 			if (enum64_placeholder_id == 0) {
2730 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2731 				if (enum64_placeholder_id < 0)
2732 					return enum64_placeholder_id;
2733 
2734 				t = (struct btf_type *)btf__type_by_id(btf, i);
2735 			}
2736 
2737 			m = btf_members(t);
2738 			vlen = btf_vlen(t);
2739 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2740 			for (j = 0; j < vlen; j++, m++) {
2741 				m->type = enum64_placeholder_id;
2742 				m->offset = 0;
2743 			}
2744                 }
2745 	}
2746 
2747 	return 0;
2748 }
2749 
libbpf_needs_btf(const struct bpf_object * obj)2750 static bool libbpf_needs_btf(const struct bpf_object *obj)
2751 {
2752 	return obj->efile.btf_maps_shndx >= 0 ||
2753 	       obj->efile.st_ops_shndx >= 0 ||
2754 	       obj->nr_extern > 0;
2755 }
2756 
kernel_needs_btf(const struct bpf_object * obj)2757 static bool kernel_needs_btf(const struct bpf_object *obj)
2758 {
2759 	return obj->efile.st_ops_shndx >= 0;
2760 }
2761 
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)2762 static int bpf_object__init_btf(struct bpf_object *obj,
2763 				Elf_Data *btf_data,
2764 				Elf_Data *btf_ext_data)
2765 {
2766 	int err = -ENOENT;
2767 
2768 	if (btf_data) {
2769 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2770 		err = libbpf_get_error(obj->btf);
2771 		if (err) {
2772 			obj->btf = NULL;
2773 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2774 			goto out;
2775 		}
2776 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2777 		btf__set_pointer_size(obj->btf, 8);
2778 	}
2779 	if (btf_ext_data) {
2780 		struct btf_ext_info *ext_segs[3];
2781 		int seg_num, sec_num;
2782 
2783 		if (!obj->btf) {
2784 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2785 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2786 			goto out;
2787 		}
2788 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2789 		err = libbpf_get_error(obj->btf_ext);
2790 		if (err) {
2791 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2792 				BTF_EXT_ELF_SEC, err);
2793 			obj->btf_ext = NULL;
2794 			goto out;
2795 		}
2796 
2797 		/* setup .BTF.ext to ELF section mapping */
2798 		ext_segs[0] = &obj->btf_ext->func_info;
2799 		ext_segs[1] = &obj->btf_ext->line_info;
2800 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2801 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2802 			struct btf_ext_info *seg = ext_segs[seg_num];
2803 			const struct btf_ext_info_sec *sec;
2804 			const char *sec_name;
2805 			Elf_Scn *scn;
2806 
2807 			if (seg->sec_cnt == 0)
2808 				continue;
2809 
2810 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2811 			if (!seg->sec_idxs) {
2812 				err = -ENOMEM;
2813 				goto out;
2814 			}
2815 
2816 			sec_num = 0;
2817 			for_each_btf_ext_sec(seg, sec) {
2818 				/* preventively increment index to avoid doing
2819 				 * this before every continue below
2820 				 */
2821 				sec_num++;
2822 
2823 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2824 				if (str_is_empty(sec_name))
2825 					continue;
2826 				scn = elf_sec_by_name(obj, sec_name);
2827 				if (!scn)
2828 					continue;
2829 
2830 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2831 			}
2832 		}
2833 	}
2834 out:
2835 	if (err && libbpf_needs_btf(obj)) {
2836 		pr_warn("BTF is required, but is missing or corrupted.\n");
2837 		return err;
2838 	}
2839 	return 0;
2840 }
2841 
compare_vsi_off(const void * _a,const void * _b)2842 static int compare_vsi_off(const void *_a, const void *_b)
2843 {
2844 	const struct btf_var_secinfo *a = _a;
2845 	const struct btf_var_secinfo *b = _b;
2846 
2847 	return a->offset - b->offset;
2848 }
2849 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)2850 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2851 			     struct btf_type *t)
2852 {
2853 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
2854 	const char *name = btf__name_by_offset(btf, t->name_off);
2855 	const struct btf_type *t_var;
2856 	struct btf_var_secinfo *vsi;
2857 	const struct btf_var *var;
2858 	int ret;
2859 
2860 	if (!name) {
2861 		pr_debug("No name found in string section for DATASEC kind.\n");
2862 		return -ENOENT;
2863 	}
2864 
2865 	/* .extern datasec size and var offsets were set correctly during
2866 	 * extern collection step, so just skip straight to sorting variables
2867 	 */
2868 	if (t->size)
2869 		goto sort_vars;
2870 
2871 	ret = find_elf_sec_sz(obj, name, &size);
2872 	if (ret || !size) {
2873 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2874 		return -ENOENT;
2875 	}
2876 
2877 	t->size = size;
2878 
2879 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2880 		t_var = btf__type_by_id(btf, vsi->type);
2881 		if (!t_var || !btf_is_var(t_var)) {
2882 			pr_debug("Non-VAR type seen in section %s\n", name);
2883 			return -EINVAL;
2884 		}
2885 
2886 		var = btf_var(t_var);
2887 		if (var->linkage == BTF_VAR_STATIC)
2888 			continue;
2889 
2890 		name = btf__name_by_offset(btf, t_var->name_off);
2891 		if (!name) {
2892 			pr_debug("No name found in string section for VAR kind\n");
2893 			return -ENOENT;
2894 		}
2895 
2896 		ret = find_elf_var_offset(obj, name, &off);
2897 		if (ret) {
2898 			pr_debug("No offset found in symbol table for VAR %s\n",
2899 				 name);
2900 			return -ENOENT;
2901 		}
2902 
2903 		vsi->offset = off;
2904 	}
2905 
2906 sort_vars:
2907 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2908 	return 0;
2909 }
2910 
btf_finalize_data(struct bpf_object * obj,struct btf * btf)2911 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2912 {
2913 	int err = 0;
2914 	__u32 i, n = btf__type_cnt(btf);
2915 
2916 	for (i = 1; i < n; i++) {
2917 		struct btf_type *t = btf_type_by_id(btf, i);
2918 
2919 		/* Loader needs to fix up some of the things compiler
2920 		 * couldn't get its hands on while emitting BTF. This
2921 		 * is section size and global variable offset. We use
2922 		 * the info from the ELF itself for this purpose.
2923 		 */
2924 		if (btf_is_datasec(t)) {
2925 			err = btf_fixup_datasec(obj, btf, t);
2926 			if (err)
2927 				break;
2928 		}
2929 	}
2930 
2931 	return libbpf_err(err);
2932 }
2933 
bpf_object__finalize_btf(struct bpf_object * obj)2934 static int bpf_object__finalize_btf(struct bpf_object *obj)
2935 {
2936 	int err;
2937 
2938 	if (!obj->btf)
2939 		return 0;
2940 
2941 	err = btf_finalize_data(obj, obj->btf);
2942 	if (err) {
2943 		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2944 		return err;
2945 	}
2946 
2947 	return 0;
2948 }
2949 
prog_needs_vmlinux_btf(struct bpf_program * prog)2950 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2951 {
2952 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2953 	    prog->type == BPF_PROG_TYPE_LSM)
2954 		return true;
2955 
2956 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2957 	 * also need vmlinux BTF
2958 	 */
2959 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2960 		return true;
2961 
2962 	return false;
2963 }
2964 
obj_needs_vmlinux_btf(const struct bpf_object * obj)2965 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2966 {
2967 	struct bpf_program *prog;
2968 	int i;
2969 
2970 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
2971 	 * is not specified
2972 	 */
2973 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2974 		return true;
2975 
2976 	/* Support for typed ksyms needs kernel BTF */
2977 	for (i = 0; i < obj->nr_extern; i++) {
2978 		const struct extern_desc *ext;
2979 
2980 		ext = &obj->externs[i];
2981 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
2982 			return true;
2983 	}
2984 
2985 	bpf_object__for_each_program(prog, obj) {
2986 		if (!prog->autoload)
2987 			continue;
2988 		if (prog_needs_vmlinux_btf(prog))
2989 			return true;
2990 	}
2991 
2992 	return false;
2993 }
2994 
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)2995 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2996 {
2997 	int err;
2998 
2999 	/* btf_vmlinux could be loaded earlier */
3000 	if (obj->btf_vmlinux || obj->gen_loader)
3001 		return 0;
3002 
3003 	if (!force && !obj_needs_vmlinux_btf(obj))
3004 		return 0;
3005 
3006 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3007 	err = libbpf_get_error(obj->btf_vmlinux);
3008 	if (err) {
3009 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3010 		obj->btf_vmlinux = NULL;
3011 		return err;
3012 	}
3013 	return 0;
3014 }
3015 
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3016 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3017 {
3018 	struct btf *kern_btf = obj->btf;
3019 	bool btf_mandatory, sanitize;
3020 	int i, err = 0;
3021 
3022 	if (!obj->btf)
3023 		return 0;
3024 
3025 	if (!kernel_supports(obj, FEAT_BTF)) {
3026 		if (kernel_needs_btf(obj)) {
3027 			err = -EOPNOTSUPP;
3028 			goto report;
3029 		}
3030 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3031 		return 0;
3032 	}
3033 
3034 	/* Even though some subprogs are global/weak, user might prefer more
3035 	 * permissive BPF verification process that BPF verifier performs for
3036 	 * static functions, taking into account more context from the caller
3037 	 * functions. In such case, they need to mark such subprogs with
3038 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3039 	 * corresponding FUNC BTF type to be marked as static and trigger more
3040 	 * involved BPF verification process.
3041 	 */
3042 	for (i = 0; i < obj->nr_programs; i++) {
3043 		struct bpf_program *prog = &obj->programs[i];
3044 		struct btf_type *t;
3045 		const char *name;
3046 		int j, n;
3047 
3048 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3049 			continue;
3050 
3051 		n = btf__type_cnt(obj->btf);
3052 		for (j = 1; j < n; j++) {
3053 			t = btf_type_by_id(obj->btf, j);
3054 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3055 				continue;
3056 
3057 			name = btf__str_by_offset(obj->btf, t->name_off);
3058 			if (strcmp(name, prog->name) != 0)
3059 				continue;
3060 
3061 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3062 			break;
3063 		}
3064 	}
3065 
3066 	sanitize = btf_needs_sanitization(obj);
3067 	if (sanitize) {
3068 		const void *raw_data;
3069 		__u32 sz;
3070 
3071 		/* clone BTF to sanitize a copy and leave the original intact */
3072 		raw_data = btf__raw_data(obj->btf, &sz);
3073 		kern_btf = btf__new(raw_data, sz);
3074 		err = libbpf_get_error(kern_btf);
3075 		if (err)
3076 			return err;
3077 
3078 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3079 		btf__set_pointer_size(obj->btf, 8);
3080 		err = bpf_object__sanitize_btf(obj, kern_btf);
3081 		if (err)
3082 			return err;
3083 	}
3084 
3085 	if (obj->gen_loader) {
3086 		__u32 raw_size = 0;
3087 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3088 
3089 		if (!raw_data)
3090 			return -ENOMEM;
3091 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3092 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3093 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3094 		 */
3095 		btf__set_fd(kern_btf, 0);
3096 	} else {
3097 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3098 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3099 					   obj->log_level ? 1 : 0);
3100 	}
3101 	if (sanitize) {
3102 		if (!err) {
3103 			/* move fd to libbpf's BTF */
3104 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3105 			btf__set_fd(kern_btf, -1);
3106 		}
3107 		btf__free(kern_btf);
3108 	}
3109 report:
3110 	if (err) {
3111 		btf_mandatory = kernel_needs_btf(obj);
3112 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3113 			btf_mandatory ? "BTF is mandatory, can't proceed."
3114 				      : "BTF is optional, ignoring.");
3115 		if (!btf_mandatory)
3116 			err = 0;
3117 	}
3118 	return err;
3119 }
3120 
elf_sym_str(const struct bpf_object * obj,size_t off)3121 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3122 {
3123 	const char *name;
3124 
3125 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3126 	if (!name) {
3127 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3128 			off, obj->path, elf_errmsg(-1));
3129 		return NULL;
3130 	}
3131 
3132 	return name;
3133 }
3134 
elf_sec_str(const struct bpf_object * obj,size_t off)3135 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3136 {
3137 	const char *name;
3138 
3139 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3140 	if (!name) {
3141 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3142 			off, obj->path, elf_errmsg(-1));
3143 		return NULL;
3144 	}
3145 
3146 	return name;
3147 }
3148 
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3149 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3150 {
3151 	Elf_Scn *scn;
3152 
3153 	scn = elf_getscn(obj->efile.elf, idx);
3154 	if (!scn) {
3155 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3156 			idx, obj->path, elf_errmsg(-1));
3157 		return NULL;
3158 	}
3159 	return scn;
3160 }
3161 
elf_sec_by_name(const struct bpf_object * obj,const char * name)3162 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3163 {
3164 	Elf_Scn *scn = NULL;
3165 	Elf *elf = obj->efile.elf;
3166 	const char *sec_name;
3167 
3168 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3169 		sec_name = elf_sec_name(obj, scn);
3170 		if (!sec_name)
3171 			return NULL;
3172 
3173 		if (strcmp(sec_name, name) != 0)
3174 			continue;
3175 
3176 		return scn;
3177 	}
3178 	return NULL;
3179 }
3180 
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3181 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3182 {
3183 	Elf64_Shdr *shdr;
3184 
3185 	if (!scn)
3186 		return NULL;
3187 
3188 	shdr = elf64_getshdr(scn);
3189 	if (!shdr) {
3190 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3191 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3192 		return NULL;
3193 	}
3194 
3195 	return shdr;
3196 }
3197 
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3198 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3199 {
3200 	const char *name;
3201 	Elf64_Shdr *sh;
3202 
3203 	if (!scn)
3204 		return NULL;
3205 
3206 	sh = elf_sec_hdr(obj, scn);
3207 	if (!sh)
3208 		return NULL;
3209 
3210 	name = elf_sec_str(obj, sh->sh_name);
3211 	if (!name) {
3212 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3213 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3214 		return NULL;
3215 	}
3216 
3217 	return name;
3218 }
3219 
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3220 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3221 {
3222 	Elf_Data *data;
3223 
3224 	if (!scn)
3225 		return NULL;
3226 
3227 	data = elf_getdata(scn, 0);
3228 	if (!data) {
3229 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3230 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3231 			obj->path, elf_errmsg(-1));
3232 		return NULL;
3233 	}
3234 
3235 	return data;
3236 }
3237 
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3238 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3239 {
3240 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3241 		return NULL;
3242 
3243 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3244 }
3245 
elf_rel_by_idx(Elf_Data * data,size_t idx)3246 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3247 {
3248 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3249 		return NULL;
3250 
3251 	return (Elf64_Rel *)data->d_buf + idx;
3252 }
3253 
is_sec_name_dwarf(const char * name)3254 static bool is_sec_name_dwarf(const char *name)
3255 {
3256 	/* approximation, but the actual list is too long */
3257 	return str_has_pfx(name, ".debug_");
3258 }
3259 
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3260 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3261 {
3262 	/* no special handling of .strtab */
3263 	if (hdr->sh_type == SHT_STRTAB)
3264 		return true;
3265 
3266 	/* ignore .llvm_addrsig section as well */
3267 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3268 		return true;
3269 
3270 	/* no subprograms will lead to an empty .text section, ignore it */
3271 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3272 	    strcmp(name, ".text") == 0)
3273 		return true;
3274 
3275 	/* DWARF sections */
3276 	if (is_sec_name_dwarf(name))
3277 		return true;
3278 
3279 	if (str_has_pfx(name, ".rel")) {
3280 		name += sizeof(".rel") - 1;
3281 		/* DWARF section relocations */
3282 		if (is_sec_name_dwarf(name))
3283 			return true;
3284 
3285 		/* .BTF and .BTF.ext don't need relocations */
3286 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3287 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3288 			return true;
3289 	}
3290 
3291 	return false;
3292 }
3293 
cmp_progs(const void * _a,const void * _b)3294 static int cmp_progs(const void *_a, const void *_b)
3295 {
3296 	const struct bpf_program *a = _a;
3297 	const struct bpf_program *b = _b;
3298 
3299 	if (a->sec_idx != b->sec_idx)
3300 		return a->sec_idx < b->sec_idx ? -1 : 1;
3301 
3302 	/* sec_insn_off can't be the same within the section */
3303 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3304 }
3305 
bpf_object__elf_collect(struct bpf_object * obj)3306 static int bpf_object__elf_collect(struct bpf_object *obj)
3307 {
3308 	struct elf_sec_desc *sec_desc;
3309 	Elf *elf = obj->efile.elf;
3310 	Elf_Data *btf_ext_data = NULL;
3311 	Elf_Data *btf_data = NULL;
3312 	int idx = 0, err = 0;
3313 	const char *name;
3314 	Elf_Data *data;
3315 	Elf_Scn *scn;
3316 	Elf64_Shdr *sh;
3317 
3318 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3319 	 * section. Since section count retrieved by elf_getshdrnum() does
3320 	 * include sec #0, it is already the necessary size of an array to keep
3321 	 * all the sections.
3322 	 */
3323 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3324 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3325 			obj->path, elf_errmsg(-1));
3326 		return -LIBBPF_ERRNO__FORMAT;
3327 	}
3328 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3329 	if (!obj->efile.secs)
3330 		return -ENOMEM;
3331 
3332 	/* a bunch of ELF parsing functionality depends on processing symbols,
3333 	 * so do the first pass and find the symbol table
3334 	 */
3335 	scn = NULL;
3336 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3337 		sh = elf_sec_hdr(obj, scn);
3338 		if (!sh)
3339 			return -LIBBPF_ERRNO__FORMAT;
3340 
3341 		if (sh->sh_type == SHT_SYMTAB) {
3342 			if (obj->efile.symbols) {
3343 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3344 				return -LIBBPF_ERRNO__FORMAT;
3345 			}
3346 
3347 			data = elf_sec_data(obj, scn);
3348 			if (!data)
3349 				return -LIBBPF_ERRNO__FORMAT;
3350 
3351 			idx = elf_ndxscn(scn);
3352 
3353 			obj->efile.symbols = data;
3354 			obj->efile.symbols_shndx = idx;
3355 			obj->efile.strtabidx = sh->sh_link;
3356 		}
3357 	}
3358 
3359 	if (!obj->efile.symbols) {
3360 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3361 			obj->path);
3362 		return -ENOENT;
3363 	}
3364 
3365 	scn = NULL;
3366 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3367 		idx = elf_ndxscn(scn);
3368 		sec_desc = &obj->efile.secs[idx];
3369 
3370 		sh = elf_sec_hdr(obj, scn);
3371 		if (!sh)
3372 			return -LIBBPF_ERRNO__FORMAT;
3373 
3374 		name = elf_sec_str(obj, sh->sh_name);
3375 		if (!name)
3376 			return -LIBBPF_ERRNO__FORMAT;
3377 
3378 		if (ignore_elf_section(sh, name))
3379 			continue;
3380 
3381 		data = elf_sec_data(obj, scn);
3382 		if (!data)
3383 			return -LIBBPF_ERRNO__FORMAT;
3384 
3385 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3386 			 idx, name, (unsigned long)data->d_size,
3387 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3388 			 (int)sh->sh_type);
3389 
3390 		if (strcmp(name, "license") == 0) {
3391 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3392 			if (err)
3393 				return err;
3394 		} else if (strcmp(name, "version") == 0) {
3395 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3396 			if (err)
3397 				return err;
3398 		} else if (strcmp(name, "maps") == 0) {
3399 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3400 			return -ENOTSUP;
3401 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3402 			obj->efile.btf_maps_shndx = idx;
3403 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3404 			if (sh->sh_type != SHT_PROGBITS)
3405 				return -LIBBPF_ERRNO__FORMAT;
3406 			btf_data = data;
3407 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3408 			if (sh->sh_type != SHT_PROGBITS)
3409 				return -LIBBPF_ERRNO__FORMAT;
3410 			btf_ext_data = data;
3411 		} else if (sh->sh_type == SHT_SYMTAB) {
3412 			/* already processed during the first pass above */
3413 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3414 			if (sh->sh_flags & SHF_EXECINSTR) {
3415 				if (strcmp(name, ".text") == 0)
3416 					obj->efile.text_shndx = idx;
3417 				err = bpf_object__add_programs(obj, data, name, idx);
3418 				if (err)
3419 					return err;
3420 			} else if (strcmp(name, DATA_SEC) == 0 ||
3421 				   str_has_pfx(name, DATA_SEC ".")) {
3422 				sec_desc->sec_type = SEC_DATA;
3423 				sec_desc->shdr = sh;
3424 				sec_desc->data = data;
3425 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3426 				   str_has_pfx(name, RODATA_SEC ".")) {
3427 				sec_desc->sec_type = SEC_RODATA;
3428 				sec_desc->shdr = sh;
3429 				sec_desc->data = data;
3430 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3431 				obj->efile.st_ops_data = data;
3432 				obj->efile.st_ops_shndx = idx;
3433 			} else {
3434 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3435 					idx, name);
3436 			}
3437 		} else if (sh->sh_type == SHT_REL) {
3438 			int targ_sec_idx = sh->sh_info; /* points to other section */
3439 
3440 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3441 			    targ_sec_idx >= obj->efile.sec_cnt)
3442 				return -LIBBPF_ERRNO__FORMAT;
3443 
3444 			/* Only do relo for section with exec instructions */
3445 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3446 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3447 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3448 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3449 					idx, name, targ_sec_idx,
3450 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3451 				continue;
3452 			}
3453 
3454 			sec_desc->sec_type = SEC_RELO;
3455 			sec_desc->shdr = sh;
3456 			sec_desc->data = data;
3457 		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3458 			sec_desc->sec_type = SEC_BSS;
3459 			sec_desc->shdr = sh;
3460 			sec_desc->data = data;
3461 		} else {
3462 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3463 				(size_t)sh->sh_size);
3464 		}
3465 	}
3466 
3467 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3468 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3469 		return -LIBBPF_ERRNO__FORMAT;
3470 	}
3471 
3472 	/* sort BPF programs by section name and in-section instruction offset
3473 	 * for faster search */
3474 	if (obj->nr_programs)
3475 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3476 
3477 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3478 }
3479 
sym_is_extern(const Elf64_Sym * sym)3480 static bool sym_is_extern(const Elf64_Sym *sym)
3481 {
3482 	int bind = ELF64_ST_BIND(sym->st_info);
3483 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3484 	return sym->st_shndx == SHN_UNDEF &&
3485 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3486 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3487 }
3488 
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)3489 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3490 {
3491 	int bind = ELF64_ST_BIND(sym->st_info);
3492 	int type = ELF64_ST_TYPE(sym->st_info);
3493 
3494 	/* in .text section */
3495 	if (sym->st_shndx != text_shndx)
3496 		return false;
3497 
3498 	/* local function */
3499 	if (bind == STB_LOCAL && type == STT_SECTION)
3500 		return true;
3501 
3502 	/* global function */
3503 	return bind == STB_GLOBAL && type == STT_FUNC;
3504 }
3505 
find_extern_btf_id(const struct btf * btf,const char * ext_name)3506 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3507 {
3508 	const struct btf_type *t;
3509 	const char *tname;
3510 	int i, n;
3511 
3512 	if (!btf)
3513 		return -ESRCH;
3514 
3515 	n = btf__type_cnt(btf);
3516 	for (i = 1; i < n; i++) {
3517 		t = btf__type_by_id(btf, i);
3518 
3519 		if (!btf_is_var(t) && !btf_is_func(t))
3520 			continue;
3521 
3522 		tname = btf__name_by_offset(btf, t->name_off);
3523 		if (strcmp(tname, ext_name))
3524 			continue;
3525 
3526 		if (btf_is_var(t) &&
3527 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3528 			return -EINVAL;
3529 
3530 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3531 			return -EINVAL;
3532 
3533 		return i;
3534 	}
3535 
3536 	return -ENOENT;
3537 }
3538 
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)3539 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3540 	const struct btf_var_secinfo *vs;
3541 	const struct btf_type *t;
3542 	int i, j, n;
3543 
3544 	if (!btf)
3545 		return -ESRCH;
3546 
3547 	n = btf__type_cnt(btf);
3548 	for (i = 1; i < n; i++) {
3549 		t = btf__type_by_id(btf, i);
3550 
3551 		if (!btf_is_datasec(t))
3552 			continue;
3553 
3554 		vs = btf_var_secinfos(t);
3555 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3556 			if (vs->type == ext_btf_id)
3557 				return i;
3558 		}
3559 	}
3560 
3561 	return -ENOENT;
3562 }
3563 
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)3564 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3565 				     bool *is_signed)
3566 {
3567 	const struct btf_type *t;
3568 	const char *name;
3569 
3570 	t = skip_mods_and_typedefs(btf, id, NULL);
3571 	name = btf__name_by_offset(btf, t->name_off);
3572 
3573 	if (is_signed)
3574 		*is_signed = false;
3575 	switch (btf_kind(t)) {
3576 	case BTF_KIND_INT: {
3577 		int enc = btf_int_encoding(t);
3578 
3579 		if (enc & BTF_INT_BOOL)
3580 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3581 		if (is_signed)
3582 			*is_signed = enc & BTF_INT_SIGNED;
3583 		if (t->size == 1)
3584 			return KCFG_CHAR;
3585 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3586 			return KCFG_UNKNOWN;
3587 		return KCFG_INT;
3588 	}
3589 	case BTF_KIND_ENUM:
3590 		if (t->size != 4)
3591 			return KCFG_UNKNOWN;
3592 		if (strcmp(name, "libbpf_tristate"))
3593 			return KCFG_UNKNOWN;
3594 		return KCFG_TRISTATE;
3595 	case BTF_KIND_ENUM64:
3596 		if (strcmp(name, "libbpf_tristate"))
3597 			return KCFG_UNKNOWN;
3598 		return KCFG_TRISTATE;
3599 	case BTF_KIND_ARRAY:
3600 		if (btf_array(t)->nelems == 0)
3601 			return KCFG_UNKNOWN;
3602 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3603 			return KCFG_UNKNOWN;
3604 		return KCFG_CHAR_ARR;
3605 	default:
3606 		return KCFG_UNKNOWN;
3607 	}
3608 }
3609 
cmp_externs(const void * _a,const void * _b)3610 static int cmp_externs(const void *_a, const void *_b)
3611 {
3612 	const struct extern_desc *a = _a;
3613 	const struct extern_desc *b = _b;
3614 
3615 	if (a->type != b->type)
3616 		return a->type < b->type ? -1 : 1;
3617 
3618 	if (a->type == EXT_KCFG) {
3619 		/* descending order by alignment requirements */
3620 		if (a->kcfg.align != b->kcfg.align)
3621 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3622 		/* ascending order by size, within same alignment class */
3623 		if (a->kcfg.sz != b->kcfg.sz)
3624 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3625 	}
3626 
3627 	/* resolve ties by name */
3628 	return strcmp(a->name, b->name);
3629 }
3630 
find_int_btf_id(const struct btf * btf)3631 static int find_int_btf_id(const struct btf *btf)
3632 {
3633 	const struct btf_type *t;
3634 	int i, n;
3635 
3636 	n = btf__type_cnt(btf);
3637 	for (i = 1; i < n; i++) {
3638 		t = btf__type_by_id(btf, i);
3639 
3640 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3641 			return i;
3642 	}
3643 
3644 	return 0;
3645 }
3646 
add_dummy_ksym_var(struct btf * btf)3647 static int add_dummy_ksym_var(struct btf *btf)
3648 {
3649 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3650 	const struct btf_var_secinfo *vs;
3651 	const struct btf_type *sec;
3652 
3653 	if (!btf)
3654 		return 0;
3655 
3656 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3657 					    BTF_KIND_DATASEC);
3658 	if (sec_btf_id < 0)
3659 		return 0;
3660 
3661 	sec = btf__type_by_id(btf, sec_btf_id);
3662 	vs = btf_var_secinfos(sec);
3663 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3664 		const struct btf_type *vt;
3665 
3666 		vt = btf__type_by_id(btf, vs->type);
3667 		if (btf_is_func(vt))
3668 			break;
3669 	}
3670 
3671 	/* No func in ksyms sec.  No need to add dummy var. */
3672 	if (i == btf_vlen(sec))
3673 		return 0;
3674 
3675 	int_btf_id = find_int_btf_id(btf);
3676 	dummy_var_btf_id = btf__add_var(btf,
3677 					"dummy_ksym",
3678 					BTF_VAR_GLOBAL_ALLOCATED,
3679 					int_btf_id);
3680 	if (dummy_var_btf_id < 0)
3681 		pr_warn("cannot create a dummy_ksym var\n");
3682 
3683 	return dummy_var_btf_id;
3684 }
3685 
bpf_object__collect_externs(struct bpf_object * obj)3686 static int bpf_object__collect_externs(struct bpf_object *obj)
3687 {
3688 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3689 	const struct btf_type *t;
3690 	struct extern_desc *ext;
3691 	int i, n, off, dummy_var_btf_id;
3692 	const char *ext_name, *sec_name;
3693 	Elf_Scn *scn;
3694 	Elf64_Shdr *sh;
3695 
3696 	if (!obj->efile.symbols)
3697 		return 0;
3698 
3699 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3700 	sh = elf_sec_hdr(obj, scn);
3701 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3702 		return -LIBBPF_ERRNO__FORMAT;
3703 
3704 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3705 	if (dummy_var_btf_id < 0)
3706 		return dummy_var_btf_id;
3707 
3708 	n = sh->sh_size / sh->sh_entsize;
3709 	pr_debug("looking for externs among %d symbols...\n", n);
3710 
3711 	for (i = 0; i < n; i++) {
3712 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3713 
3714 		if (!sym)
3715 			return -LIBBPF_ERRNO__FORMAT;
3716 		if (!sym_is_extern(sym))
3717 			continue;
3718 		ext_name = elf_sym_str(obj, sym->st_name);
3719 		if (!ext_name || !ext_name[0])
3720 			continue;
3721 
3722 		ext = obj->externs;
3723 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3724 		if (!ext)
3725 			return -ENOMEM;
3726 		obj->externs = ext;
3727 		ext = &ext[obj->nr_extern];
3728 		memset(ext, 0, sizeof(*ext));
3729 		obj->nr_extern++;
3730 
3731 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3732 		if (ext->btf_id <= 0) {
3733 			pr_warn("failed to find BTF for extern '%s': %d\n",
3734 				ext_name, ext->btf_id);
3735 			return ext->btf_id;
3736 		}
3737 		t = btf__type_by_id(obj->btf, ext->btf_id);
3738 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3739 		ext->sym_idx = i;
3740 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3741 
3742 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3743 		if (ext->sec_btf_id <= 0) {
3744 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3745 				ext_name, ext->btf_id, ext->sec_btf_id);
3746 			return ext->sec_btf_id;
3747 		}
3748 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3749 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3750 
3751 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3752 			if (btf_is_func(t)) {
3753 				pr_warn("extern function %s is unsupported under %s section\n",
3754 					ext->name, KCONFIG_SEC);
3755 				return -ENOTSUP;
3756 			}
3757 			kcfg_sec = sec;
3758 			ext->type = EXT_KCFG;
3759 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3760 			if (ext->kcfg.sz <= 0) {
3761 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3762 					ext_name, ext->kcfg.sz);
3763 				return ext->kcfg.sz;
3764 			}
3765 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3766 			if (ext->kcfg.align <= 0) {
3767 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3768 					ext_name, ext->kcfg.align);
3769 				return -EINVAL;
3770 			}
3771 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3772 						        &ext->kcfg.is_signed);
3773 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3774 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3775 				return -ENOTSUP;
3776 			}
3777 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3778 			ksym_sec = sec;
3779 			ext->type = EXT_KSYM;
3780 			skip_mods_and_typedefs(obj->btf, t->type,
3781 					       &ext->ksym.type_id);
3782 		} else {
3783 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3784 			return -ENOTSUP;
3785 		}
3786 	}
3787 	pr_debug("collected %d externs total\n", obj->nr_extern);
3788 
3789 	if (!obj->nr_extern)
3790 		return 0;
3791 
3792 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3793 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3794 
3795 	/* for .ksyms section, we need to turn all externs into allocated
3796 	 * variables in BTF to pass kernel verification; we do this by
3797 	 * pretending that each extern is a 8-byte variable
3798 	 */
3799 	if (ksym_sec) {
3800 		/* find existing 4-byte integer type in BTF to use for fake
3801 		 * extern variables in DATASEC
3802 		 */
3803 		int int_btf_id = find_int_btf_id(obj->btf);
3804 		/* For extern function, a dummy_var added earlier
3805 		 * will be used to replace the vs->type and
3806 		 * its name string will be used to refill
3807 		 * the missing param's name.
3808 		 */
3809 		const struct btf_type *dummy_var;
3810 
3811 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3812 		for (i = 0; i < obj->nr_extern; i++) {
3813 			ext = &obj->externs[i];
3814 			if (ext->type != EXT_KSYM)
3815 				continue;
3816 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3817 				 i, ext->sym_idx, ext->name);
3818 		}
3819 
3820 		sec = ksym_sec;
3821 		n = btf_vlen(sec);
3822 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3823 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3824 			struct btf_type *vt;
3825 
3826 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3827 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3828 			ext = find_extern_by_name(obj, ext_name);
3829 			if (!ext) {
3830 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3831 					btf_kind_str(vt), ext_name);
3832 				return -ESRCH;
3833 			}
3834 			if (btf_is_func(vt)) {
3835 				const struct btf_type *func_proto;
3836 				struct btf_param *param;
3837 				int j;
3838 
3839 				func_proto = btf__type_by_id(obj->btf,
3840 							     vt->type);
3841 				param = btf_params(func_proto);
3842 				/* Reuse the dummy_var string if the
3843 				 * func proto does not have param name.
3844 				 */
3845 				for (j = 0; j < btf_vlen(func_proto); j++)
3846 					if (param[j].type && !param[j].name_off)
3847 						param[j].name_off =
3848 							dummy_var->name_off;
3849 				vs->type = dummy_var_btf_id;
3850 				vt->info &= ~0xffff;
3851 				vt->info |= BTF_FUNC_GLOBAL;
3852 			} else {
3853 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3854 				vt->type = int_btf_id;
3855 			}
3856 			vs->offset = off;
3857 			vs->size = sizeof(int);
3858 		}
3859 		sec->size = off;
3860 	}
3861 
3862 	if (kcfg_sec) {
3863 		sec = kcfg_sec;
3864 		/* for kcfg externs calculate their offsets within a .kconfig map */
3865 		off = 0;
3866 		for (i = 0; i < obj->nr_extern; i++) {
3867 			ext = &obj->externs[i];
3868 			if (ext->type != EXT_KCFG)
3869 				continue;
3870 
3871 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3872 			off = ext->kcfg.data_off + ext->kcfg.sz;
3873 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3874 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3875 		}
3876 		sec->size = off;
3877 		n = btf_vlen(sec);
3878 		for (i = 0; i < n; i++) {
3879 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3880 
3881 			t = btf__type_by_id(obj->btf, vs->type);
3882 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3883 			ext = find_extern_by_name(obj, ext_name);
3884 			if (!ext) {
3885 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3886 					ext_name);
3887 				return -ESRCH;
3888 			}
3889 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3890 			vs->offset = ext->kcfg.data_off;
3891 		}
3892 	}
3893 	return 0;
3894 }
3895 
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)3896 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3897 {
3898 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3899 }
3900 
3901 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)3902 bpf_object__find_program_by_name(const struct bpf_object *obj,
3903 				 const char *name)
3904 {
3905 	struct bpf_program *prog;
3906 
3907 	bpf_object__for_each_program(prog, obj) {
3908 		if (prog_is_subprog(obj, prog))
3909 			continue;
3910 		if (!strcmp(prog->name, name))
3911 			return prog;
3912 	}
3913 	return errno = ENOENT, NULL;
3914 }
3915 
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)3916 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3917 				      int shndx)
3918 {
3919 	switch (obj->efile.secs[shndx].sec_type) {
3920 	case SEC_BSS:
3921 	case SEC_DATA:
3922 	case SEC_RODATA:
3923 		return true;
3924 	default:
3925 		return false;
3926 	}
3927 }
3928 
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)3929 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3930 				      int shndx)
3931 {
3932 	return shndx == obj->efile.btf_maps_shndx;
3933 }
3934 
3935 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)3936 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3937 {
3938 	if (shndx == obj->efile.symbols_shndx)
3939 		return LIBBPF_MAP_KCONFIG;
3940 
3941 	switch (obj->efile.secs[shndx].sec_type) {
3942 	case SEC_BSS:
3943 		return LIBBPF_MAP_BSS;
3944 	case SEC_DATA:
3945 		return LIBBPF_MAP_DATA;
3946 	case SEC_RODATA:
3947 		return LIBBPF_MAP_RODATA;
3948 	default:
3949 		return LIBBPF_MAP_UNSPEC;
3950 	}
3951 }
3952 
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)3953 static int bpf_program__record_reloc(struct bpf_program *prog,
3954 				     struct reloc_desc *reloc_desc,
3955 				     __u32 insn_idx, const char *sym_name,
3956 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
3957 {
3958 	struct bpf_insn *insn = &prog->insns[insn_idx];
3959 	size_t map_idx, nr_maps = prog->obj->nr_maps;
3960 	struct bpf_object *obj = prog->obj;
3961 	__u32 shdr_idx = sym->st_shndx;
3962 	enum libbpf_map_type type;
3963 	const char *sym_sec_name;
3964 	struct bpf_map *map;
3965 
3966 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3967 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3968 			prog->name, sym_name, insn_idx, insn->code);
3969 		return -LIBBPF_ERRNO__RELOC;
3970 	}
3971 
3972 	if (sym_is_extern(sym)) {
3973 		int sym_idx = ELF64_R_SYM(rel->r_info);
3974 		int i, n = obj->nr_extern;
3975 		struct extern_desc *ext;
3976 
3977 		for (i = 0; i < n; i++) {
3978 			ext = &obj->externs[i];
3979 			if (ext->sym_idx == sym_idx)
3980 				break;
3981 		}
3982 		if (i >= n) {
3983 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3984 				prog->name, sym_name, sym_idx);
3985 			return -LIBBPF_ERRNO__RELOC;
3986 		}
3987 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3988 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3989 		if (insn->code == (BPF_JMP | BPF_CALL))
3990 			reloc_desc->type = RELO_EXTERN_FUNC;
3991 		else
3992 			reloc_desc->type = RELO_EXTERN_VAR;
3993 		reloc_desc->insn_idx = insn_idx;
3994 		reloc_desc->sym_off = i; /* sym_off stores extern index */
3995 		return 0;
3996 	}
3997 
3998 	/* sub-program call relocation */
3999 	if (is_call_insn(insn)) {
4000 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4001 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4002 			return -LIBBPF_ERRNO__RELOC;
4003 		}
4004 		/* text_shndx can be 0, if no default "main" program exists */
4005 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4006 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4007 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4008 				prog->name, sym_name, sym_sec_name);
4009 			return -LIBBPF_ERRNO__RELOC;
4010 		}
4011 		if (sym->st_value % BPF_INSN_SZ) {
4012 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4013 				prog->name, sym_name, (size_t)sym->st_value);
4014 			return -LIBBPF_ERRNO__RELOC;
4015 		}
4016 		reloc_desc->type = RELO_CALL;
4017 		reloc_desc->insn_idx = insn_idx;
4018 		reloc_desc->sym_off = sym->st_value;
4019 		return 0;
4020 	}
4021 
4022 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4023 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4024 			prog->name, sym_name, shdr_idx);
4025 		return -LIBBPF_ERRNO__RELOC;
4026 	}
4027 
4028 	/* loading subprog addresses */
4029 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4030 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4031 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4032 		 */
4033 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4034 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4035 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4036 			return -LIBBPF_ERRNO__RELOC;
4037 		}
4038 
4039 		reloc_desc->type = RELO_SUBPROG_ADDR;
4040 		reloc_desc->insn_idx = insn_idx;
4041 		reloc_desc->sym_off = sym->st_value;
4042 		return 0;
4043 	}
4044 
4045 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4046 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4047 
4048 	/* generic map reference relocation */
4049 	if (type == LIBBPF_MAP_UNSPEC) {
4050 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4051 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4052 				prog->name, sym_name, sym_sec_name);
4053 			return -LIBBPF_ERRNO__RELOC;
4054 		}
4055 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4056 			map = &obj->maps[map_idx];
4057 			if (map->libbpf_type != type ||
4058 			    map->sec_idx != sym->st_shndx ||
4059 			    map->sec_offset != sym->st_value)
4060 				continue;
4061 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4062 				 prog->name, map_idx, map->name, map->sec_idx,
4063 				 map->sec_offset, insn_idx);
4064 			break;
4065 		}
4066 		if (map_idx >= nr_maps) {
4067 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4068 				prog->name, sym_sec_name, (size_t)sym->st_value);
4069 			return -LIBBPF_ERRNO__RELOC;
4070 		}
4071 		reloc_desc->type = RELO_LD64;
4072 		reloc_desc->insn_idx = insn_idx;
4073 		reloc_desc->map_idx = map_idx;
4074 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4075 		return 0;
4076 	}
4077 
4078 	/* global data map relocation */
4079 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4080 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4081 			prog->name, sym_sec_name);
4082 		return -LIBBPF_ERRNO__RELOC;
4083 	}
4084 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4085 		map = &obj->maps[map_idx];
4086 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4087 			continue;
4088 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4089 			 prog->name, map_idx, map->name, map->sec_idx,
4090 			 map->sec_offset, insn_idx);
4091 		break;
4092 	}
4093 	if (map_idx >= nr_maps) {
4094 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4095 			prog->name, sym_sec_name);
4096 		return -LIBBPF_ERRNO__RELOC;
4097 	}
4098 
4099 	reloc_desc->type = RELO_DATA;
4100 	reloc_desc->insn_idx = insn_idx;
4101 	reloc_desc->map_idx = map_idx;
4102 	reloc_desc->sym_off = sym->st_value;
4103 	return 0;
4104 }
4105 
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4106 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4107 {
4108 	return insn_idx >= prog->sec_insn_off &&
4109 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4110 }
4111 
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4112 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4113 						 size_t sec_idx, size_t insn_idx)
4114 {
4115 	int l = 0, r = obj->nr_programs - 1, m;
4116 	struct bpf_program *prog;
4117 
4118 	if (!obj->nr_programs)
4119 		return NULL;
4120 
4121 	while (l < r) {
4122 		m = l + (r - l + 1) / 2;
4123 		prog = &obj->programs[m];
4124 
4125 		if (prog->sec_idx < sec_idx ||
4126 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4127 			l = m;
4128 		else
4129 			r = m - 1;
4130 	}
4131 	/* matching program could be at index l, but it still might be the
4132 	 * wrong one, so we need to double check conditions for the last time
4133 	 */
4134 	prog = &obj->programs[l];
4135 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4136 		return prog;
4137 	return NULL;
4138 }
4139 
4140 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4141 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4142 {
4143 	const char *relo_sec_name, *sec_name;
4144 	size_t sec_idx = shdr->sh_info, sym_idx;
4145 	struct bpf_program *prog;
4146 	struct reloc_desc *relos;
4147 	int err, i, nrels;
4148 	const char *sym_name;
4149 	__u32 insn_idx;
4150 	Elf_Scn *scn;
4151 	Elf_Data *scn_data;
4152 	Elf64_Sym *sym;
4153 	Elf64_Rel *rel;
4154 
4155 	if (sec_idx >= obj->efile.sec_cnt)
4156 		return -EINVAL;
4157 
4158 	scn = elf_sec_by_idx(obj, sec_idx);
4159 	scn_data = elf_sec_data(obj, scn);
4160 	if (!scn_data)
4161 		return -LIBBPF_ERRNO__FORMAT;
4162 
4163 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4164 	sec_name = elf_sec_name(obj, scn);
4165 	if (!relo_sec_name || !sec_name)
4166 		return -EINVAL;
4167 
4168 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4169 		 relo_sec_name, sec_idx, sec_name);
4170 	nrels = shdr->sh_size / shdr->sh_entsize;
4171 
4172 	for (i = 0; i < nrels; i++) {
4173 		rel = elf_rel_by_idx(data, i);
4174 		if (!rel) {
4175 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4176 			return -LIBBPF_ERRNO__FORMAT;
4177 		}
4178 
4179 		sym_idx = ELF64_R_SYM(rel->r_info);
4180 		sym = elf_sym_by_idx(obj, sym_idx);
4181 		if (!sym) {
4182 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4183 				relo_sec_name, sym_idx, i);
4184 			return -LIBBPF_ERRNO__FORMAT;
4185 		}
4186 
4187 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4188 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4189 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4190 			return -LIBBPF_ERRNO__FORMAT;
4191 		}
4192 
4193 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4194 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4195 				relo_sec_name, (size_t)rel->r_offset, i);
4196 			return -LIBBPF_ERRNO__FORMAT;
4197 		}
4198 
4199 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4200 		/* relocations against static functions are recorded as
4201 		 * relocations against the section that contains a function;
4202 		 * in such case, symbol will be STT_SECTION and sym.st_name
4203 		 * will point to empty string (0), so fetch section name
4204 		 * instead
4205 		 */
4206 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4207 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4208 		else
4209 			sym_name = elf_sym_str(obj, sym->st_name);
4210 		sym_name = sym_name ?: "<?";
4211 
4212 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4213 			 relo_sec_name, i, insn_idx, sym_name);
4214 
4215 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4216 		if (!prog) {
4217 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4218 				relo_sec_name, i, sec_name, insn_idx);
4219 			continue;
4220 		}
4221 
4222 		relos = libbpf_reallocarray(prog->reloc_desc,
4223 					    prog->nr_reloc + 1, sizeof(*relos));
4224 		if (!relos)
4225 			return -ENOMEM;
4226 		prog->reloc_desc = relos;
4227 
4228 		/* adjust insn_idx to local BPF program frame of reference */
4229 		insn_idx -= prog->sec_insn_off;
4230 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4231 						insn_idx, sym_name, sym, rel);
4232 		if (err)
4233 			return err;
4234 
4235 		prog->nr_reloc++;
4236 	}
4237 	return 0;
4238 }
4239 
bpf_map_find_btf_info(struct bpf_object * obj,struct bpf_map * map)4240 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4241 {
4242 	int id;
4243 
4244 	if (!obj->btf)
4245 		return -ENOENT;
4246 
4247 	/* if it's BTF-defined map, we don't need to search for type IDs.
4248 	 * For struct_ops map, it does not need btf_key_type_id and
4249 	 * btf_value_type_id.
4250 	 */
4251 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4252 		return 0;
4253 
4254 	/*
4255 	 * LLVM annotates global data differently in BTF, that is,
4256 	 * only as '.data', '.bss' or '.rodata'.
4257 	 */
4258 	if (!bpf_map__is_internal(map))
4259 		return -ENOENT;
4260 
4261 	id = btf__find_by_name(obj->btf, map->real_name);
4262 	if (id < 0)
4263 		return id;
4264 
4265 	map->btf_key_type_id = 0;
4266 	map->btf_value_type_id = id;
4267 	return 0;
4268 }
4269 
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4270 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4271 {
4272 	char file[PATH_MAX], buff[4096];
4273 	FILE *fp;
4274 	__u32 val;
4275 	int err;
4276 
4277 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4278 	memset(info, 0, sizeof(*info));
4279 
4280 	fp = fopen(file, "r");
4281 	if (!fp) {
4282 		err = -errno;
4283 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4284 			err);
4285 		return err;
4286 	}
4287 
4288 	while (fgets(buff, sizeof(buff), fp)) {
4289 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4290 			info->type = val;
4291 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4292 			info->key_size = val;
4293 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4294 			info->value_size = val;
4295 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4296 			info->max_entries = val;
4297 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4298 			info->map_flags = val;
4299 	}
4300 
4301 	fclose(fp);
4302 
4303 	return 0;
4304 }
4305 
bpf_map__autocreate(const struct bpf_map * map)4306 bool bpf_map__autocreate(const struct bpf_map *map)
4307 {
4308 	return map->autocreate;
4309 }
4310 
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4311 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4312 {
4313 	if (map->obj->loaded)
4314 		return libbpf_err(-EBUSY);
4315 
4316 	map->autocreate = autocreate;
4317 	return 0;
4318 }
4319 
bpf_map__reuse_fd(struct bpf_map * map,int fd)4320 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4321 {
4322 	struct bpf_map_info info;
4323 	__u32 len = sizeof(info), name_len;
4324 	int new_fd, err;
4325 	char *new_name;
4326 
4327 	memset(&info, 0, len);
4328 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4329 	if (err && errno == EINVAL)
4330 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4331 	if (err)
4332 		return libbpf_err(err);
4333 
4334 	name_len = strlen(info.name);
4335 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4336 		new_name = strdup(map->name);
4337 	else
4338 		new_name = strdup(info.name);
4339 
4340 	if (!new_name)
4341 		return libbpf_err(-errno);
4342 
4343 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4344 	if (new_fd < 0) {
4345 		err = -errno;
4346 		goto err_free_new_name;
4347 	}
4348 
4349 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4350 	if (new_fd < 0) {
4351 		err = -errno;
4352 		goto err_close_new_fd;
4353 	}
4354 
4355 	err = zclose(map->fd);
4356 	if (err) {
4357 		err = -errno;
4358 		goto err_close_new_fd;
4359 	}
4360 	free(map->name);
4361 
4362 	map->fd = new_fd;
4363 	map->name = new_name;
4364 	map->def.type = info.type;
4365 	map->def.key_size = info.key_size;
4366 	map->def.value_size = info.value_size;
4367 	map->def.max_entries = info.max_entries;
4368 	map->def.map_flags = info.map_flags;
4369 	map->btf_key_type_id = info.btf_key_type_id;
4370 	map->btf_value_type_id = info.btf_value_type_id;
4371 	map->reused = true;
4372 	map->map_extra = info.map_extra;
4373 
4374 	return 0;
4375 
4376 err_close_new_fd:
4377 	close(new_fd);
4378 err_free_new_name:
4379 	free(new_name);
4380 	return libbpf_err(err);
4381 }
4382 
bpf_map__max_entries(const struct bpf_map * map)4383 __u32 bpf_map__max_entries(const struct bpf_map *map)
4384 {
4385 	return map->def.max_entries;
4386 }
4387 
bpf_map__inner_map(struct bpf_map * map)4388 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4389 {
4390 	if (!bpf_map_type__is_map_in_map(map->def.type))
4391 		return errno = EINVAL, NULL;
4392 
4393 	return map->inner_map;
4394 }
4395 
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4396 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4397 {
4398 	if (map->obj->loaded)
4399 		return libbpf_err(-EBUSY);
4400 
4401 	map->def.max_entries = max_entries;
4402 
4403 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4404 	if (map_is_ringbuf(map))
4405 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4406 
4407 	return 0;
4408 }
4409 
4410 static int
bpf_object__probe_loading(struct bpf_object * obj)4411 bpf_object__probe_loading(struct bpf_object *obj)
4412 {
4413 	char *cp, errmsg[STRERR_BUFSIZE];
4414 	struct bpf_insn insns[] = {
4415 		BPF_MOV64_IMM(BPF_REG_0, 0),
4416 		BPF_EXIT_INSN(),
4417 	};
4418 	int ret, insn_cnt = ARRAY_SIZE(insns);
4419 
4420 	if (obj->gen_loader)
4421 		return 0;
4422 
4423 	ret = bump_rlimit_memlock();
4424 	if (ret)
4425 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4426 
4427 	/* make sure basic loading works */
4428 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4429 	if (ret < 0)
4430 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4431 	if (ret < 0) {
4432 		ret = errno;
4433 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4434 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4435 			"program. Make sure your kernel supports BPF "
4436 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4437 			"set to big enough value.\n", __func__, cp, ret);
4438 		return -ret;
4439 	}
4440 	close(ret);
4441 
4442 	return 0;
4443 }
4444 
probe_fd(int fd)4445 static int probe_fd(int fd)
4446 {
4447 	if (fd >= 0)
4448 		close(fd);
4449 	return fd >= 0;
4450 }
4451 
probe_kern_prog_name(void)4452 static int probe_kern_prog_name(void)
4453 {
4454 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4455 	struct bpf_insn insns[] = {
4456 		BPF_MOV64_IMM(BPF_REG_0, 0),
4457 		BPF_EXIT_INSN(),
4458 	};
4459 	union bpf_attr attr;
4460 	int ret;
4461 
4462 	memset(&attr, 0, attr_sz);
4463 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4464 	attr.license = ptr_to_u64("GPL");
4465 	attr.insns = ptr_to_u64(insns);
4466 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4467 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4468 
4469 	/* make sure loading with name works */
4470 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4471 	return probe_fd(ret);
4472 }
4473 
probe_kern_global_data(void)4474 static int probe_kern_global_data(void)
4475 {
4476 	char *cp, errmsg[STRERR_BUFSIZE];
4477 	struct bpf_insn insns[] = {
4478 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4479 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4480 		BPF_MOV64_IMM(BPF_REG_0, 0),
4481 		BPF_EXIT_INSN(),
4482 	};
4483 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4484 
4485 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4486 	if (map < 0) {
4487 		ret = -errno;
4488 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4489 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4490 			__func__, cp, -ret);
4491 		return ret;
4492 	}
4493 
4494 	insns[0].imm = map;
4495 
4496 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4497 	close(map);
4498 	return probe_fd(ret);
4499 }
4500 
probe_kern_btf(void)4501 static int probe_kern_btf(void)
4502 {
4503 	static const char strs[] = "\0int";
4504 	__u32 types[] = {
4505 		/* int */
4506 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4507 	};
4508 
4509 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4510 					     strs, sizeof(strs)));
4511 }
4512 
probe_kern_btf_func(void)4513 static int probe_kern_btf_func(void)
4514 {
4515 	static const char strs[] = "\0int\0x\0a";
4516 	/* void x(int a) {} */
4517 	__u32 types[] = {
4518 		/* int */
4519 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4520 		/* FUNC_PROTO */                                /* [2] */
4521 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4522 		BTF_PARAM_ENC(7, 1),
4523 		/* FUNC x */                                    /* [3] */
4524 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4525 	};
4526 
4527 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4528 					     strs, sizeof(strs)));
4529 }
4530 
probe_kern_btf_func_global(void)4531 static int probe_kern_btf_func_global(void)
4532 {
4533 	static const char strs[] = "\0int\0x\0a";
4534 	/* static void x(int a) {} */
4535 	__u32 types[] = {
4536 		/* int */
4537 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4538 		/* FUNC_PROTO */                                /* [2] */
4539 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4540 		BTF_PARAM_ENC(7, 1),
4541 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4542 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4543 	};
4544 
4545 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4546 					     strs, sizeof(strs)));
4547 }
4548 
probe_kern_btf_datasec(void)4549 static int probe_kern_btf_datasec(void)
4550 {
4551 	static const char strs[] = "\0x\0.data";
4552 	/* static int a; */
4553 	__u32 types[] = {
4554 		/* int */
4555 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4556 		/* VAR x */                                     /* [2] */
4557 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4558 		BTF_VAR_STATIC,
4559 		/* DATASEC val */                               /* [3] */
4560 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4561 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4562 	};
4563 
4564 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4565 					     strs, sizeof(strs)));
4566 }
4567 
probe_kern_btf_float(void)4568 static int probe_kern_btf_float(void)
4569 {
4570 	static const char strs[] = "\0float";
4571 	__u32 types[] = {
4572 		/* float */
4573 		BTF_TYPE_FLOAT_ENC(1, 4),
4574 	};
4575 
4576 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4577 					     strs, sizeof(strs)));
4578 }
4579 
probe_kern_btf_decl_tag(void)4580 static int probe_kern_btf_decl_tag(void)
4581 {
4582 	static const char strs[] = "\0tag";
4583 	__u32 types[] = {
4584 		/* int */
4585 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4586 		/* VAR x */                                     /* [2] */
4587 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4588 		BTF_VAR_STATIC,
4589 		/* attr */
4590 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4591 	};
4592 
4593 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4594 					     strs, sizeof(strs)));
4595 }
4596 
probe_kern_btf_type_tag(void)4597 static int probe_kern_btf_type_tag(void)
4598 {
4599 	static const char strs[] = "\0tag";
4600 	__u32 types[] = {
4601 		/* int */
4602 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4603 		/* attr */
4604 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4605 		/* ptr */
4606 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4607 	};
4608 
4609 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4610 					     strs, sizeof(strs)));
4611 }
4612 
probe_kern_array_mmap(void)4613 static int probe_kern_array_mmap(void)
4614 {
4615 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4616 	int fd;
4617 
4618 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4619 	return probe_fd(fd);
4620 }
4621 
probe_kern_exp_attach_type(void)4622 static int probe_kern_exp_attach_type(void)
4623 {
4624 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4625 	struct bpf_insn insns[] = {
4626 		BPF_MOV64_IMM(BPF_REG_0, 0),
4627 		BPF_EXIT_INSN(),
4628 	};
4629 	int fd, insn_cnt = ARRAY_SIZE(insns);
4630 
4631 	/* use any valid combination of program type and (optional)
4632 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4633 	 * to see if kernel supports expected_attach_type field for
4634 	 * BPF_PROG_LOAD command
4635 	 */
4636 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4637 	return probe_fd(fd);
4638 }
4639 
probe_kern_probe_read_kernel(void)4640 static int probe_kern_probe_read_kernel(void)
4641 {
4642 	struct bpf_insn insns[] = {
4643 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4644 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4645 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4646 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4647 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4648 		BPF_EXIT_INSN(),
4649 	};
4650 	int fd, insn_cnt = ARRAY_SIZE(insns);
4651 
4652 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4653 	return probe_fd(fd);
4654 }
4655 
probe_prog_bind_map(void)4656 static int probe_prog_bind_map(void)
4657 {
4658 	char *cp, errmsg[STRERR_BUFSIZE];
4659 	struct bpf_insn insns[] = {
4660 		BPF_MOV64_IMM(BPF_REG_0, 0),
4661 		BPF_EXIT_INSN(),
4662 	};
4663 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4664 
4665 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4666 	if (map < 0) {
4667 		ret = -errno;
4668 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4669 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4670 			__func__, cp, -ret);
4671 		return ret;
4672 	}
4673 
4674 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4675 	if (prog < 0) {
4676 		close(map);
4677 		return 0;
4678 	}
4679 
4680 	ret = bpf_prog_bind_map(prog, map, NULL);
4681 
4682 	close(map);
4683 	close(prog);
4684 
4685 	return ret >= 0;
4686 }
4687 
probe_module_btf(void)4688 static int probe_module_btf(void)
4689 {
4690 	static const char strs[] = "\0int";
4691 	__u32 types[] = {
4692 		/* int */
4693 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4694 	};
4695 	struct bpf_btf_info info;
4696 	__u32 len = sizeof(info);
4697 	char name[16];
4698 	int fd, err;
4699 
4700 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4701 	if (fd < 0)
4702 		return 0; /* BTF not supported at all */
4703 
4704 	memset(&info, 0, sizeof(info));
4705 	info.name = ptr_to_u64(name);
4706 	info.name_len = sizeof(name);
4707 
4708 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4709 	 * kernel's module BTF support coincides with support for
4710 	 * name/name_len fields in struct bpf_btf_info.
4711 	 */
4712 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4713 	close(fd);
4714 	return !err;
4715 }
4716 
probe_perf_link(void)4717 static int probe_perf_link(void)
4718 {
4719 	struct bpf_insn insns[] = {
4720 		BPF_MOV64_IMM(BPF_REG_0, 0),
4721 		BPF_EXIT_INSN(),
4722 	};
4723 	int prog_fd, link_fd, err;
4724 
4725 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4726 				insns, ARRAY_SIZE(insns), NULL);
4727 	if (prog_fd < 0)
4728 		return -errno;
4729 
4730 	/* use invalid perf_event FD to get EBADF, if link is supported;
4731 	 * otherwise EINVAL should be returned
4732 	 */
4733 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4734 	err = -errno; /* close() can clobber errno */
4735 
4736 	if (link_fd >= 0)
4737 		close(link_fd);
4738 	close(prog_fd);
4739 
4740 	return link_fd < 0 && err == -EBADF;
4741 }
4742 
probe_kern_bpf_cookie(void)4743 static int probe_kern_bpf_cookie(void)
4744 {
4745 	struct bpf_insn insns[] = {
4746 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4747 		BPF_EXIT_INSN(),
4748 	};
4749 	int ret, insn_cnt = ARRAY_SIZE(insns);
4750 
4751 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4752 	return probe_fd(ret);
4753 }
4754 
probe_kern_btf_enum64(void)4755 static int probe_kern_btf_enum64(void)
4756 {
4757 	static const char strs[] = "\0enum64";
4758 	__u32 types[] = {
4759 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4760 	};
4761 
4762 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4763 					     strs, sizeof(strs)));
4764 }
4765 
4766 static int probe_kern_syscall_wrapper(void);
4767 
4768 enum kern_feature_result {
4769 	FEAT_UNKNOWN = 0,
4770 	FEAT_SUPPORTED = 1,
4771 	FEAT_MISSING = 2,
4772 };
4773 
4774 typedef int (*feature_probe_fn)(void);
4775 
4776 static struct kern_feature_desc {
4777 	const char *desc;
4778 	feature_probe_fn probe;
4779 	enum kern_feature_result res;
4780 } feature_probes[__FEAT_CNT] = {
4781 	[FEAT_PROG_NAME] = {
4782 		"BPF program name", probe_kern_prog_name,
4783 	},
4784 	[FEAT_GLOBAL_DATA] = {
4785 		"global variables", probe_kern_global_data,
4786 	},
4787 	[FEAT_BTF] = {
4788 		"minimal BTF", probe_kern_btf,
4789 	},
4790 	[FEAT_BTF_FUNC] = {
4791 		"BTF functions", probe_kern_btf_func,
4792 	},
4793 	[FEAT_BTF_GLOBAL_FUNC] = {
4794 		"BTF global function", probe_kern_btf_func_global,
4795 	},
4796 	[FEAT_BTF_DATASEC] = {
4797 		"BTF data section and variable", probe_kern_btf_datasec,
4798 	},
4799 	[FEAT_ARRAY_MMAP] = {
4800 		"ARRAY map mmap()", probe_kern_array_mmap,
4801 	},
4802 	[FEAT_EXP_ATTACH_TYPE] = {
4803 		"BPF_PROG_LOAD expected_attach_type attribute",
4804 		probe_kern_exp_attach_type,
4805 	},
4806 	[FEAT_PROBE_READ_KERN] = {
4807 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4808 	},
4809 	[FEAT_PROG_BIND_MAP] = {
4810 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4811 	},
4812 	[FEAT_MODULE_BTF] = {
4813 		"module BTF support", probe_module_btf,
4814 	},
4815 	[FEAT_BTF_FLOAT] = {
4816 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4817 	},
4818 	[FEAT_PERF_LINK] = {
4819 		"BPF perf link support", probe_perf_link,
4820 	},
4821 	[FEAT_BTF_DECL_TAG] = {
4822 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4823 	},
4824 	[FEAT_BTF_TYPE_TAG] = {
4825 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4826 	},
4827 	[FEAT_MEMCG_ACCOUNT] = {
4828 		"memcg-based memory accounting", probe_memcg_account,
4829 	},
4830 	[FEAT_BPF_COOKIE] = {
4831 		"BPF cookie support", probe_kern_bpf_cookie,
4832 	},
4833 	[FEAT_BTF_ENUM64] = {
4834 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4835 	},
4836 	[FEAT_SYSCALL_WRAPPER] = {
4837 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4838 	},
4839 };
4840 
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)4841 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4842 {
4843 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4844 	int ret;
4845 
4846 	if (obj && obj->gen_loader)
4847 		/* To generate loader program assume the latest kernel
4848 		 * to avoid doing extra prog_load, map_create syscalls.
4849 		 */
4850 		return true;
4851 
4852 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4853 		ret = feat->probe();
4854 		if (ret > 0) {
4855 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4856 		} else if (ret == 0) {
4857 			WRITE_ONCE(feat->res, FEAT_MISSING);
4858 		} else {
4859 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4860 			WRITE_ONCE(feat->res, FEAT_MISSING);
4861 		}
4862 	}
4863 
4864 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4865 }
4866 
map_is_reuse_compat(const struct bpf_map * map,int map_fd)4867 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4868 {
4869 	struct bpf_map_info map_info;
4870 	char msg[STRERR_BUFSIZE];
4871 	__u32 map_info_len = sizeof(map_info);
4872 	int err;
4873 
4874 	memset(&map_info, 0, map_info_len);
4875 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4876 	if (err && errno == EINVAL)
4877 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4878 	if (err) {
4879 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4880 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4881 		return false;
4882 	}
4883 
4884 	return (map_info.type == map->def.type &&
4885 		map_info.key_size == map->def.key_size &&
4886 		map_info.value_size == map->def.value_size &&
4887 		map_info.max_entries == map->def.max_entries &&
4888 		map_info.map_flags == map->def.map_flags &&
4889 		map_info.map_extra == map->map_extra);
4890 }
4891 
4892 static int
bpf_object__reuse_map(struct bpf_map * map)4893 bpf_object__reuse_map(struct bpf_map *map)
4894 {
4895 	char *cp, errmsg[STRERR_BUFSIZE];
4896 	int err, pin_fd;
4897 
4898 	pin_fd = bpf_obj_get(map->pin_path);
4899 	if (pin_fd < 0) {
4900 		err = -errno;
4901 		if (err == -ENOENT) {
4902 			pr_debug("found no pinned map to reuse at '%s'\n",
4903 				 map->pin_path);
4904 			return 0;
4905 		}
4906 
4907 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4908 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4909 			map->pin_path, cp);
4910 		return err;
4911 	}
4912 
4913 	if (!map_is_reuse_compat(map, pin_fd)) {
4914 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4915 			map->pin_path);
4916 		close(pin_fd);
4917 		return -EINVAL;
4918 	}
4919 
4920 	err = bpf_map__reuse_fd(map, pin_fd);
4921 	close(pin_fd);
4922 	if (err) {
4923 		return err;
4924 	}
4925 	map->pinned = true;
4926 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4927 
4928 	return 0;
4929 }
4930 
4931 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)4932 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4933 {
4934 	enum libbpf_map_type map_type = map->libbpf_type;
4935 	char *cp, errmsg[STRERR_BUFSIZE];
4936 	int err, zero = 0;
4937 
4938 	if (obj->gen_loader) {
4939 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4940 					 map->mmaped, map->def.value_size);
4941 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4942 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4943 		return 0;
4944 	}
4945 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4946 	if (err) {
4947 		err = -errno;
4948 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4949 		pr_warn("Error setting initial map(%s) contents: %s\n",
4950 			map->name, cp);
4951 		return err;
4952 	}
4953 
4954 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
4955 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4956 		err = bpf_map_freeze(map->fd);
4957 		if (err) {
4958 			err = -errno;
4959 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4960 			pr_warn("Error freezing map(%s) as read-only: %s\n",
4961 				map->name, cp);
4962 			return err;
4963 		}
4964 	}
4965 	return 0;
4966 }
4967 
4968 static void bpf_map__destroy(struct bpf_map *map);
4969 
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)4970 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4971 {
4972 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4973 	struct bpf_map_def *def = &map->def;
4974 	const char *map_name = NULL;
4975 	int err = 0;
4976 
4977 	if (kernel_supports(obj, FEAT_PROG_NAME))
4978 		map_name = map->name;
4979 	create_attr.map_ifindex = map->map_ifindex;
4980 	create_attr.map_flags = def->map_flags;
4981 	create_attr.numa_node = map->numa_node;
4982 	create_attr.map_extra = map->map_extra;
4983 
4984 	if (bpf_map__is_struct_ops(map))
4985 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4986 
4987 	if (obj->btf && btf__fd(obj->btf) >= 0) {
4988 		create_attr.btf_fd = btf__fd(obj->btf);
4989 		create_attr.btf_key_type_id = map->btf_key_type_id;
4990 		create_attr.btf_value_type_id = map->btf_value_type_id;
4991 	}
4992 
4993 	if (bpf_map_type__is_map_in_map(def->type)) {
4994 		if (map->inner_map) {
4995 			err = bpf_object__create_map(obj, map->inner_map, true);
4996 			if (err) {
4997 				pr_warn("map '%s': failed to create inner map: %d\n",
4998 					map->name, err);
4999 				return err;
5000 			}
5001 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5002 		}
5003 		if (map->inner_map_fd >= 0)
5004 			create_attr.inner_map_fd = map->inner_map_fd;
5005 	}
5006 
5007 	switch (def->type) {
5008 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5009 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5010 	case BPF_MAP_TYPE_STACK_TRACE:
5011 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5012 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5013 	case BPF_MAP_TYPE_DEVMAP:
5014 	case BPF_MAP_TYPE_DEVMAP_HASH:
5015 	case BPF_MAP_TYPE_CPUMAP:
5016 	case BPF_MAP_TYPE_XSKMAP:
5017 	case BPF_MAP_TYPE_SOCKMAP:
5018 	case BPF_MAP_TYPE_SOCKHASH:
5019 	case BPF_MAP_TYPE_QUEUE:
5020 	case BPF_MAP_TYPE_STACK:
5021 		create_attr.btf_fd = 0;
5022 		create_attr.btf_key_type_id = 0;
5023 		create_attr.btf_value_type_id = 0;
5024 		map->btf_key_type_id = 0;
5025 		map->btf_value_type_id = 0;
5026 	default:
5027 		break;
5028 	}
5029 
5030 	if (obj->gen_loader) {
5031 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5032 				    def->key_size, def->value_size, def->max_entries,
5033 				    &create_attr, is_inner ? -1 : map - obj->maps);
5034 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5035 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5036 		 */
5037 		map->fd = 0;
5038 	} else {
5039 		map->fd = bpf_map_create(def->type, map_name,
5040 					 def->key_size, def->value_size,
5041 					 def->max_entries, &create_attr);
5042 	}
5043 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5044 			    create_attr.btf_value_type_id)) {
5045 		char *cp, errmsg[STRERR_BUFSIZE];
5046 
5047 		err = -errno;
5048 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5049 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5050 			map->name, cp, err);
5051 		create_attr.btf_fd = 0;
5052 		create_attr.btf_key_type_id = 0;
5053 		create_attr.btf_value_type_id = 0;
5054 		map->btf_key_type_id = 0;
5055 		map->btf_value_type_id = 0;
5056 		map->fd = bpf_map_create(def->type, map_name,
5057 					 def->key_size, def->value_size,
5058 					 def->max_entries, &create_attr);
5059 	}
5060 
5061 	err = map->fd < 0 ? -errno : 0;
5062 
5063 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5064 		if (obj->gen_loader)
5065 			map->inner_map->fd = -1;
5066 		bpf_map__destroy(map->inner_map);
5067 		zfree(&map->inner_map);
5068 	}
5069 
5070 	return err;
5071 }
5072 
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5073 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5074 {
5075 	const struct bpf_map *targ_map;
5076 	unsigned int i;
5077 	int fd, err = 0;
5078 
5079 	for (i = 0; i < map->init_slots_sz; i++) {
5080 		if (!map->init_slots[i])
5081 			continue;
5082 
5083 		targ_map = map->init_slots[i];
5084 		fd = bpf_map__fd(targ_map);
5085 
5086 		if (obj->gen_loader) {
5087 			bpf_gen__populate_outer_map(obj->gen_loader,
5088 						    map - obj->maps, i,
5089 						    targ_map - obj->maps);
5090 		} else {
5091 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5092 		}
5093 		if (err) {
5094 			err = -errno;
5095 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5096 				map->name, i, targ_map->name, fd, err);
5097 			return err;
5098 		}
5099 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5100 			 map->name, i, targ_map->name, fd);
5101 	}
5102 
5103 	zfree(&map->init_slots);
5104 	map->init_slots_sz = 0;
5105 
5106 	return 0;
5107 }
5108 
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5109 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5110 {
5111 	const struct bpf_program *targ_prog;
5112 	unsigned int i;
5113 	int fd, err;
5114 
5115 	if (obj->gen_loader)
5116 		return -ENOTSUP;
5117 
5118 	for (i = 0; i < map->init_slots_sz; i++) {
5119 		if (!map->init_slots[i])
5120 			continue;
5121 
5122 		targ_prog = map->init_slots[i];
5123 		fd = bpf_program__fd(targ_prog);
5124 
5125 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5126 		if (err) {
5127 			err = -errno;
5128 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5129 				map->name, i, targ_prog->name, fd, err);
5130 			return err;
5131 		}
5132 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5133 			 map->name, i, targ_prog->name, fd);
5134 	}
5135 
5136 	zfree(&map->init_slots);
5137 	map->init_slots_sz = 0;
5138 
5139 	return 0;
5140 }
5141 
bpf_object_init_prog_arrays(struct bpf_object * obj)5142 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5143 {
5144 	struct bpf_map *map;
5145 	int i, err;
5146 
5147 	for (i = 0; i < obj->nr_maps; i++) {
5148 		map = &obj->maps[i];
5149 
5150 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5151 			continue;
5152 
5153 		err = init_prog_array_slots(obj, map);
5154 		if (err < 0) {
5155 			zclose(map->fd);
5156 			return err;
5157 		}
5158 	}
5159 	return 0;
5160 }
5161 
map_set_def_max_entries(struct bpf_map * map)5162 static int map_set_def_max_entries(struct bpf_map *map)
5163 {
5164 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5165 		int nr_cpus;
5166 
5167 		nr_cpus = libbpf_num_possible_cpus();
5168 		if (nr_cpus < 0) {
5169 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5170 				map->name, nr_cpus);
5171 			return nr_cpus;
5172 		}
5173 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5174 		map->def.max_entries = nr_cpus;
5175 	}
5176 
5177 	return 0;
5178 }
5179 
5180 static int
bpf_object__create_maps(struct bpf_object * obj)5181 bpf_object__create_maps(struct bpf_object *obj)
5182 {
5183 	struct bpf_map *map;
5184 	char *cp, errmsg[STRERR_BUFSIZE];
5185 	unsigned int i, j;
5186 	int err;
5187 	bool retried;
5188 
5189 	for (i = 0; i < obj->nr_maps; i++) {
5190 		map = &obj->maps[i];
5191 
5192 		/* To support old kernels, we skip creating global data maps
5193 		 * (.rodata, .data, .kconfig, etc); later on, during program
5194 		 * loading, if we detect that at least one of the to-be-loaded
5195 		 * programs is referencing any global data map, we'll error
5196 		 * out with program name and relocation index logged.
5197 		 * This approach allows to accommodate Clang emitting
5198 		 * unnecessary .rodata.str1.1 sections for string literals,
5199 		 * but also it allows to have CO-RE applications that use
5200 		 * global variables in some of BPF programs, but not others.
5201 		 * If those global variable-using programs are not loaded at
5202 		 * runtime due to bpf_program__set_autoload(prog, false),
5203 		 * bpf_object loading will succeed just fine even on old
5204 		 * kernels.
5205 		 */
5206 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5207 			map->autocreate = false;
5208 
5209 		if (!map->autocreate) {
5210 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5211 			continue;
5212 		}
5213 
5214 		err = map_set_def_max_entries(map);
5215 		if (err)
5216 			goto err_out;
5217 
5218 		retried = false;
5219 retry:
5220 		if (map->pin_path) {
5221 			err = bpf_object__reuse_map(map);
5222 			if (err) {
5223 				pr_warn("map '%s': error reusing pinned map\n",
5224 					map->name);
5225 				goto err_out;
5226 			}
5227 			if (retried && map->fd < 0) {
5228 				pr_warn("map '%s': cannot find pinned map\n",
5229 					map->name);
5230 				err = -ENOENT;
5231 				goto err_out;
5232 			}
5233 		}
5234 
5235 		if (map->fd >= 0) {
5236 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5237 				 map->name, map->fd);
5238 		} else {
5239 			err = bpf_object__create_map(obj, map, false);
5240 			if (err)
5241 				goto err_out;
5242 
5243 			pr_debug("map '%s': created successfully, fd=%d\n",
5244 				 map->name, map->fd);
5245 
5246 			if (bpf_map__is_internal(map)) {
5247 				err = bpf_object__populate_internal_map(obj, map);
5248 				if (err < 0) {
5249 					zclose(map->fd);
5250 					goto err_out;
5251 				}
5252 			}
5253 
5254 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5255 				err = init_map_in_map_slots(obj, map);
5256 				if (err < 0) {
5257 					zclose(map->fd);
5258 					goto err_out;
5259 				}
5260 			}
5261 		}
5262 
5263 		if (map->pin_path && !map->pinned) {
5264 			err = bpf_map__pin(map, NULL);
5265 			if (err) {
5266 				zclose(map->fd);
5267 				if (!retried && err == -EEXIST) {
5268 					retried = true;
5269 					goto retry;
5270 				}
5271 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5272 					map->name, map->pin_path, err);
5273 				goto err_out;
5274 			}
5275 		}
5276 	}
5277 
5278 	return 0;
5279 
5280 err_out:
5281 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5282 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5283 	pr_perm_msg(err);
5284 	for (j = 0; j < i; j++)
5285 		zclose(obj->maps[j].fd);
5286 	return err;
5287 }
5288 
bpf_core_is_flavor_sep(const char * s)5289 static bool bpf_core_is_flavor_sep(const char *s)
5290 {
5291 	/* check X___Y name pattern, where X and Y are not underscores */
5292 	return s[0] != '_' &&				      /* X */
5293 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5294 	       s[4] != '_';				      /* Y */
5295 }
5296 
5297 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5298  * before last triple underscore. Struct name part after last triple
5299  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5300  */
bpf_core_essential_name_len(const char * name)5301 size_t bpf_core_essential_name_len(const char *name)
5302 {
5303 	size_t n = strlen(name);
5304 	int i;
5305 
5306 	for (i = n - 5; i >= 0; i--) {
5307 		if (bpf_core_is_flavor_sep(name + i))
5308 			return i + 1;
5309 	}
5310 	return n;
5311 }
5312 
bpf_core_free_cands(struct bpf_core_cand_list * cands)5313 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5314 {
5315 	if (!cands)
5316 		return;
5317 
5318 	free(cands->cands);
5319 	free(cands);
5320 }
5321 
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)5322 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5323 		       size_t local_essent_len,
5324 		       const struct btf *targ_btf,
5325 		       const char *targ_btf_name,
5326 		       int targ_start_id,
5327 		       struct bpf_core_cand_list *cands)
5328 {
5329 	struct bpf_core_cand *new_cands, *cand;
5330 	const struct btf_type *t, *local_t;
5331 	const char *targ_name, *local_name;
5332 	size_t targ_essent_len;
5333 	int n, i;
5334 
5335 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5336 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5337 
5338 	n = btf__type_cnt(targ_btf);
5339 	for (i = targ_start_id; i < n; i++) {
5340 		t = btf__type_by_id(targ_btf, i);
5341 		if (!btf_kind_core_compat(t, local_t))
5342 			continue;
5343 
5344 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5345 		if (str_is_empty(targ_name))
5346 			continue;
5347 
5348 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5349 		if (targ_essent_len != local_essent_len)
5350 			continue;
5351 
5352 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5353 			continue;
5354 
5355 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5356 			 local_cand->id, btf_kind_str(local_t),
5357 			 local_name, i, btf_kind_str(t), targ_name,
5358 			 targ_btf_name);
5359 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5360 					      sizeof(*cands->cands));
5361 		if (!new_cands)
5362 			return -ENOMEM;
5363 
5364 		cand = &new_cands[cands->len];
5365 		cand->btf = targ_btf;
5366 		cand->id = i;
5367 
5368 		cands->cands = new_cands;
5369 		cands->len++;
5370 	}
5371 	return 0;
5372 }
5373 
load_module_btfs(struct bpf_object * obj)5374 static int load_module_btfs(struct bpf_object *obj)
5375 {
5376 	struct bpf_btf_info info;
5377 	struct module_btf *mod_btf;
5378 	struct btf *btf;
5379 	char name[64];
5380 	__u32 id = 0, len;
5381 	int err, fd;
5382 
5383 	if (obj->btf_modules_loaded)
5384 		return 0;
5385 
5386 	if (obj->gen_loader)
5387 		return 0;
5388 
5389 	/* don't do this again, even if we find no module BTFs */
5390 	obj->btf_modules_loaded = true;
5391 
5392 	/* kernel too old to support module BTFs */
5393 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5394 		return 0;
5395 
5396 	while (true) {
5397 		err = bpf_btf_get_next_id(id, &id);
5398 		if (err && errno == ENOENT)
5399 			return 0;
5400 		if (err) {
5401 			err = -errno;
5402 			pr_warn("failed to iterate BTF objects: %d\n", err);
5403 			return err;
5404 		}
5405 
5406 		fd = bpf_btf_get_fd_by_id(id);
5407 		if (fd < 0) {
5408 			if (errno == ENOENT)
5409 				continue; /* expected race: BTF was unloaded */
5410 			err = -errno;
5411 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5412 			return err;
5413 		}
5414 
5415 		len = sizeof(info);
5416 		memset(&info, 0, sizeof(info));
5417 		info.name = ptr_to_u64(name);
5418 		info.name_len = sizeof(name);
5419 
5420 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5421 		if (err) {
5422 			err = -errno;
5423 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5424 			goto err_out;
5425 		}
5426 
5427 		/* ignore non-module BTFs */
5428 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5429 			close(fd);
5430 			continue;
5431 		}
5432 
5433 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5434 		err = libbpf_get_error(btf);
5435 		if (err) {
5436 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5437 				name, id, err);
5438 			goto err_out;
5439 		}
5440 
5441 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5442 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5443 		if (err)
5444 			goto err_out;
5445 
5446 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5447 
5448 		mod_btf->btf = btf;
5449 		mod_btf->id = id;
5450 		mod_btf->fd = fd;
5451 		mod_btf->name = strdup(name);
5452 		if (!mod_btf->name) {
5453 			err = -ENOMEM;
5454 			goto err_out;
5455 		}
5456 		continue;
5457 
5458 err_out:
5459 		close(fd);
5460 		return err;
5461 	}
5462 
5463 	return 0;
5464 }
5465 
5466 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5467 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5468 {
5469 	struct bpf_core_cand local_cand = {};
5470 	struct bpf_core_cand_list *cands;
5471 	const struct btf *main_btf;
5472 	const struct btf_type *local_t;
5473 	const char *local_name;
5474 	size_t local_essent_len;
5475 	int err, i;
5476 
5477 	local_cand.btf = local_btf;
5478 	local_cand.id = local_type_id;
5479 	local_t = btf__type_by_id(local_btf, local_type_id);
5480 	if (!local_t)
5481 		return ERR_PTR(-EINVAL);
5482 
5483 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5484 	if (str_is_empty(local_name))
5485 		return ERR_PTR(-EINVAL);
5486 	local_essent_len = bpf_core_essential_name_len(local_name);
5487 
5488 	cands = calloc(1, sizeof(*cands));
5489 	if (!cands)
5490 		return ERR_PTR(-ENOMEM);
5491 
5492 	/* Attempt to find target candidates in vmlinux BTF first */
5493 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5494 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5495 	if (err)
5496 		goto err_out;
5497 
5498 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5499 	if (cands->len)
5500 		return cands;
5501 
5502 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5503 	if (obj->btf_vmlinux_override)
5504 		return cands;
5505 
5506 	/* now look through module BTFs, trying to still find candidates */
5507 	err = load_module_btfs(obj);
5508 	if (err)
5509 		goto err_out;
5510 
5511 	for (i = 0; i < obj->btf_module_cnt; i++) {
5512 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5513 					 obj->btf_modules[i].btf,
5514 					 obj->btf_modules[i].name,
5515 					 btf__type_cnt(obj->btf_vmlinux),
5516 					 cands);
5517 		if (err)
5518 			goto err_out;
5519 	}
5520 
5521 	return cands;
5522 err_out:
5523 	bpf_core_free_cands(cands);
5524 	return ERR_PTR(err);
5525 }
5526 
5527 /* Check local and target types for compatibility. This check is used for
5528  * type-based CO-RE relocations and follow slightly different rules than
5529  * field-based relocations. This function assumes that root types were already
5530  * checked for name match. Beyond that initial root-level name check, names
5531  * are completely ignored. Compatibility rules are as follows:
5532  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5533  *     kind should match for local and target types (i.e., STRUCT is not
5534  *     compatible with UNION);
5535  *   - for ENUMs, the size is ignored;
5536  *   - for INT, size and signedness are ignored;
5537  *   - for ARRAY, dimensionality is ignored, element types are checked for
5538  *     compatibility recursively;
5539  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5540  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5541  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5542  *     number of input args and compatible return and argument types.
5543  * These rules are not set in stone and probably will be adjusted as we get
5544  * more experience with using BPF CO-RE relocations.
5545  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5546 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5547 			      const struct btf *targ_btf, __u32 targ_id)
5548 {
5549 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5550 }
5551 
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5552 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5553 			 const struct btf *targ_btf, __u32 targ_id)
5554 {
5555 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5556 }
5557 
bpf_core_hash_fn(const void * key,void * ctx)5558 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5559 {
5560 	return (size_t)key;
5561 }
5562 
bpf_core_equal_fn(const void * k1,const void * k2,void * ctx)5563 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5564 {
5565 	return k1 == k2;
5566 }
5567 
u32_as_hash_key(__u32 x)5568 static void *u32_as_hash_key(__u32 x)
5569 {
5570 	return (void *)(uintptr_t)x;
5571 }
5572 
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5573 static int record_relo_core(struct bpf_program *prog,
5574 			    const struct bpf_core_relo *core_relo, int insn_idx)
5575 {
5576 	struct reloc_desc *relos, *relo;
5577 
5578 	relos = libbpf_reallocarray(prog->reloc_desc,
5579 				    prog->nr_reloc + 1, sizeof(*relos));
5580 	if (!relos)
5581 		return -ENOMEM;
5582 	relo = &relos[prog->nr_reloc];
5583 	relo->type = RELO_CORE;
5584 	relo->insn_idx = insn_idx;
5585 	relo->core_relo = core_relo;
5586 	prog->reloc_desc = relos;
5587 	prog->nr_reloc++;
5588 	return 0;
5589 }
5590 
find_relo_core(struct bpf_program * prog,int insn_idx)5591 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5592 {
5593 	struct reloc_desc *relo;
5594 	int i;
5595 
5596 	for (i = 0; i < prog->nr_reloc; i++) {
5597 		relo = &prog->reloc_desc[i];
5598 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5599 			continue;
5600 
5601 		return relo->core_relo;
5602 	}
5603 
5604 	return NULL;
5605 }
5606 
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)5607 static int bpf_core_resolve_relo(struct bpf_program *prog,
5608 				 const struct bpf_core_relo *relo,
5609 				 int relo_idx,
5610 				 const struct btf *local_btf,
5611 				 struct hashmap *cand_cache,
5612 				 struct bpf_core_relo_res *targ_res)
5613 {
5614 	struct bpf_core_spec specs_scratch[3] = {};
5615 	const void *type_key = u32_as_hash_key(relo->type_id);
5616 	struct bpf_core_cand_list *cands = NULL;
5617 	const char *prog_name = prog->name;
5618 	const struct btf_type *local_type;
5619 	const char *local_name;
5620 	__u32 local_id = relo->type_id;
5621 	int err;
5622 
5623 	local_type = btf__type_by_id(local_btf, local_id);
5624 	if (!local_type)
5625 		return -EINVAL;
5626 
5627 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5628 	if (!local_name)
5629 		return -EINVAL;
5630 
5631 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5632 	    !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5633 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5634 		if (IS_ERR(cands)) {
5635 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5636 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5637 				local_name, PTR_ERR(cands));
5638 			return PTR_ERR(cands);
5639 		}
5640 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5641 		if (err) {
5642 			bpf_core_free_cands(cands);
5643 			return err;
5644 		}
5645 	}
5646 
5647 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5648 				       targ_res);
5649 }
5650 
5651 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5652 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5653 {
5654 	const struct btf_ext_info_sec *sec;
5655 	struct bpf_core_relo_res targ_res;
5656 	const struct bpf_core_relo *rec;
5657 	const struct btf_ext_info *seg;
5658 	struct hashmap_entry *entry;
5659 	struct hashmap *cand_cache = NULL;
5660 	struct bpf_program *prog;
5661 	struct bpf_insn *insn;
5662 	const char *sec_name;
5663 	int i, err = 0, insn_idx, sec_idx, sec_num;
5664 
5665 	if (obj->btf_ext->core_relo_info.len == 0)
5666 		return 0;
5667 
5668 	if (targ_btf_path) {
5669 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5670 		err = libbpf_get_error(obj->btf_vmlinux_override);
5671 		if (err) {
5672 			pr_warn("failed to parse target BTF: %d\n", err);
5673 			return err;
5674 		}
5675 	}
5676 
5677 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5678 	if (IS_ERR(cand_cache)) {
5679 		err = PTR_ERR(cand_cache);
5680 		goto out;
5681 	}
5682 
5683 	seg = &obj->btf_ext->core_relo_info;
5684 	sec_num = 0;
5685 	for_each_btf_ext_sec(seg, sec) {
5686 		sec_idx = seg->sec_idxs[sec_num];
5687 		sec_num++;
5688 
5689 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5690 		if (str_is_empty(sec_name)) {
5691 			err = -EINVAL;
5692 			goto out;
5693 		}
5694 
5695 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5696 
5697 		for_each_btf_ext_rec(seg, sec, i, rec) {
5698 			if (rec->insn_off % BPF_INSN_SZ)
5699 				return -EINVAL;
5700 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5701 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5702 			if (!prog) {
5703 				/* When __weak subprog is "overridden" by another instance
5704 				 * of the subprog from a different object file, linker still
5705 				 * appends all the .BTF.ext info that used to belong to that
5706 				 * eliminated subprogram.
5707 				 * This is similar to what x86-64 linker does for relocations.
5708 				 * So just ignore such relocations just like we ignore
5709 				 * subprog instructions when discovering subprograms.
5710 				 */
5711 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5712 					 sec_name, i, insn_idx);
5713 				continue;
5714 			}
5715 			/* no need to apply CO-RE relocation if the program is
5716 			 * not going to be loaded
5717 			 */
5718 			if (!prog->autoload)
5719 				continue;
5720 
5721 			/* adjust insn_idx from section frame of reference to the local
5722 			 * program's frame of reference; (sub-)program code is not yet
5723 			 * relocated, so it's enough to just subtract in-section offset
5724 			 */
5725 			insn_idx = insn_idx - prog->sec_insn_off;
5726 			if (insn_idx >= prog->insns_cnt)
5727 				return -EINVAL;
5728 			insn = &prog->insns[insn_idx];
5729 
5730 			err = record_relo_core(prog, rec, insn_idx);
5731 			if (err) {
5732 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5733 					prog->name, i, err);
5734 				goto out;
5735 			}
5736 
5737 			if (prog->obj->gen_loader)
5738 				continue;
5739 
5740 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5741 			if (err) {
5742 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5743 					prog->name, i, err);
5744 				goto out;
5745 			}
5746 
5747 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5748 			if (err) {
5749 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5750 					prog->name, i, insn_idx, err);
5751 				goto out;
5752 			}
5753 		}
5754 	}
5755 
5756 out:
5757 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5758 	btf__free(obj->btf_vmlinux_override);
5759 	obj->btf_vmlinux_override = NULL;
5760 
5761 	if (!IS_ERR_OR_NULL(cand_cache)) {
5762 		hashmap__for_each_entry(cand_cache, entry, i) {
5763 			bpf_core_free_cands(entry->value);
5764 		}
5765 		hashmap__free(cand_cache);
5766 	}
5767 	return err;
5768 }
5769 
5770 /* base map load ldimm64 special constant, used also for log fixup logic */
5771 #define MAP_LDIMM64_POISON_BASE 2001000000
5772 #define MAP_LDIMM64_POISON_PFX "200100"
5773 
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)5774 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5775 			       int insn_idx, struct bpf_insn *insn,
5776 			       int map_idx, const struct bpf_map *map)
5777 {
5778 	int i;
5779 
5780 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5781 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5782 
5783 	/* we turn single ldimm64 into two identical invalid calls */
5784 	for (i = 0; i < 2; i++) {
5785 		insn->code = BPF_JMP | BPF_CALL;
5786 		insn->dst_reg = 0;
5787 		insn->src_reg = 0;
5788 		insn->off = 0;
5789 		/* if this instruction is reachable (not a dead code),
5790 		 * verifier will complain with something like:
5791 		 * invalid func unknown#2001000123
5792 		 * where lower 123 is map index into obj->maps[] array
5793 		 */
5794 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5795 
5796 		insn++;
5797 	}
5798 }
5799 
5800 /* Relocate data references within program code:
5801  *  - map references;
5802  *  - global variable references;
5803  *  - extern references.
5804  */
5805 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)5806 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5807 {
5808 	int i;
5809 
5810 	for (i = 0; i < prog->nr_reloc; i++) {
5811 		struct reloc_desc *relo = &prog->reloc_desc[i];
5812 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5813 		const struct bpf_map *map;
5814 		struct extern_desc *ext;
5815 
5816 		switch (relo->type) {
5817 		case RELO_LD64:
5818 			map = &obj->maps[relo->map_idx];
5819 			if (obj->gen_loader) {
5820 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5821 				insn[0].imm = relo->map_idx;
5822 			} else if (map->autocreate) {
5823 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5824 				insn[0].imm = map->fd;
5825 			} else {
5826 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5827 						   relo->map_idx, map);
5828 			}
5829 			break;
5830 		case RELO_DATA:
5831 			map = &obj->maps[relo->map_idx];
5832 			insn[1].imm = insn[0].imm + relo->sym_off;
5833 			if (obj->gen_loader) {
5834 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5835 				insn[0].imm = relo->map_idx;
5836 			} else if (map->autocreate) {
5837 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5838 				insn[0].imm = map->fd;
5839 			} else {
5840 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5841 						   relo->map_idx, map);
5842 			}
5843 			break;
5844 		case RELO_EXTERN_VAR:
5845 			ext = &obj->externs[relo->sym_off];
5846 			if (ext->type == EXT_KCFG) {
5847 				if (obj->gen_loader) {
5848 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5849 					insn[0].imm = obj->kconfig_map_idx;
5850 				} else {
5851 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5852 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5853 				}
5854 				insn[1].imm = ext->kcfg.data_off;
5855 			} else /* EXT_KSYM */ {
5856 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5857 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5858 					insn[0].imm = ext->ksym.kernel_btf_id;
5859 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5860 				} else { /* typeless ksyms or unresolved typed ksyms */
5861 					insn[0].imm = (__u32)ext->ksym.addr;
5862 					insn[1].imm = ext->ksym.addr >> 32;
5863 				}
5864 			}
5865 			break;
5866 		case RELO_EXTERN_FUNC:
5867 			ext = &obj->externs[relo->sym_off];
5868 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5869 			if (ext->is_set) {
5870 				insn[0].imm = ext->ksym.kernel_btf_id;
5871 				insn[0].off = ext->ksym.btf_fd_idx;
5872 			} else { /* unresolved weak kfunc */
5873 				insn[0].imm = 0;
5874 				insn[0].off = 0;
5875 			}
5876 			break;
5877 		case RELO_SUBPROG_ADDR:
5878 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5879 				pr_warn("prog '%s': relo #%d: bad insn\n",
5880 					prog->name, i);
5881 				return -EINVAL;
5882 			}
5883 			/* handled already */
5884 			break;
5885 		case RELO_CALL:
5886 			/* handled already */
5887 			break;
5888 		case RELO_CORE:
5889 			/* will be handled by bpf_program_record_relos() */
5890 			break;
5891 		default:
5892 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5893 				prog->name, i, relo->type);
5894 			return -EINVAL;
5895 		}
5896 	}
5897 
5898 	return 0;
5899 }
5900 
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)5901 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5902 				    const struct bpf_program *prog,
5903 				    const struct btf_ext_info *ext_info,
5904 				    void **prog_info, __u32 *prog_rec_cnt,
5905 				    __u32 *prog_rec_sz)
5906 {
5907 	void *copy_start = NULL, *copy_end = NULL;
5908 	void *rec, *rec_end, *new_prog_info;
5909 	const struct btf_ext_info_sec *sec;
5910 	size_t old_sz, new_sz;
5911 	int i, sec_num, sec_idx, off_adj;
5912 
5913 	sec_num = 0;
5914 	for_each_btf_ext_sec(ext_info, sec) {
5915 		sec_idx = ext_info->sec_idxs[sec_num];
5916 		sec_num++;
5917 		if (prog->sec_idx != sec_idx)
5918 			continue;
5919 
5920 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
5921 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5922 
5923 			if (insn_off < prog->sec_insn_off)
5924 				continue;
5925 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5926 				break;
5927 
5928 			if (!copy_start)
5929 				copy_start = rec;
5930 			copy_end = rec + ext_info->rec_size;
5931 		}
5932 
5933 		if (!copy_start)
5934 			return -ENOENT;
5935 
5936 		/* append func/line info of a given (sub-)program to the main
5937 		 * program func/line info
5938 		 */
5939 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5940 		new_sz = old_sz + (copy_end - copy_start);
5941 		new_prog_info = realloc(*prog_info, new_sz);
5942 		if (!new_prog_info)
5943 			return -ENOMEM;
5944 		*prog_info = new_prog_info;
5945 		*prog_rec_cnt = new_sz / ext_info->rec_size;
5946 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5947 
5948 		/* Kernel instruction offsets are in units of 8-byte
5949 		 * instructions, while .BTF.ext instruction offsets generated
5950 		 * by Clang are in units of bytes. So convert Clang offsets
5951 		 * into kernel offsets and adjust offset according to program
5952 		 * relocated position.
5953 		 */
5954 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
5955 		rec = new_prog_info + old_sz;
5956 		rec_end = new_prog_info + new_sz;
5957 		for (; rec < rec_end; rec += ext_info->rec_size) {
5958 			__u32 *insn_off = rec;
5959 
5960 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5961 		}
5962 		*prog_rec_sz = ext_info->rec_size;
5963 		return 0;
5964 	}
5965 
5966 	return -ENOENT;
5967 }
5968 
5969 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)5970 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5971 			      struct bpf_program *main_prog,
5972 			      const struct bpf_program *prog)
5973 {
5974 	int err;
5975 
5976 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5977 	 * supprot func/line info
5978 	 */
5979 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5980 		return 0;
5981 
5982 	/* only attempt func info relocation if main program's func_info
5983 	 * relocation was successful
5984 	 */
5985 	if (main_prog != prog && !main_prog->func_info)
5986 		goto line_info;
5987 
5988 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5989 				       &main_prog->func_info,
5990 				       &main_prog->func_info_cnt,
5991 				       &main_prog->func_info_rec_size);
5992 	if (err) {
5993 		if (err != -ENOENT) {
5994 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5995 				prog->name, err);
5996 			return err;
5997 		}
5998 		if (main_prog->func_info) {
5999 			/*
6000 			 * Some info has already been found but has problem
6001 			 * in the last btf_ext reloc. Must have to error out.
6002 			 */
6003 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6004 			return err;
6005 		}
6006 		/* Have problem loading the very first info. Ignore the rest. */
6007 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6008 			prog->name);
6009 	}
6010 
6011 line_info:
6012 	/* don't relocate line info if main program's relocation failed */
6013 	if (main_prog != prog && !main_prog->line_info)
6014 		return 0;
6015 
6016 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6017 				       &main_prog->line_info,
6018 				       &main_prog->line_info_cnt,
6019 				       &main_prog->line_info_rec_size);
6020 	if (err) {
6021 		if (err != -ENOENT) {
6022 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6023 				prog->name, err);
6024 			return err;
6025 		}
6026 		if (main_prog->line_info) {
6027 			/*
6028 			 * Some info has already been found but has problem
6029 			 * in the last btf_ext reloc. Must have to error out.
6030 			 */
6031 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6032 			return err;
6033 		}
6034 		/* Have problem loading the very first info. Ignore the rest. */
6035 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6036 			prog->name);
6037 	}
6038 	return 0;
6039 }
6040 
cmp_relo_by_insn_idx(const void * key,const void * elem)6041 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6042 {
6043 	size_t insn_idx = *(const size_t *)key;
6044 	const struct reloc_desc *relo = elem;
6045 
6046 	if (insn_idx == relo->insn_idx)
6047 		return 0;
6048 	return insn_idx < relo->insn_idx ? -1 : 1;
6049 }
6050 
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6051 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6052 {
6053 	if (!prog->nr_reloc)
6054 		return NULL;
6055 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6056 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6057 }
6058 
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6059 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6060 {
6061 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6062 	struct reloc_desc *relos;
6063 	int i;
6064 
6065 	if (main_prog == subprog)
6066 		return 0;
6067 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6068 	/* if new count is zero, reallocarray can return a valid NULL result;
6069 	 * in this case the previous pointer will be freed, so we *have to*
6070 	 * reassign old pointer to the new value (even if it's NULL)
6071 	 */
6072 	if (!relos && new_cnt)
6073 		return -ENOMEM;
6074 	if (subprog->nr_reloc)
6075 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6076 		       sizeof(*relos) * subprog->nr_reloc);
6077 
6078 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6079 		relos[i].insn_idx += subprog->sub_insn_off;
6080 	/* After insn_idx adjustment the 'relos' array is still sorted
6081 	 * by insn_idx and doesn't break bsearch.
6082 	 */
6083 	main_prog->reloc_desc = relos;
6084 	main_prog->nr_reloc = new_cnt;
6085 	return 0;
6086 }
6087 
6088 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6089 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6090 		       struct bpf_program *prog)
6091 {
6092 	size_t sub_insn_idx, insn_idx, new_cnt;
6093 	struct bpf_program *subprog;
6094 	struct bpf_insn *insns, *insn;
6095 	struct reloc_desc *relo;
6096 	int err;
6097 
6098 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6099 	if (err)
6100 		return err;
6101 
6102 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6103 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6104 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6105 			continue;
6106 
6107 		relo = find_prog_insn_relo(prog, insn_idx);
6108 		if (relo && relo->type == RELO_EXTERN_FUNC)
6109 			/* kfunc relocations will be handled later
6110 			 * in bpf_object__relocate_data()
6111 			 */
6112 			continue;
6113 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6114 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6115 				prog->name, insn_idx, relo->type);
6116 			return -LIBBPF_ERRNO__RELOC;
6117 		}
6118 		if (relo) {
6119 			/* sub-program instruction index is a combination of
6120 			 * an offset of a symbol pointed to by relocation and
6121 			 * call instruction's imm field; for global functions,
6122 			 * call always has imm = -1, but for static functions
6123 			 * relocation is against STT_SECTION and insn->imm
6124 			 * points to a start of a static function
6125 			 *
6126 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6127 			 * the byte offset in the corresponding section.
6128 			 */
6129 			if (relo->type == RELO_CALL)
6130 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6131 			else
6132 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6133 		} else if (insn_is_pseudo_func(insn)) {
6134 			/*
6135 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6136 			 * functions are in the same section, so it shouldn't reach here.
6137 			 */
6138 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6139 				prog->name, insn_idx);
6140 			return -LIBBPF_ERRNO__RELOC;
6141 		} else {
6142 			/* if subprogram call is to a static function within
6143 			 * the same ELF section, there won't be any relocation
6144 			 * emitted, but it also means there is no additional
6145 			 * offset necessary, insns->imm is relative to
6146 			 * instruction's original position within the section
6147 			 */
6148 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6149 		}
6150 
6151 		/* we enforce that sub-programs should be in .text section */
6152 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6153 		if (!subprog) {
6154 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6155 				prog->name);
6156 			return -LIBBPF_ERRNO__RELOC;
6157 		}
6158 
6159 		/* if it's the first call instruction calling into this
6160 		 * subprogram (meaning this subprog hasn't been processed
6161 		 * yet) within the context of current main program:
6162 		 *   - append it at the end of main program's instructions blog;
6163 		 *   - process is recursively, while current program is put on hold;
6164 		 *   - if that subprogram calls some other not yet processes
6165 		 *   subprogram, same thing will happen recursively until
6166 		 *   there are no more unprocesses subprograms left to append
6167 		 *   and relocate.
6168 		 */
6169 		if (subprog->sub_insn_off == 0) {
6170 			subprog->sub_insn_off = main_prog->insns_cnt;
6171 
6172 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6173 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6174 			if (!insns) {
6175 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6176 				return -ENOMEM;
6177 			}
6178 			main_prog->insns = insns;
6179 			main_prog->insns_cnt = new_cnt;
6180 
6181 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6182 			       subprog->insns_cnt * sizeof(*insns));
6183 
6184 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6185 				 main_prog->name, subprog->insns_cnt, subprog->name);
6186 
6187 			/* The subprog insns are now appended. Append its relos too. */
6188 			err = append_subprog_relos(main_prog, subprog);
6189 			if (err)
6190 				return err;
6191 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6192 			if (err)
6193 				return err;
6194 		}
6195 
6196 		/* main_prog->insns memory could have been re-allocated, so
6197 		 * calculate pointer again
6198 		 */
6199 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6200 		/* calculate correct instruction position within current main
6201 		 * prog; each main prog can have a different set of
6202 		 * subprograms appended (potentially in different order as
6203 		 * well), so position of any subprog can be different for
6204 		 * different main programs */
6205 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6206 
6207 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6208 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6209 	}
6210 
6211 	return 0;
6212 }
6213 
6214 /*
6215  * Relocate sub-program calls.
6216  *
6217  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6218  * main prog) is processed separately. For each subprog (non-entry functions,
6219  * that can be called from either entry progs or other subprogs) gets their
6220  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6221  * hasn't been yet appended and relocated within current main prog. Once its
6222  * relocated, sub_insn_off will point at the position within current main prog
6223  * where given subprog was appended. This will further be used to relocate all
6224  * the call instructions jumping into this subprog.
6225  *
6226  * We start with main program and process all call instructions. If the call
6227  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6228  * is zero), subprog instructions are appended at the end of main program's
6229  * instruction array. Then main program is "put on hold" while we recursively
6230  * process newly appended subprogram. If that subprogram calls into another
6231  * subprogram that hasn't been appended, new subprogram is appended again to
6232  * the *main* prog's instructions (subprog's instructions are always left
6233  * untouched, as they need to be in unmodified state for subsequent main progs
6234  * and subprog instructions are always sent only as part of a main prog) and
6235  * the process continues recursively. Once all the subprogs called from a main
6236  * prog or any of its subprogs are appended (and relocated), all their
6237  * positions within finalized instructions array are known, so it's easy to
6238  * rewrite call instructions with correct relative offsets, corresponding to
6239  * desired target subprog.
6240  *
6241  * Its important to realize that some subprogs might not be called from some
6242  * main prog and any of its called/used subprogs. Those will keep their
6243  * subprog->sub_insn_off as zero at all times and won't be appended to current
6244  * main prog and won't be relocated within the context of current main prog.
6245  * They might still be used from other main progs later.
6246  *
6247  * Visually this process can be shown as below. Suppose we have two main
6248  * programs mainA and mainB and BPF object contains three subprogs: subA,
6249  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6250  * subC both call subB:
6251  *
6252  *        +--------+ +-------+
6253  *        |        v v       |
6254  *     +--+---+ +--+-+-+ +---+--+
6255  *     | subA | | subB | | subC |
6256  *     +--+---+ +------+ +---+--+
6257  *        ^                  ^
6258  *        |                  |
6259  *    +---+-------+   +------+----+
6260  *    |   mainA   |   |   mainB   |
6261  *    +-----------+   +-----------+
6262  *
6263  * We'll start relocating mainA, will find subA, append it and start
6264  * processing sub A recursively:
6265  *
6266  *    +-----------+------+
6267  *    |   mainA   | subA |
6268  *    +-----------+------+
6269  *
6270  * At this point we notice that subB is used from subA, so we append it and
6271  * relocate (there are no further subcalls from subB):
6272  *
6273  *    +-----------+------+------+
6274  *    |   mainA   | subA | subB |
6275  *    +-----------+------+------+
6276  *
6277  * At this point, we relocate subA calls, then go one level up and finish with
6278  * relocatin mainA calls. mainA is done.
6279  *
6280  * For mainB process is similar but results in different order. We start with
6281  * mainB and skip subA and subB, as mainB never calls them (at least
6282  * directly), but we see subC is needed, so we append and start processing it:
6283  *
6284  *    +-----------+------+
6285  *    |   mainB   | subC |
6286  *    +-----------+------+
6287  * Now we see subC needs subB, so we go back to it, append and relocate it:
6288  *
6289  *    +-----------+------+------+
6290  *    |   mainB   | subC | subB |
6291  *    +-----------+------+------+
6292  *
6293  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6294  */
6295 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6296 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6297 {
6298 	struct bpf_program *subprog;
6299 	int i, err;
6300 
6301 	/* mark all subprogs as not relocated (yet) within the context of
6302 	 * current main program
6303 	 */
6304 	for (i = 0; i < obj->nr_programs; i++) {
6305 		subprog = &obj->programs[i];
6306 		if (!prog_is_subprog(obj, subprog))
6307 			continue;
6308 
6309 		subprog->sub_insn_off = 0;
6310 	}
6311 
6312 	err = bpf_object__reloc_code(obj, prog, prog);
6313 	if (err)
6314 		return err;
6315 
6316 	return 0;
6317 }
6318 
6319 static void
bpf_object__free_relocs(struct bpf_object * obj)6320 bpf_object__free_relocs(struct bpf_object *obj)
6321 {
6322 	struct bpf_program *prog;
6323 	int i;
6324 
6325 	/* free up relocation descriptors */
6326 	for (i = 0; i < obj->nr_programs; i++) {
6327 		prog = &obj->programs[i];
6328 		zfree(&prog->reloc_desc);
6329 		prog->nr_reloc = 0;
6330 	}
6331 }
6332 
cmp_relocs(const void * _a,const void * _b)6333 static int cmp_relocs(const void *_a, const void *_b)
6334 {
6335 	const struct reloc_desc *a = _a;
6336 	const struct reloc_desc *b = _b;
6337 
6338 	if (a->insn_idx != b->insn_idx)
6339 		return a->insn_idx < b->insn_idx ? -1 : 1;
6340 
6341 	/* no two relocations should have the same insn_idx, but ... */
6342 	if (a->type != b->type)
6343 		return a->type < b->type ? -1 : 1;
6344 
6345 	return 0;
6346 }
6347 
bpf_object__sort_relos(struct bpf_object * obj)6348 static void bpf_object__sort_relos(struct bpf_object *obj)
6349 {
6350 	int i;
6351 
6352 	for (i = 0; i < obj->nr_programs; i++) {
6353 		struct bpf_program *p = &obj->programs[i];
6354 
6355 		if (!p->nr_reloc)
6356 			continue;
6357 
6358 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6359 	}
6360 }
6361 
6362 static int
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)6363 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6364 {
6365 	struct bpf_program *prog;
6366 	size_t i, j;
6367 	int err;
6368 
6369 	if (obj->btf_ext) {
6370 		err = bpf_object__relocate_core(obj, targ_btf_path);
6371 		if (err) {
6372 			pr_warn("failed to perform CO-RE relocations: %d\n",
6373 				err);
6374 			return err;
6375 		}
6376 		bpf_object__sort_relos(obj);
6377 	}
6378 
6379 	/* Before relocating calls pre-process relocations and mark
6380 	 * few ld_imm64 instructions that points to subprogs.
6381 	 * Otherwise bpf_object__reloc_code() later would have to consider
6382 	 * all ld_imm64 insns as relocation candidates. That would
6383 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6384 	 * would increase and most of them will fail to find a relo.
6385 	 */
6386 	for (i = 0; i < obj->nr_programs; i++) {
6387 		prog = &obj->programs[i];
6388 		for (j = 0; j < prog->nr_reloc; j++) {
6389 			struct reloc_desc *relo = &prog->reloc_desc[j];
6390 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6391 
6392 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6393 			if (relo->type == RELO_SUBPROG_ADDR)
6394 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6395 		}
6396 	}
6397 
6398 	/* relocate subprogram calls and append used subprograms to main
6399 	 * programs; each copy of subprogram code needs to be relocated
6400 	 * differently for each main program, because its code location might
6401 	 * have changed.
6402 	 * Append subprog relos to main programs to allow data relos to be
6403 	 * processed after text is completely relocated.
6404 	 */
6405 	for (i = 0; i < obj->nr_programs; i++) {
6406 		prog = &obj->programs[i];
6407 		/* sub-program's sub-calls are relocated within the context of
6408 		 * its main program only
6409 		 */
6410 		if (prog_is_subprog(obj, prog))
6411 			continue;
6412 		if (!prog->autoload)
6413 			continue;
6414 
6415 		err = bpf_object__relocate_calls(obj, prog);
6416 		if (err) {
6417 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6418 				prog->name, err);
6419 			return err;
6420 		}
6421 	}
6422 	/* Process data relos for main programs */
6423 	for (i = 0; i < obj->nr_programs; i++) {
6424 		prog = &obj->programs[i];
6425 		if (prog_is_subprog(obj, prog))
6426 			continue;
6427 		if (!prog->autoload)
6428 			continue;
6429 		err = bpf_object__relocate_data(obj, prog);
6430 		if (err) {
6431 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6432 				prog->name, err);
6433 			return err;
6434 		}
6435 	}
6436 
6437 	return 0;
6438 }
6439 
6440 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6441 					    Elf64_Shdr *shdr, Elf_Data *data);
6442 
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)6443 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6444 					 Elf64_Shdr *shdr, Elf_Data *data)
6445 {
6446 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6447 	int i, j, nrels, new_sz;
6448 	const struct btf_var_secinfo *vi = NULL;
6449 	const struct btf_type *sec, *var, *def;
6450 	struct bpf_map *map = NULL, *targ_map = NULL;
6451 	struct bpf_program *targ_prog = NULL;
6452 	bool is_prog_array, is_map_in_map;
6453 	const struct btf_member *member;
6454 	const char *name, *mname, *type;
6455 	unsigned int moff;
6456 	Elf64_Sym *sym;
6457 	Elf64_Rel *rel;
6458 	void *tmp;
6459 
6460 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6461 		return -EINVAL;
6462 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6463 	if (!sec)
6464 		return -EINVAL;
6465 
6466 	nrels = shdr->sh_size / shdr->sh_entsize;
6467 	for (i = 0; i < nrels; i++) {
6468 		rel = elf_rel_by_idx(data, i);
6469 		if (!rel) {
6470 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6471 			return -LIBBPF_ERRNO__FORMAT;
6472 		}
6473 
6474 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6475 		if (!sym) {
6476 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6477 				i, (size_t)ELF64_R_SYM(rel->r_info));
6478 			return -LIBBPF_ERRNO__FORMAT;
6479 		}
6480 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6481 
6482 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6483 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6484 			 (size_t)rel->r_offset, sym->st_name, name);
6485 
6486 		for (j = 0; j < obj->nr_maps; j++) {
6487 			map = &obj->maps[j];
6488 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6489 				continue;
6490 
6491 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6492 			if (vi->offset <= rel->r_offset &&
6493 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6494 				break;
6495 		}
6496 		if (j == obj->nr_maps) {
6497 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6498 				i, name, (size_t)rel->r_offset);
6499 			return -EINVAL;
6500 		}
6501 
6502 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6503 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6504 		type = is_map_in_map ? "map" : "prog";
6505 		if (is_map_in_map) {
6506 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6507 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6508 					i, name);
6509 				return -LIBBPF_ERRNO__RELOC;
6510 			}
6511 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6512 			    map->def.key_size != sizeof(int)) {
6513 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6514 					i, map->name, sizeof(int));
6515 				return -EINVAL;
6516 			}
6517 			targ_map = bpf_object__find_map_by_name(obj, name);
6518 			if (!targ_map) {
6519 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6520 					i, name);
6521 				return -ESRCH;
6522 			}
6523 		} else if (is_prog_array) {
6524 			targ_prog = bpf_object__find_program_by_name(obj, name);
6525 			if (!targ_prog) {
6526 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6527 					i, name);
6528 				return -ESRCH;
6529 			}
6530 			if (targ_prog->sec_idx != sym->st_shndx ||
6531 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6532 			    prog_is_subprog(obj, targ_prog)) {
6533 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6534 					i, name);
6535 				return -LIBBPF_ERRNO__RELOC;
6536 			}
6537 		} else {
6538 			return -EINVAL;
6539 		}
6540 
6541 		var = btf__type_by_id(obj->btf, vi->type);
6542 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6543 		if (btf_vlen(def) == 0)
6544 			return -EINVAL;
6545 		member = btf_members(def) + btf_vlen(def) - 1;
6546 		mname = btf__name_by_offset(obj->btf, member->name_off);
6547 		if (strcmp(mname, "values"))
6548 			return -EINVAL;
6549 
6550 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6551 		if (rel->r_offset - vi->offset < moff)
6552 			return -EINVAL;
6553 
6554 		moff = rel->r_offset - vi->offset - moff;
6555 		/* here we use BPF pointer size, which is always 64 bit, as we
6556 		 * are parsing ELF that was built for BPF target
6557 		 */
6558 		if (moff % bpf_ptr_sz)
6559 			return -EINVAL;
6560 		moff /= bpf_ptr_sz;
6561 		if (moff >= map->init_slots_sz) {
6562 			new_sz = moff + 1;
6563 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6564 			if (!tmp)
6565 				return -ENOMEM;
6566 			map->init_slots = tmp;
6567 			memset(map->init_slots + map->init_slots_sz, 0,
6568 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6569 			map->init_slots_sz = new_sz;
6570 		}
6571 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6572 
6573 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6574 			 i, map->name, moff, type, name);
6575 	}
6576 
6577 	return 0;
6578 }
6579 
bpf_object__collect_relos(struct bpf_object * obj)6580 static int bpf_object__collect_relos(struct bpf_object *obj)
6581 {
6582 	int i, err;
6583 
6584 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6585 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6586 		Elf64_Shdr *shdr;
6587 		Elf_Data *data;
6588 		int idx;
6589 
6590 		if (sec_desc->sec_type != SEC_RELO)
6591 			continue;
6592 
6593 		shdr = sec_desc->shdr;
6594 		data = sec_desc->data;
6595 		idx = shdr->sh_info;
6596 
6597 		if (shdr->sh_type != SHT_REL) {
6598 			pr_warn("internal error at %d\n", __LINE__);
6599 			return -LIBBPF_ERRNO__INTERNAL;
6600 		}
6601 
6602 		if (idx == obj->efile.st_ops_shndx)
6603 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6604 		else if (idx == obj->efile.btf_maps_shndx)
6605 			err = bpf_object__collect_map_relos(obj, shdr, data);
6606 		else
6607 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6608 		if (err)
6609 			return err;
6610 	}
6611 
6612 	bpf_object__sort_relos(obj);
6613 	return 0;
6614 }
6615 
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)6616 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6617 {
6618 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6619 	    BPF_OP(insn->code) == BPF_CALL &&
6620 	    BPF_SRC(insn->code) == BPF_K &&
6621 	    insn->src_reg == 0 &&
6622 	    insn->dst_reg == 0) {
6623 		    *func_id = insn->imm;
6624 		    return true;
6625 	}
6626 	return false;
6627 }
6628 
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)6629 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6630 {
6631 	struct bpf_insn *insn = prog->insns;
6632 	enum bpf_func_id func_id;
6633 	int i;
6634 
6635 	if (obj->gen_loader)
6636 		return 0;
6637 
6638 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6639 		if (!insn_is_helper_call(insn, &func_id))
6640 			continue;
6641 
6642 		/* on kernels that don't yet support
6643 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6644 		 * to bpf_probe_read() which works well for old kernels
6645 		 */
6646 		switch (func_id) {
6647 		case BPF_FUNC_probe_read_kernel:
6648 		case BPF_FUNC_probe_read_user:
6649 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6650 				insn->imm = BPF_FUNC_probe_read;
6651 			break;
6652 		case BPF_FUNC_probe_read_kernel_str:
6653 		case BPF_FUNC_probe_read_user_str:
6654 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6655 				insn->imm = BPF_FUNC_probe_read_str;
6656 			break;
6657 		default:
6658 			break;
6659 		}
6660 	}
6661 	return 0;
6662 }
6663 
6664 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6665 				     int *btf_obj_fd, int *btf_type_id);
6666 
6667 /* 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)6668 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6669 				    struct bpf_prog_load_opts *opts, long cookie)
6670 {
6671 	enum sec_def_flags def = cookie;
6672 
6673 	/* old kernels might not support specifying expected_attach_type */
6674 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6675 		opts->expected_attach_type = 0;
6676 
6677 	if (def & SEC_SLEEPABLE)
6678 		opts->prog_flags |= BPF_F_SLEEPABLE;
6679 
6680 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6681 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6682 
6683 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6684 		int btf_obj_fd = 0, btf_type_id = 0, err;
6685 		const char *attach_name;
6686 
6687 		attach_name = strchr(prog->sec_name, '/');
6688 		if (!attach_name) {
6689 			/* if BPF program is annotated with just SEC("fentry")
6690 			 * (or similar) without declaratively specifying
6691 			 * target, then it is expected that target will be
6692 			 * specified with bpf_program__set_attach_target() at
6693 			 * runtime before BPF object load step. If not, then
6694 			 * there is nothing to load into the kernel as BPF
6695 			 * verifier won't be able to validate BPF program
6696 			 * correctness anyways.
6697 			 */
6698 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6699 				prog->name);
6700 			return -EINVAL;
6701 		}
6702 		attach_name++; /* skip over / */
6703 
6704 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6705 		if (err)
6706 			return err;
6707 
6708 		/* cache resolved BTF FD and BTF type ID in the prog */
6709 		prog->attach_btf_obj_fd = btf_obj_fd;
6710 		prog->attach_btf_id = btf_type_id;
6711 
6712 		/* but by now libbpf common logic is not utilizing
6713 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6714 		 * this callback is called after opts were populated by
6715 		 * libbpf, so this callback has to update opts explicitly here
6716 		 */
6717 		opts->attach_btf_obj_fd = btf_obj_fd;
6718 		opts->attach_btf_id = btf_type_id;
6719 	}
6720 	return 0;
6721 }
6722 
6723 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6724 
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)6725 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6726 				struct bpf_insn *insns, int insns_cnt,
6727 				const char *license, __u32 kern_version, int *prog_fd)
6728 {
6729 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6730 	const char *prog_name = NULL;
6731 	char *cp, errmsg[STRERR_BUFSIZE];
6732 	size_t log_buf_size = 0;
6733 	char *log_buf = NULL, *tmp;
6734 	int btf_fd, ret, err;
6735 	bool own_log_buf = true;
6736 	__u32 log_level = prog->log_level;
6737 
6738 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6739 		/*
6740 		 * The program type must be set.  Most likely we couldn't find a proper
6741 		 * section definition at load time, and thus we didn't infer the type.
6742 		 */
6743 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6744 			prog->name, prog->sec_name);
6745 		return -EINVAL;
6746 	}
6747 
6748 	if (!insns || !insns_cnt)
6749 		return -EINVAL;
6750 
6751 	load_attr.expected_attach_type = prog->expected_attach_type;
6752 	if (kernel_supports(obj, FEAT_PROG_NAME))
6753 		prog_name = prog->name;
6754 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6755 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6756 	load_attr.attach_btf_id = prog->attach_btf_id;
6757 	load_attr.kern_version = kern_version;
6758 	load_attr.prog_ifindex = prog->prog_ifindex;
6759 
6760 	/* specify func_info/line_info only if kernel supports them */
6761 	btf_fd = bpf_object__btf_fd(obj);
6762 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6763 		load_attr.prog_btf_fd = btf_fd;
6764 		load_attr.func_info = prog->func_info;
6765 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6766 		load_attr.func_info_cnt = prog->func_info_cnt;
6767 		load_attr.line_info = prog->line_info;
6768 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6769 		load_attr.line_info_cnt = prog->line_info_cnt;
6770 	}
6771 	load_attr.log_level = log_level;
6772 	load_attr.prog_flags = prog->prog_flags;
6773 	load_attr.fd_array = obj->fd_array;
6774 
6775 	/* adjust load_attr if sec_def provides custom preload callback */
6776 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6777 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6778 		if (err < 0) {
6779 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6780 				prog->name, err);
6781 			return err;
6782 		}
6783 		insns = prog->insns;
6784 		insns_cnt = prog->insns_cnt;
6785 	}
6786 
6787 	if (obj->gen_loader) {
6788 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6789 				   license, insns, insns_cnt, &load_attr,
6790 				   prog - obj->programs);
6791 		*prog_fd = -1;
6792 		return 0;
6793 	}
6794 
6795 retry_load:
6796 	/* if log_level is zero, we don't request logs initially even if
6797 	 * custom log_buf is specified; if the program load fails, then we'll
6798 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6799 	 * our own and retry the load to get details on what failed
6800 	 */
6801 	if (log_level) {
6802 		if (prog->log_buf) {
6803 			log_buf = prog->log_buf;
6804 			log_buf_size = prog->log_size;
6805 			own_log_buf = false;
6806 		} else if (obj->log_buf) {
6807 			log_buf = obj->log_buf;
6808 			log_buf_size = obj->log_size;
6809 			own_log_buf = false;
6810 		} else {
6811 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6812 			tmp = realloc(log_buf, log_buf_size);
6813 			if (!tmp) {
6814 				ret = -ENOMEM;
6815 				goto out;
6816 			}
6817 			log_buf = tmp;
6818 			log_buf[0] = '\0';
6819 			own_log_buf = true;
6820 		}
6821 	}
6822 
6823 	load_attr.log_buf = log_buf;
6824 	load_attr.log_size = log_buf_size;
6825 	load_attr.log_level = log_level;
6826 
6827 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6828 	if (ret >= 0) {
6829 		if (log_level && own_log_buf) {
6830 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6831 				 prog->name, log_buf);
6832 		}
6833 
6834 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6835 			struct bpf_map *map;
6836 			int i;
6837 
6838 			for (i = 0; i < obj->nr_maps; i++) {
6839 				map = &prog->obj->maps[i];
6840 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6841 					continue;
6842 
6843 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6844 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6845 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6846 						prog->name, map->real_name, cp);
6847 					/* Don't fail hard if can't bind rodata. */
6848 				}
6849 			}
6850 		}
6851 
6852 		*prog_fd = ret;
6853 		ret = 0;
6854 		goto out;
6855 	}
6856 
6857 	if (log_level == 0) {
6858 		log_level = 1;
6859 		goto retry_load;
6860 	}
6861 	/* On ENOSPC, increase log buffer size and retry, unless custom
6862 	 * log_buf is specified.
6863 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6864 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6865 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6866 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6867 	 */
6868 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6869 		goto retry_load;
6870 
6871 	ret = -errno;
6872 
6873 	/* post-process verifier log to improve error descriptions */
6874 	fixup_verifier_log(prog, log_buf, log_buf_size);
6875 
6876 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6877 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6878 	pr_perm_msg(ret);
6879 
6880 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6881 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6882 			prog->name, log_buf);
6883 	}
6884 
6885 out:
6886 	if (own_log_buf)
6887 		free(log_buf);
6888 	return ret;
6889 }
6890 
find_prev_line(char * buf,char * cur)6891 static char *find_prev_line(char *buf, char *cur)
6892 {
6893 	char *p;
6894 
6895 	if (cur == buf) /* end of a log buf */
6896 		return NULL;
6897 
6898 	p = cur - 1;
6899 	while (p - 1 >= buf && *(p - 1) != '\n')
6900 		p--;
6901 
6902 	return p;
6903 }
6904 
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)6905 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6906 		      char *orig, size_t orig_sz, const char *patch)
6907 {
6908 	/* size of the remaining log content to the right from the to-be-replaced part */
6909 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6910 	size_t patch_sz = strlen(patch);
6911 
6912 	if (patch_sz != orig_sz) {
6913 		/* If patch line(s) are longer than original piece of verifier log,
6914 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
6915 		 * starting from after to-be-replaced part of the log.
6916 		 *
6917 		 * If patch line(s) are shorter than original piece of verifier log,
6918 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
6919 		 * starting from after to-be-replaced part of the log
6920 		 *
6921 		 * We need to be careful about not overflowing available
6922 		 * buf_sz capacity. If that's the case, we'll truncate the end
6923 		 * of the original log, as necessary.
6924 		 */
6925 		if (patch_sz > orig_sz) {
6926 			if (orig + patch_sz >= buf + buf_sz) {
6927 				/* patch is big enough to cover remaining space completely */
6928 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6929 				rem_sz = 0;
6930 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
6931 				/* patch causes part of remaining log to be truncated */
6932 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6933 			}
6934 		}
6935 		/* shift remaining log to the right by calculated amount */
6936 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6937 	}
6938 
6939 	memcpy(orig, patch, patch_sz);
6940 }
6941 
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)6942 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6943 				       char *buf, size_t buf_sz, size_t log_sz,
6944 				       char *line1, char *line2, char *line3)
6945 {
6946 	/* Expected log for failed and not properly guarded CO-RE relocation:
6947 	 * line1 -> 123: (85) call unknown#195896080
6948 	 * line2 -> invalid func unknown#195896080
6949 	 * line3 -> <anything else or end of buffer>
6950 	 *
6951 	 * "123" is the index of the instruction that was poisoned. We extract
6952 	 * instruction index to find corresponding CO-RE relocation and
6953 	 * replace this part of the log with more relevant information about
6954 	 * failed CO-RE relocation.
6955 	 */
6956 	const struct bpf_core_relo *relo;
6957 	struct bpf_core_spec spec;
6958 	char patch[512], spec_buf[256];
6959 	int insn_idx, err, spec_len;
6960 
6961 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
6962 		return;
6963 
6964 	relo = find_relo_core(prog, insn_idx);
6965 	if (!relo)
6966 		return;
6967 
6968 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
6969 	if (err)
6970 		return;
6971 
6972 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
6973 	snprintf(patch, sizeof(patch),
6974 		 "%d: <invalid CO-RE relocation>\n"
6975 		 "failed to resolve CO-RE relocation %s%s\n",
6976 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
6977 
6978 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
6979 }
6980 
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)6981 static void fixup_log_missing_map_load(struct bpf_program *prog,
6982 				       char *buf, size_t buf_sz, size_t log_sz,
6983 				       char *line1, char *line2, char *line3)
6984 {
6985 	/* Expected log for failed and not properly guarded CO-RE relocation:
6986 	 * line1 -> 123: (85) call unknown#2001000345
6987 	 * line2 -> invalid func unknown#2001000345
6988 	 * line3 -> <anything else or end of buffer>
6989 	 *
6990 	 * "123" is the index of the instruction that was poisoned.
6991 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
6992 	 */
6993 	struct bpf_object *obj = prog->obj;
6994 	const struct bpf_map *map;
6995 	int insn_idx, map_idx;
6996 	char patch[128];
6997 
6998 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
6999 		return;
7000 
7001 	map_idx -= MAP_LDIMM64_POISON_BASE;
7002 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7003 		return;
7004 	map = &obj->maps[map_idx];
7005 
7006 	snprintf(patch, sizeof(patch),
7007 		 "%d: <invalid BPF map reference>\n"
7008 		 "BPF map '%s' is referenced but wasn't created\n",
7009 		 insn_idx, map->name);
7010 
7011 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7012 }
7013 
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7014 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7015 {
7016 	/* look for familiar error patterns in last N lines of the log */
7017 	const size_t max_last_line_cnt = 10;
7018 	char *prev_line, *cur_line, *next_line;
7019 	size_t log_sz;
7020 	int i;
7021 
7022 	if (!buf)
7023 		return;
7024 
7025 	log_sz = strlen(buf) + 1;
7026 	next_line = buf + log_sz - 1;
7027 
7028 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7029 		cur_line = find_prev_line(buf, next_line);
7030 		if (!cur_line)
7031 			return;
7032 
7033 		/* failed CO-RE relocation case */
7034 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7035 			prev_line = find_prev_line(buf, cur_line);
7036 			if (!prev_line)
7037 				continue;
7038 
7039 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7040 						   prev_line, cur_line, next_line);
7041 			return;
7042 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7043 			prev_line = find_prev_line(buf, cur_line);
7044 			if (!prev_line)
7045 				continue;
7046 
7047 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7048 						   prev_line, cur_line, next_line);
7049 			return;
7050 		}
7051 	}
7052 }
7053 
bpf_program_record_relos(struct bpf_program * prog)7054 static int bpf_program_record_relos(struct bpf_program *prog)
7055 {
7056 	struct bpf_object *obj = prog->obj;
7057 	int i;
7058 
7059 	for (i = 0; i < prog->nr_reloc; i++) {
7060 		struct reloc_desc *relo = &prog->reloc_desc[i];
7061 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7062 
7063 		switch (relo->type) {
7064 		case RELO_EXTERN_VAR:
7065 			if (ext->type != EXT_KSYM)
7066 				continue;
7067 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7068 					       ext->is_weak, !ext->ksym.type_id,
7069 					       BTF_KIND_VAR, relo->insn_idx);
7070 			break;
7071 		case RELO_EXTERN_FUNC:
7072 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7073 					       ext->is_weak, false, BTF_KIND_FUNC,
7074 					       relo->insn_idx);
7075 			break;
7076 		case RELO_CORE: {
7077 			struct bpf_core_relo cr = {
7078 				.insn_off = relo->insn_idx * 8,
7079 				.type_id = relo->core_relo->type_id,
7080 				.access_str_off = relo->core_relo->access_str_off,
7081 				.kind = relo->core_relo->kind,
7082 			};
7083 
7084 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7085 			break;
7086 		}
7087 		default:
7088 			continue;
7089 		}
7090 	}
7091 	return 0;
7092 }
7093 
7094 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7095 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7096 {
7097 	struct bpf_program *prog;
7098 	size_t i;
7099 	int err;
7100 
7101 	for (i = 0; i < obj->nr_programs; i++) {
7102 		prog = &obj->programs[i];
7103 		err = bpf_object__sanitize_prog(obj, prog);
7104 		if (err)
7105 			return err;
7106 	}
7107 
7108 	for (i = 0; i < obj->nr_programs; i++) {
7109 		prog = &obj->programs[i];
7110 		if (prog_is_subprog(obj, prog))
7111 			continue;
7112 		if (!prog->autoload) {
7113 			pr_debug("prog '%s': skipped loading\n", prog->name);
7114 			continue;
7115 		}
7116 		prog->log_level |= log_level;
7117 
7118 		if (obj->gen_loader)
7119 			bpf_program_record_relos(prog);
7120 
7121 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7122 					   obj->license, obj->kern_version, &prog->fd);
7123 		if (err) {
7124 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7125 			return err;
7126 		}
7127 	}
7128 
7129 	bpf_object__free_relocs(obj);
7130 	return 0;
7131 }
7132 
7133 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7134 
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7135 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7136 {
7137 	struct bpf_program *prog;
7138 	int err;
7139 
7140 	bpf_object__for_each_program(prog, obj) {
7141 		prog->sec_def = find_sec_def(prog->sec_name);
7142 		if (!prog->sec_def) {
7143 			/* couldn't guess, but user might manually specify */
7144 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7145 				prog->name, prog->sec_name);
7146 			continue;
7147 		}
7148 
7149 		prog->type = prog->sec_def->prog_type;
7150 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7151 
7152 		/* sec_def can have custom callback which should be called
7153 		 * after bpf_program is initialized to adjust its properties
7154 		 */
7155 		if (prog->sec_def->prog_setup_fn) {
7156 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7157 			if (err < 0) {
7158 				pr_warn("prog '%s': failed to initialize: %d\n",
7159 					prog->name, err);
7160 				return err;
7161 			}
7162 		}
7163 	}
7164 
7165 	return 0;
7166 }
7167 
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7168 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7169 					  const struct bpf_object_open_opts *opts)
7170 {
7171 	const char *obj_name, *kconfig, *btf_tmp_path;
7172 	struct bpf_object *obj;
7173 	char tmp_name[64];
7174 	int err;
7175 	char *log_buf;
7176 	size_t log_size;
7177 	__u32 log_level;
7178 
7179 	if (elf_version(EV_CURRENT) == EV_NONE) {
7180 		pr_warn("failed to init libelf for %s\n",
7181 			path ? : "(mem buf)");
7182 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7183 	}
7184 
7185 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7186 		return ERR_PTR(-EINVAL);
7187 
7188 	obj_name = OPTS_GET(opts, object_name, NULL);
7189 	if (obj_buf) {
7190 		if (!obj_name) {
7191 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7192 				 (unsigned long)obj_buf,
7193 				 (unsigned long)obj_buf_sz);
7194 			obj_name = tmp_name;
7195 		}
7196 		path = obj_name;
7197 		pr_debug("loading object '%s' from buffer\n", obj_name);
7198 	}
7199 
7200 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7201 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7202 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7203 	if (log_size > UINT_MAX)
7204 		return ERR_PTR(-EINVAL);
7205 	if (log_size && !log_buf)
7206 		return ERR_PTR(-EINVAL);
7207 
7208 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7209 	if (IS_ERR(obj))
7210 		return obj;
7211 
7212 	obj->log_buf = log_buf;
7213 	obj->log_size = log_size;
7214 	obj->log_level = log_level;
7215 
7216 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7217 	if (btf_tmp_path) {
7218 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7219 			err = -ENAMETOOLONG;
7220 			goto out;
7221 		}
7222 		obj->btf_custom_path = strdup(btf_tmp_path);
7223 		if (!obj->btf_custom_path) {
7224 			err = -ENOMEM;
7225 			goto out;
7226 		}
7227 	}
7228 
7229 	kconfig = OPTS_GET(opts, kconfig, NULL);
7230 	if (kconfig) {
7231 		obj->kconfig = strdup(kconfig);
7232 		if (!obj->kconfig) {
7233 			err = -ENOMEM;
7234 			goto out;
7235 		}
7236 	}
7237 
7238 	err = bpf_object__elf_init(obj);
7239 	err = err ? : bpf_object__check_endianness(obj);
7240 	err = err ? : bpf_object__elf_collect(obj);
7241 	err = err ? : bpf_object__collect_externs(obj);
7242 	err = err ? : bpf_object__finalize_btf(obj);
7243 	err = err ? : bpf_object__init_maps(obj, opts);
7244 	err = err ? : bpf_object_init_progs(obj, opts);
7245 	err = err ? : bpf_object__collect_relos(obj);
7246 	if (err)
7247 		goto out;
7248 
7249 	bpf_object__elf_finish(obj);
7250 
7251 	return obj;
7252 out:
7253 	bpf_object__close(obj);
7254 	return ERR_PTR(err);
7255 }
7256 
7257 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)7258 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7259 {
7260 	if (!path)
7261 		return libbpf_err_ptr(-EINVAL);
7262 
7263 	pr_debug("loading %s\n", path);
7264 
7265 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7266 }
7267 
bpf_object__open(const char * path)7268 struct bpf_object *bpf_object__open(const char *path)
7269 {
7270 	return bpf_object__open_file(path, NULL);
7271 }
7272 
7273 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7274 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7275 		     const struct bpf_object_open_opts *opts)
7276 {
7277 	if (!obj_buf || obj_buf_sz == 0)
7278 		return libbpf_err_ptr(-EINVAL);
7279 
7280 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7281 }
7282 
bpf_object_unload(struct bpf_object * obj)7283 static int bpf_object_unload(struct bpf_object *obj)
7284 {
7285 	size_t i;
7286 
7287 	if (!obj)
7288 		return libbpf_err(-EINVAL);
7289 
7290 	for (i = 0; i < obj->nr_maps; i++) {
7291 		zclose(obj->maps[i].fd);
7292 		if (obj->maps[i].st_ops)
7293 			zfree(&obj->maps[i].st_ops->kern_vdata);
7294 	}
7295 
7296 	for (i = 0; i < obj->nr_programs; i++)
7297 		bpf_program__unload(&obj->programs[i]);
7298 
7299 	return 0;
7300 }
7301 
bpf_object__sanitize_maps(struct bpf_object * obj)7302 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7303 {
7304 	struct bpf_map *m;
7305 
7306 	bpf_object__for_each_map(m, obj) {
7307 		if (!bpf_map__is_internal(m))
7308 			continue;
7309 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7310 			m->def.map_flags ^= BPF_F_MMAPABLE;
7311 	}
7312 
7313 	return 0;
7314 }
7315 
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)7316 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7317 {
7318 	char sym_type, sym_name[500];
7319 	unsigned long long sym_addr;
7320 	int ret, err = 0;
7321 	FILE *f;
7322 
7323 	f = fopen("/proc/kallsyms", "r");
7324 	if (!f) {
7325 		err = -errno;
7326 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7327 		return err;
7328 	}
7329 
7330 	while (true) {
7331 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7332 			     &sym_addr, &sym_type, sym_name);
7333 		if (ret == EOF && feof(f))
7334 			break;
7335 		if (ret != 3) {
7336 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7337 			err = -EINVAL;
7338 			break;
7339 		}
7340 
7341 		err = cb(sym_addr, sym_type, sym_name, ctx);
7342 		if (err)
7343 			break;
7344 	}
7345 
7346 	fclose(f);
7347 	return err;
7348 }
7349 
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)7350 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7351 		       const char *sym_name, void *ctx)
7352 {
7353 	struct bpf_object *obj = ctx;
7354 	const struct btf_type *t;
7355 	struct extern_desc *ext;
7356 
7357 	ext = find_extern_by_name(obj, sym_name);
7358 	if (!ext || ext->type != EXT_KSYM)
7359 		return 0;
7360 
7361 	t = btf__type_by_id(obj->btf, ext->btf_id);
7362 	if (!btf_is_var(t))
7363 		return 0;
7364 
7365 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7366 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7367 			sym_name, ext->ksym.addr, sym_addr);
7368 		return -EINVAL;
7369 	}
7370 	if (!ext->is_set) {
7371 		ext->is_set = true;
7372 		ext->ksym.addr = sym_addr;
7373 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7374 	}
7375 	return 0;
7376 }
7377 
bpf_object__read_kallsyms_file(struct bpf_object * obj)7378 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7379 {
7380 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7381 }
7382 
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)7383 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7384 			    __u16 kind, struct btf **res_btf,
7385 			    struct module_btf **res_mod_btf)
7386 {
7387 	struct module_btf *mod_btf;
7388 	struct btf *btf;
7389 	int i, id, err;
7390 
7391 	btf = obj->btf_vmlinux;
7392 	mod_btf = NULL;
7393 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7394 
7395 	if (id == -ENOENT) {
7396 		err = load_module_btfs(obj);
7397 		if (err)
7398 			return err;
7399 
7400 		for (i = 0; i < obj->btf_module_cnt; i++) {
7401 			/* we assume module_btf's BTF FD is always >0 */
7402 			mod_btf = &obj->btf_modules[i];
7403 			btf = mod_btf->btf;
7404 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7405 			if (id != -ENOENT)
7406 				break;
7407 		}
7408 	}
7409 	if (id <= 0)
7410 		return -ESRCH;
7411 
7412 	*res_btf = btf;
7413 	*res_mod_btf = mod_btf;
7414 	return id;
7415 }
7416 
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)7417 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7418 					       struct extern_desc *ext)
7419 {
7420 	const struct btf_type *targ_var, *targ_type;
7421 	__u32 targ_type_id, local_type_id;
7422 	struct module_btf *mod_btf = NULL;
7423 	const char *targ_var_name;
7424 	struct btf *btf = NULL;
7425 	int id, err;
7426 
7427 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7428 	if (id < 0) {
7429 		if (id == -ESRCH && ext->is_weak)
7430 			return 0;
7431 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7432 			ext->name);
7433 		return id;
7434 	}
7435 
7436 	/* find local type_id */
7437 	local_type_id = ext->ksym.type_id;
7438 
7439 	/* find target type_id */
7440 	targ_var = btf__type_by_id(btf, id);
7441 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7442 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7443 
7444 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7445 					btf, targ_type_id);
7446 	if (err <= 0) {
7447 		const struct btf_type *local_type;
7448 		const char *targ_name, *local_name;
7449 
7450 		local_type = btf__type_by_id(obj->btf, local_type_id);
7451 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7452 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7453 
7454 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7455 			ext->name, local_type_id,
7456 			btf_kind_str(local_type), local_name, targ_type_id,
7457 			btf_kind_str(targ_type), targ_name);
7458 		return -EINVAL;
7459 	}
7460 
7461 	ext->is_set = true;
7462 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7463 	ext->ksym.kernel_btf_id = id;
7464 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7465 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7466 
7467 	return 0;
7468 }
7469 
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)7470 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7471 						struct extern_desc *ext)
7472 {
7473 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7474 	struct module_btf *mod_btf = NULL;
7475 	const struct btf_type *kern_func;
7476 	struct btf *kern_btf = NULL;
7477 	int ret;
7478 
7479 	local_func_proto_id = ext->ksym.type_id;
7480 
7481 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7482 	if (kfunc_id < 0) {
7483 		if (kfunc_id == -ESRCH && ext->is_weak)
7484 			return 0;
7485 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7486 			ext->name);
7487 		return kfunc_id;
7488 	}
7489 
7490 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7491 	kfunc_proto_id = kern_func->type;
7492 
7493 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7494 					kern_btf, kfunc_proto_id);
7495 	if (ret <= 0) {
7496 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7497 			ext->name, local_func_proto_id, kfunc_proto_id);
7498 		return -EINVAL;
7499 	}
7500 
7501 	/* set index for module BTF fd in fd_array, if unset */
7502 	if (mod_btf && !mod_btf->fd_array_idx) {
7503 		/* insn->off is s16 */
7504 		if (obj->fd_array_cnt == INT16_MAX) {
7505 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7506 				ext->name, mod_btf->fd_array_idx);
7507 			return -E2BIG;
7508 		}
7509 		/* Cannot use index 0 for module BTF fd */
7510 		if (!obj->fd_array_cnt)
7511 			obj->fd_array_cnt = 1;
7512 
7513 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7514 					obj->fd_array_cnt + 1);
7515 		if (ret)
7516 			return ret;
7517 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7518 		/* we assume module BTF FD is always >0 */
7519 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7520 	}
7521 
7522 	ext->is_set = true;
7523 	ext->ksym.kernel_btf_id = kfunc_id;
7524 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7525 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7526 		 ext->name, kfunc_id);
7527 
7528 	return 0;
7529 }
7530 
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)7531 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7532 {
7533 	const struct btf_type *t;
7534 	struct extern_desc *ext;
7535 	int i, err;
7536 
7537 	for (i = 0; i < obj->nr_extern; i++) {
7538 		ext = &obj->externs[i];
7539 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7540 			continue;
7541 
7542 		if (obj->gen_loader) {
7543 			ext->is_set = true;
7544 			ext->ksym.kernel_btf_obj_fd = 0;
7545 			ext->ksym.kernel_btf_id = 0;
7546 			continue;
7547 		}
7548 		t = btf__type_by_id(obj->btf, ext->btf_id);
7549 		if (btf_is_var(t))
7550 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7551 		else
7552 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7553 		if (err)
7554 			return err;
7555 	}
7556 	return 0;
7557 }
7558 
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)7559 static int bpf_object__resolve_externs(struct bpf_object *obj,
7560 				       const char *extra_kconfig)
7561 {
7562 	bool need_config = false, need_kallsyms = false;
7563 	bool need_vmlinux_btf = false;
7564 	struct extern_desc *ext;
7565 	void *kcfg_data = NULL;
7566 	int err, i;
7567 
7568 	if (obj->nr_extern == 0)
7569 		return 0;
7570 
7571 	if (obj->kconfig_map_idx >= 0)
7572 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7573 
7574 	for (i = 0; i < obj->nr_extern; i++) {
7575 		ext = &obj->externs[i];
7576 
7577 		if (ext->type == EXT_KSYM) {
7578 			if (ext->ksym.type_id)
7579 				need_vmlinux_btf = true;
7580 			else
7581 				need_kallsyms = true;
7582 			continue;
7583 		} else if (ext->type == EXT_KCFG) {
7584 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7585 			__u64 value = 0;
7586 
7587 			/* Kconfig externs need actual /proc/config.gz */
7588 			if (str_has_pfx(ext->name, "CONFIG_")) {
7589 				need_config = true;
7590 				continue;
7591 			}
7592 
7593 			/* Virtual kcfg externs are customly handled by libbpf */
7594 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7595 				value = get_kernel_version();
7596 				if (!value) {
7597 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7598 					return -EINVAL;
7599 				}
7600 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7601 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7602 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7603 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7604 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7605 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7606 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7607 				 * customly by libbpf (their values don't come from Kconfig).
7608 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7609 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7610 				 * externs.
7611 				 */
7612 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7613 				return -EINVAL;
7614 			}
7615 
7616 			err = set_kcfg_value_num(ext, ext_ptr, value);
7617 			if (err)
7618 				return err;
7619 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7620 				 ext->name, (long long)value);
7621 		} else {
7622 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7623 			return -EINVAL;
7624 		}
7625 	}
7626 	if (need_config && extra_kconfig) {
7627 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7628 		if (err)
7629 			return -EINVAL;
7630 		need_config = false;
7631 		for (i = 0; i < obj->nr_extern; i++) {
7632 			ext = &obj->externs[i];
7633 			if (ext->type == EXT_KCFG && !ext->is_set) {
7634 				need_config = true;
7635 				break;
7636 			}
7637 		}
7638 	}
7639 	if (need_config) {
7640 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7641 		if (err)
7642 			return -EINVAL;
7643 	}
7644 	if (need_kallsyms) {
7645 		err = bpf_object__read_kallsyms_file(obj);
7646 		if (err)
7647 			return -EINVAL;
7648 	}
7649 	if (need_vmlinux_btf) {
7650 		err = bpf_object__resolve_ksyms_btf_id(obj);
7651 		if (err)
7652 			return -EINVAL;
7653 	}
7654 	for (i = 0; i < obj->nr_extern; i++) {
7655 		ext = &obj->externs[i];
7656 
7657 		if (!ext->is_set && !ext->is_weak) {
7658 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7659 			return -ESRCH;
7660 		} else if (!ext->is_set) {
7661 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7662 				 ext->name);
7663 		}
7664 	}
7665 
7666 	return 0;
7667 }
7668 
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)7669 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7670 {
7671 	int err, i;
7672 
7673 	if (!obj)
7674 		return libbpf_err(-EINVAL);
7675 
7676 	if (obj->loaded) {
7677 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7678 		return libbpf_err(-EINVAL);
7679 	}
7680 
7681 	if (obj->gen_loader)
7682 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7683 
7684 	err = bpf_object__probe_loading(obj);
7685 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7686 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7687 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7688 	err = err ? : bpf_object__sanitize_maps(obj);
7689 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7690 	err = err ? : bpf_object__create_maps(obj);
7691 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7692 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7693 	err = err ? : bpf_object_init_prog_arrays(obj);
7694 
7695 	if (obj->gen_loader) {
7696 		/* reset FDs */
7697 		if (obj->btf)
7698 			btf__set_fd(obj->btf, -1);
7699 		for (i = 0; i < obj->nr_maps; i++)
7700 			obj->maps[i].fd = -1;
7701 		if (!err)
7702 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7703 	}
7704 
7705 	/* clean up fd_array */
7706 	zfree(&obj->fd_array);
7707 
7708 	/* clean up module BTFs */
7709 	for (i = 0; i < obj->btf_module_cnt; i++) {
7710 		close(obj->btf_modules[i].fd);
7711 		btf__free(obj->btf_modules[i].btf);
7712 		free(obj->btf_modules[i].name);
7713 	}
7714 	free(obj->btf_modules);
7715 
7716 	/* clean up vmlinux BTF */
7717 	btf__free(obj->btf_vmlinux);
7718 	obj->btf_vmlinux = NULL;
7719 
7720 	obj->loaded = true; /* doesn't matter if successfully or not */
7721 
7722 	if (err)
7723 		goto out;
7724 
7725 	return 0;
7726 out:
7727 	/* unpin any maps that were auto-pinned during load */
7728 	for (i = 0; i < obj->nr_maps; i++)
7729 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7730 			bpf_map__unpin(&obj->maps[i], NULL);
7731 
7732 	bpf_object_unload(obj);
7733 	pr_warn("failed to load object '%s'\n", obj->path);
7734 	return libbpf_err(err);
7735 }
7736 
bpf_object__load(struct bpf_object * obj)7737 int bpf_object__load(struct bpf_object *obj)
7738 {
7739 	return bpf_object_load(obj, 0, NULL);
7740 }
7741 
make_parent_dir(const char * path)7742 static int make_parent_dir(const char *path)
7743 {
7744 	char *cp, errmsg[STRERR_BUFSIZE];
7745 	char *dname, *dir;
7746 	int err = 0;
7747 
7748 	dname = strdup(path);
7749 	if (dname == NULL)
7750 		return -ENOMEM;
7751 
7752 	dir = dirname(dname);
7753 	if (mkdir(dir, 0700) && errno != EEXIST)
7754 		err = -errno;
7755 
7756 	free(dname);
7757 	if (err) {
7758 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7759 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7760 	}
7761 	return err;
7762 }
7763 
check_path(const char * path)7764 static int check_path(const char *path)
7765 {
7766 	char *cp, errmsg[STRERR_BUFSIZE];
7767 	struct statfs st_fs;
7768 	char *dname, *dir;
7769 	int err = 0;
7770 
7771 	if (path == NULL)
7772 		return -EINVAL;
7773 
7774 	dname = strdup(path);
7775 	if (dname == NULL)
7776 		return -ENOMEM;
7777 
7778 	dir = dirname(dname);
7779 	if (statfs(dir, &st_fs)) {
7780 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7781 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7782 		err = -errno;
7783 	}
7784 	free(dname);
7785 
7786 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7787 		pr_warn("specified path %s is not on BPF FS\n", path);
7788 		err = -EINVAL;
7789 	}
7790 
7791 	return err;
7792 }
7793 
bpf_program__pin(struct bpf_program * prog,const char * path)7794 int bpf_program__pin(struct bpf_program *prog, const char *path)
7795 {
7796 	char *cp, errmsg[STRERR_BUFSIZE];
7797 	int err;
7798 
7799 	if (prog->fd < 0) {
7800 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7801 		return libbpf_err(-EINVAL);
7802 	}
7803 
7804 	err = make_parent_dir(path);
7805 	if (err)
7806 		return libbpf_err(err);
7807 
7808 	err = check_path(path);
7809 	if (err)
7810 		return libbpf_err(err);
7811 
7812 	if (bpf_obj_pin(prog->fd, path)) {
7813 		err = -errno;
7814 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7815 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7816 		return libbpf_err(err);
7817 	}
7818 
7819 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7820 	return 0;
7821 }
7822 
bpf_program__unpin(struct bpf_program * prog,const char * path)7823 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7824 {
7825 	int err;
7826 
7827 	if (prog->fd < 0) {
7828 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7829 		return libbpf_err(-EINVAL);
7830 	}
7831 
7832 	err = check_path(path);
7833 	if (err)
7834 		return libbpf_err(err);
7835 
7836 	err = unlink(path);
7837 	if (err)
7838 		return libbpf_err(-errno);
7839 
7840 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7841 	return 0;
7842 }
7843 
bpf_map__pin(struct bpf_map * map,const char * path)7844 int bpf_map__pin(struct bpf_map *map, const char *path)
7845 {
7846 	char *cp, errmsg[STRERR_BUFSIZE];
7847 	int err;
7848 
7849 	if (map == NULL) {
7850 		pr_warn("invalid map pointer\n");
7851 		return libbpf_err(-EINVAL);
7852 	}
7853 
7854 	if (map->pin_path) {
7855 		if (path && strcmp(path, map->pin_path)) {
7856 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7857 				bpf_map__name(map), map->pin_path, path);
7858 			return libbpf_err(-EINVAL);
7859 		} else if (map->pinned) {
7860 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7861 				 bpf_map__name(map), map->pin_path);
7862 			return 0;
7863 		}
7864 	} else {
7865 		if (!path) {
7866 			pr_warn("missing a path to pin map '%s' at\n",
7867 				bpf_map__name(map));
7868 			return libbpf_err(-EINVAL);
7869 		} else if (map->pinned) {
7870 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7871 			return libbpf_err(-EEXIST);
7872 		}
7873 
7874 		map->pin_path = strdup(path);
7875 		if (!map->pin_path) {
7876 			err = -errno;
7877 			goto out_err;
7878 		}
7879 	}
7880 
7881 	err = make_parent_dir(map->pin_path);
7882 	if (err)
7883 		return libbpf_err(err);
7884 
7885 	err = check_path(map->pin_path);
7886 	if (err)
7887 		return libbpf_err(err);
7888 
7889 	if (bpf_obj_pin(map->fd, map->pin_path)) {
7890 		err = -errno;
7891 		goto out_err;
7892 	}
7893 
7894 	map->pinned = true;
7895 	pr_debug("pinned map '%s'\n", map->pin_path);
7896 
7897 	return 0;
7898 
7899 out_err:
7900 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7901 	pr_warn("failed to pin map: %s\n", cp);
7902 	return libbpf_err(err);
7903 }
7904 
bpf_map__unpin(struct bpf_map * map,const char * path)7905 int bpf_map__unpin(struct bpf_map *map, const char *path)
7906 {
7907 	int err;
7908 
7909 	if (map == NULL) {
7910 		pr_warn("invalid map pointer\n");
7911 		return libbpf_err(-EINVAL);
7912 	}
7913 
7914 	if (map->pin_path) {
7915 		if (path && strcmp(path, map->pin_path)) {
7916 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7917 				bpf_map__name(map), map->pin_path, path);
7918 			return libbpf_err(-EINVAL);
7919 		}
7920 		path = map->pin_path;
7921 	} else if (!path) {
7922 		pr_warn("no path to unpin map '%s' from\n",
7923 			bpf_map__name(map));
7924 		return libbpf_err(-EINVAL);
7925 	}
7926 
7927 	err = check_path(path);
7928 	if (err)
7929 		return libbpf_err(err);
7930 
7931 	err = unlink(path);
7932 	if (err != 0)
7933 		return libbpf_err(-errno);
7934 
7935 	map->pinned = false;
7936 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7937 
7938 	return 0;
7939 }
7940 
bpf_map__set_pin_path(struct bpf_map * map,const char * path)7941 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7942 {
7943 	char *new = NULL;
7944 
7945 	if (path) {
7946 		new = strdup(path);
7947 		if (!new)
7948 			return libbpf_err(-errno);
7949 	}
7950 
7951 	free(map->pin_path);
7952 	map->pin_path = new;
7953 	return 0;
7954 }
7955 
7956 __alias(bpf_map__pin_path)
7957 const char *bpf_map__get_pin_path(const struct bpf_map *map);
7958 
bpf_map__pin_path(const struct bpf_map * map)7959 const char *bpf_map__pin_path(const struct bpf_map *map)
7960 {
7961 	return map->pin_path;
7962 }
7963 
bpf_map__is_pinned(const struct bpf_map * map)7964 bool bpf_map__is_pinned(const struct bpf_map *map)
7965 {
7966 	return map->pinned;
7967 }
7968 
sanitize_pin_path(char * s)7969 static void sanitize_pin_path(char *s)
7970 {
7971 	/* bpffs disallows periods in path names */
7972 	while (*s) {
7973 		if (*s == '.')
7974 			*s = '_';
7975 		s++;
7976 	}
7977 }
7978 
bpf_object__pin_maps(struct bpf_object * obj,const char * path)7979 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7980 {
7981 	struct bpf_map *map;
7982 	int err;
7983 
7984 	if (!obj)
7985 		return libbpf_err(-ENOENT);
7986 
7987 	if (!obj->loaded) {
7988 		pr_warn("object not yet loaded; load it first\n");
7989 		return libbpf_err(-ENOENT);
7990 	}
7991 
7992 	bpf_object__for_each_map(map, obj) {
7993 		char *pin_path = NULL;
7994 		char buf[PATH_MAX];
7995 
7996 		if (!map->autocreate)
7997 			continue;
7998 
7999 		if (path) {
8000 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8001 			if (err)
8002 				goto err_unpin_maps;
8003 			sanitize_pin_path(buf);
8004 			pin_path = buf;
8005 		} else if (!map->pin_path) {
8006 			continue;
8007 		}
8008 
8009 		err = bpf_map__pin(map, pin_path);
8010 		if (err)
8011 			goto err_unpin_maps;
8012 	}
8013 
8014 	return 0;
8015 
8016 err_unpin_maps:
8017 	while ((map = bpf_object__prev_map(obj, map))) {
8018 		if (!map->pin_path)
8019 			continue;
8020 
8021 		bpf_map__unpin(map, NULL);
8022 	}
8023 
8024 	return libbpf_err(err);
8025 }
8026 
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8027 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8028 {
8029 	struct bpf_map *map;
8030 	int err;
8031 
8032 	if (!obj)
8033 		return libbpf_err(-ENOENT);
8034 
8035 	bpf_object__for_each_map(map, obj) {
8036 		char *pin_path = NULL;
8037 		char buf[PATH_MAX];
8038 
8039 		if (path) {
8040 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8041 			if (err)
8042 				return libbpf_err(err);
8043 			sanitize_pin_path(buf);
8044 			pin_path = buf;
8045 		} else if (!map->pin_path) {
8046 			continue;
8047 		}
8048 
8049 		err = bpf_map__unpin(map, pin_path);
8050 		if (err)
8051 			return libbpf_err(err);
8052 	}
8053 
8054 	return 0;
8055 }
8056 
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8057 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8058 {
8059 	struct bpf_program *prog;
8060 	char buf[PATH_MAX];
8061 	int err;
8062 
8063 	if (!obj)
8064 		return libbpf_err(-ENOENT);
8065 
8066 	if (!obj->loaded) {
8067 		pr_warn("object not yet loaded; load it first\n");
8068 		return libbpf_err(-ENOENT);
8069 	}
8070 
8071 	bpf_object__for_each_program(prog, obj) {
8072 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8073 		if (err)
8074 			goto err_unpin_programs;
8075 
8076 		err = bpf_program__pin(prog, buf);
8077 		if (err)
8078 			goto err_unpin_programs;
8079 	}
8080 
8081 	return 0;
8082 
8083 err_unpin_programs:
8084 	while ((prog = bpf_object__prev_program(obj, prog))) {
8085 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8086 			continue;
8087 
8088 		bpf_program__unpin(prog, buf);
8089 	}
8090 
8091 	return libbpf_err(err);
8092 }
8093 
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)8094 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8095 {
8096 	struct bpf_program *prog;
8097 	int err;
8098 
8099 	if (!obj)
8100 		return libbpf_err(-ENOENT);
8101 
8102 	bpf_object__for_each_program(prog, obj) {
8103 		char buf[PATH_MAX];
8104 
8105 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8106 		if (err)
8107 			return libbpf_err(err);
8108 
8109 		err = bpf_program__unpin(prog, buf);
8110 		if (err)
8111 			return libbpf_err(err);
8112 	}
8113 
8114 	return 0;
8115 }
8116 
bpf_object__pin(struct bpf_object * obj,const char * path)8117 int bpf_object__pin(struct bpf_object *obj, const char *path)
8118 {
8119 	int err;
8120 
8121 	err = bpf_object__pin_maps(obj, path);
8122 	if (err)
8123 		return libbpf_err(err);
8124 
8125 	err = bpf_object__pin_programs(obj, path);
8126 	if (err) {
8127 		bpf_object__unpin_maps(obj, path);
8128 		return libbpf_err(err);
8129 	}
8130 
8131 	return 0;
8132 }
8133 
bpf_map__destroy(struct bpf_map * map)8134 static void bpf_map__destroy(struct bpf_map *map)
8135 {
8136 	if (map->inner_map) {
8137 		bpf_map__destroy(map->inner_map);
8138 		zfree(&map->inner_map);
8139 	}
8140 
8141 	zfree(&map->init_slots);
8142 	map->init_slots_sz = 0;
8143 
8144 	if (map->mmaped) {
8145 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8146 		map->mmaped = NULL;
8147 	}
8148 
8149 	if (map->st_ops) {
8150 		zfree(&map->st_ops->data);
8151 		zfree(&map->st_ops->progs);
8152 		zfree(&map->st_ops->kern_func_off);
8153 		zfree(&map->st_ops);
8154 	}
8155 
8156 	zfree(&map->name);
8157 	zfree(&map->real_name);
8158 	zfree(&map->pin_path);
8159 
8160 	if (map->fd >= 0)
8161 		zclose(map->fd);
8162 }
8163 
bpf_object__close(struct bpf_object * obj)8164 void bpf_object__close(struct bpf_object *obj)
8165 {
8166 	size_t i;
8167 
8168 	if (IS_ERR_OR_NULL(obj))
8169 		return;
8170 
8171 	usdt_manager_free(obj->usdt_man);
8172 	obj->usdt_man = NULL;
8173 
8174 	bpf_gen__free(obj->gen_loader);
8175 	bpf_object__elf_finish(obj);
8176 	bpf_object_unload(obj);
8177 	btf__free(obj->btf);
8178 	btf__free(obj->btf_vmlinux);
8179 	btf_ext__free(obj->btf_ext);
8180 
8181 	for (i = 0; i < obj->nr_maps; i++)
8182 		bpf_map__destroy(&obj->maps[i]);
8183 
8184 	zfree(&obj->btf_custom_path);
8185 	zfree(&obj->kconfig);
8186 	zfree(&obj->externs);
8187 	obj->nr_extern = 0;
8188 
8189 	zfree(&obj->maps);
8190 	obj->nr_maps = 0;
8191 
8192 	if (obj->programs && obj->nr_programs) {
8193 		for (i = 0; i < obj->nr_programs; i++)
8194 			bpf_program__exit(&obj->programs[i]);
8195 	}
8196 	zfree(&obj->programs);
8197 
8198 	free(obj);
8199 }
8200 
bpf_object__name(const struct bpf_object * obj)8201 const char *bpf_object__name(const struct bpf_object *obj)
8202 {
8203 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8204 }
8205 
bpf_object__kversion(const struct bpf_object * obj)8206 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8207 {
8208 	return obj ? obj->kern_version : 0;
8209 }
8210 
bpf_object__btf(const struct bpf_object * obj)8211 struct btf *bpf_object__btf(const struct bpf_object *obj)
8212 {
8213 	return obj ? obj->btf : NULL;
8214 }
8215 
bpf_object__btf_fd(const struct bpf_object * obj)8216 int bpf_object__btf_fd(const struct bpf_object *obj)
8217 {
8218 	return obj->btf ? btf__fd(obj->btf) : -1;
8219 }
8220 
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)8221 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8222 {
8223 	if (obj->loaded)
8224 		return libbpf_err(-EINVAL);
8225 
8226 	obj->kern_version = kern_version;
8227 
8228 	return 0;
8229 }
8230 
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)8231 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8232 {
8233 	struct bpf_gen *gen;
8234 
8235 	if (!opts)
8236 		return -EFAULT;
8237 	if (!OPTS_VALID(opts, gen_loader_opts))
8238 		return -EINVAL;
8239 	gen = calloc(sizeof(*gen), 1);
8240 	if (!gen)
8241 		return -ENOMEM;
8242 	gen->opts = opts;
8243 	obj->gen_loader = gen;
8244 	return 0;
8245 }
8246 
8247 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)8248 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8249 		    bool forward)
8250 {
8251 	size_t nr_programs = obj->nr_programs;
8252 	ssize_t idx;
8253 
8254 	if (!nr_programs)
8255 		return NULL;
8256 
8257 	if (!p)
8258 		/* Iter from the beginning */
8259 		return forward ? &obj->programs[0] :
8260 			&obj->programs[nr_programs - 1];
8261 
8262 	if (p->obj != obj) {
8263 		pr_warn("error: program handler doesn't match object\n");
8264 		return errno = EINVAL, NULL;
8265 	}
8266 
8267 	idx = (p - obj->programs) + (forward ? 1 : -1);
8268 	if (idx >= obj->nr_programs || idx < 0)
8269 		return NULL;
8270 	return &obj->programs[idx];
8271 }
8272 
8273 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)8274 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8275 {
8276 	struct bpf_program *prog = prev;
8277 
8278 	do {
8279 		prog = __bpf_program__iter(prog, obj, true);
8280 	} while (prog && prog_is_subprog(obj, prog));
8281 
8282 	return prog;
8283 }
8284 
8285 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)8286 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8287 {
8288 	struct bpf_program *prog = next;
8289 
8290 	do {
8291 		prog = __bpf_program__iter(prog, obj, false);
8292 	} while (prog && prog_is_subprog(obj, prog));
8293 
8294 	return prog;
8295 }
8296 
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)8297 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8298 {
8299 	prog->prog_ifindex = ifindex;
8300 }
8301 
bpf_program__name(const struct bpf_program * prog)8302 const char *bpf_program__name(const struct bpf_program *prog)
8303 {
8304 	return prog->name;
8305 }
8306 
bpf_program__section_name(const struct bpf_program * prog)8307 const char *bpf_program__section_name(const struct bpf_program *prog)
8308 {
8309 	return prog->sec_name;
8310 }
8311 
bpf_program__autoload(const struct bpf_program * prog)8312 bool bpf_program__autoload(const struct bpf_program *prog)
8313 {
8314 	return prog->autoload;
8315 }
8316 
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)8317 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8318 {
8319 	if (prog->obj->loaded)
8320 		return libbpf_err(-EINVAL);
8321 
8322 	prog->autoload = autoload;
8323 	return 0;
8324 }
8325 
bpf_program__autoattach(const struct bpf_program * prog)8326 bool bpf_program__autoattach(const struct bpf_program *prog)
8327 {
8328 	return prog->autoattach;
8329 }
8330 
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)8331 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8332 {
8333 	prog->autoattach = autoattach;
8334 }
8335 
bpf_program__insns(const struct bpf_program * prog)8336 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8337 {
8338 	return prog->insns;
8339 }
8340 
bpf_program__insn_cnt(const struct bpf_program * prog)8341 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8342 {
8343 	return prog->insns_cnt;
8344 }
8345 
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)8346 int bpf_program__set_insns(struct bpf_program *prog,
8347 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8348 {
8349 	struct bpf_insn *insns;
8350 
8351 	if (prog->obj->loaded)
8352 		return -EBUSY;
8353 
8354 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8355 	/* NULL is a valid return from reallocarray if the new count is zero */
8356 	if (!insns && new_insn_cnt) {
8357 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8358 		return -ENOMEM;
8359 	}
8360 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8361 
8362 	prog->insns = insns;
8363 	prog->insns_cnt = new_insn_cnt;
8364 	return 0;
8365 }
8366 
bpf_program__fd(const struct bpf_program * prog)8367 int bpf_program__fd(const struct bpf_program *prog)
8368 {
8369 	if (!prog)
8370 		return libbpf_err(-EINVAL);
8371 
8372 	if (prog->fd < 0)
8373 		return libbpf_err(-ENOENT);
8374 
8375 	return prog->fd;
8376 }
8377 
8378 __alias(bpf_program__type)
8379 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8380 
bpf_program__type(const struct bpf_program * prog)8381 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8382 {
8383 	return prog->type;
8384 }
8385 
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)8386 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8387 {
8388 	if (prog->obj->loaded)
8389 		return libbpf_err(-EBUSY);
8390 
8391 	prog->type = type;
8392 	return 0;
8393 }
8394 
8395 __alias(bpf_program__expected_attach_type)
8396 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8397 
bpf_program__expected_attach_type(const struct bpf_program * prog)8398 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8399 {
8400 	return prog->expected_attach_type;
8401 }
8402 
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)8403 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8404 					   enum bpf_attach_type type)
8405 {
8406 	if (prog->obj->loaded)
8407 		return libbpf_err(-EBUSY);
8408 
8409 	prog->expected_attach_type = type;
8410 	return 0;
8411 }
8412 
bpf_program__flags(const struct bpf_program * prog)8413 __u32 bpf_program__flags(const struct bpf_program *prog)
8414 {
8415 	return prog->prog_flags;
8416 }
8417 
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)8418 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8419 {
8420 	if (prog->obj->loaded)
8421 		return libbpf_err(-EBUSY);
8422 
8423 	prog->prog_flags = flags;
8424 	return 0;
8425 }
8426 
bpf_program__log_level(const struct bpf_program * prog)8427 __u32 bpf_program__log_level(const struct bpf_program *prog)
8428 {
8429 	return prog->log_level;
8430 }
8431 
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)8432 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8433 {
8434 	if (prog->obj->loaded)
8435 		return libbpf_err(-EBUSY);
8436 
8437 	prog->log_level = log_level;
8438 	return 0;
8439 }
8440 
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)8441 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8442 {
8443 	*log_size = prog->log_size;
8444 	return prog->log_buf;
8445 }
8446 
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)8447 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8448 {
8449 	if (log_size && !log_buf)
8450 		return -EINVAL;
8451 	if (prog->log_size > UINT_MAX)
8452 		return -EINVAL;
8453 	if (prog->obj->loaded)
8454 		return -EBUSY;
8455 
8456 	prog->log_buf = log_buf;
8457 	prog->log_size = log_size;
8458 	return 0;
8459 }
8460 
8461 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8462 	.sec = (char *)sec_pfx,						    \
8463 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8464 	.expected_attach_type = atype,					    \
8465 	.cookie = (long)(flags),					    \
8466 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8467 	__VA_ARGS__							    \
8468 }
8469 
8470 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8471 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8472 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8473 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8474 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8475 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8476 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8477 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8478 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8479 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8480 
8481 static const struct bpf_sec_def section_defs[] = {
8482 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8483 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8484 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8485 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8486 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8487 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8488 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8489 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8490 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8491 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8492 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8493 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8494 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8495 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8496 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8497 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8498 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8499 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8500 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8501 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8502 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8503 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8504 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8505 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8506 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8507 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8508 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8509 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8510 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8511 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8512 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8513 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8514 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8515 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8516 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8517 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8518 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8519 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8520 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8521 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8522 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8523 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8524 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8525 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8526 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8527 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8528 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8529 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8530 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8531 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8532 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8533 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8534 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8535 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8536 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8537 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8538 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8539 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8540 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8541 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8542 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8543 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8544 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8545 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8546 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8547 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8548 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8549 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8550 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8551 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8552 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8553 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8554 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8555 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8556 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8557 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8558 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8559 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8560 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8561 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8562 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8563 };
8564 
8565 static size_t custom_sec_def_cnt;
8566 static struct bpf_sec_def *custom_sec_defs;
8567 static struct bpf_sec_def custom_fallback_def;
8568 static bool has_custom_fallback_def;
8569 
8570 static int last_custom_sec_def_handler_id;
8571 
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)8572 int libbpf_register_prog_handler(const char *sec,
8573 				 enum bpf_prog_type prog_type,
8574 				 enum bpf_attach_type exp_attach_type,
8575 				 const struct libbpf_prog_handler_opts *opts)
8576 {
8577 	struct bpf_sec_def *sec_def;
8578 
8579 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8580 		return libbpf_err(-EINVAL);
8581 
8582 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8583 		return libbpf_err(-E2BIG);
8584 
8585 	if (sec) {
8586 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8587 					      sizeof(*sec_def));
8588 		if (!sec_def)
8589 			return libbpf_err(-ENOMEM);
8590 
8591 		custom_sec_defs = sec_def;
8592 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8593 	} else {
8594 		if (has_custom_fallback_def)
8595 			return libbpf_err(-EBUSY);
8596 
8597 		sec_def = &custom_fallback_def;
8598 	}
8599 
8600 	sec_def->sec = sec ? strdup(sec) : NULL;
8601 	if (sec && !sec_def->sec)
8602 		return libbpf_err(-ENOMEM);
8603 
8604 	sec_def->prog_type = prog_type;
8605 	sec_def->expected_attach_type = exp_attach_type;
8606 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8607 
8608 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8609 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8610 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8611 
8612 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8613 
8614 	if (sec)
8615 		custom_sec_def_cnt++;
8616 	else
8617 		has_custom_fallback_def = true;
8618 
8619 	return sec_def->handler_id;
8620 }
8621 
libbpf_unregister_prog_handler(int handler_id)8622 int libbpf_unregister_prog_handler(int handler_id)
8623 {
8624 	struct bpf_sec_def *sec_defs;
8625 	int i;
8626 
8627 	if (handler_id <= 0)
8628 		return libbpf_err(-EINVAL);
8629 
8630 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8631 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8632 		has_custom_fallback_def = false;
8633 		return 0;
8634 	}
8635 
8636 	for (i = 0; i < custom_sec_def_cnt; i++) {
8637 		if (custom_sec_defs[i].handler_id == handler_id)
8638 			break;
8639 	}
8640 
8641 	if (i == custom_sec_def_cnt)
8642 		return libbpf_err(-ENOENT);
8643 
8644 	free(custom_sec_defs[i].sec);
8645 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8646 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8647 	custom_sec_def_cnt--;
8648 
8649 	/* try to shrink the array, but it's ok if we couldn't */
8650 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8651 	/* if new count is zero, reallocarray can return a valid NULL result;
8652 	 * in this case the previous pointer will be freed, so we *have to*
8653 	 * reassign old pointer to the new value (even if it's NULL)
8654 	 */
8655 	if (sec_defs || custom_sec_def_cnt == 0)
8656 		custom_sec_defs = sec_defs;
8657 
8658 	return 0;
8659 }
8660 
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)8661 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8662 {
8663 	size_t len = strlen(sec_def->sec);
8664 
8665 	/* "type/" always has to have proper SEC("type/extras") form */
8666 	if (sec_def->sec[len - 1] == '/') {
8667 		if (str_has_pfx(sec_name, sec_def->sec))
8668 			return true;
8669 		return false;
8670 	}
8671 
8672 	/* "type+" means it can be either exact SEC("type") or
8673 	 * well-formed SEC("type/extras") with proper '/' separator
8674 	 */
8675 	if (sec_def->sec[len - 1] == '+') {
8676 		len--;
8677 		/* not even a prefix */
8678 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8679 			return false;
8680 		/* exact match or has '/' separator */
8681 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8682 			return true;
8683 		return false;
8684 	}
8685 
8686 	return strcmp(sec_name, sec_def->sec) == 0;
8687 }
8688 
find_sec_def(const char * sec_name)8689 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8690 {
8691 	const struct bpf_sec_def *sec_def;
8692 	int i, n;
8693 
8694 	n = custom_sec_def_cnt;
8695 	for (i = 0; i < n; i++) {
8696 		sec_def = &custom_sec_defs[i];
8697 		if (sec_def_matches(sec_def, sec_name))
8698 			return sec_def;
8699 	}
8700 
8701 	n = ARRAY_SIZE(section_defs);
8702 	for (i = 0; i < n; i++) {
8703 		sec_def = &section_defs[i];
8704 		if (sec_def_matches(sec_def, sec_name))
8705 			return sec_def;
8706 	}
8707 
8708 	if (has_custom_fallback_def)
8709 		return &custom_fallback_def;
8710 
8711 	return NULL;
8712 }
8713 
8714 #define MAX_TYPE_NAME_SIZE 32
8715 
libbpf_get_type_names(bool attach_type)8716 static char *libbpf_get_type_names(bool attach_type)
8717 {
8718 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8719 	char *buf;
8720 
8721 	buf = malloc(len);
8722 	if (!buf)
8723 		return NULL;
8724 
8725 	buf[0] = '\0';
8726 	/* Forge string buf with all available names */
8727 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8728 		const struct bpf_sec_def *sec_def = &section_defs[i];
8729 
8730 		if (attach_type) {
8731 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8732 				continue;
8733 
8734 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8735 				continue;
8736 		}
8737 
8738 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8739 			free(buf);
8740 			return NULL;
8741 		}
8742 		strcat(buf, " ");
8743 		strcat(buf, section_defs[i].sec);
8744 	}
8745 
8746 	return buf;
8747 }
8748 
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)8749 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8750 			     enum bpf_attach_type *expected_attach_type)
8751 {
8752 	const struct bpf_sec_def *sec_def;
8753 	char *type_names;
8754 
8755 	if (!name)
8756 		return libbpf_err(-EINVAL);
8757 
8758 	sec_def = find_sec_def(name);
8759 	if (sec_def) {
8760 		*prog_type = sec_def->prog_type;
8761 		*expected_attach_type = sec_def->expected_attach_type;
8762 		return 0;
8763 	}
8764 
8765 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8766 	type_names = libbpf_get_type_names(false);
8767 	if (type_names != NULL) {
8768 		pr_debug("supported section(type) names are:%s\n", type_names);
8769 		free(type_names);
8770 	}
8771 
8772 	return libbpf_err(-ESRCH);
8773 }
8774 
libbpf_bpf_attach_type_str(enum bpf_attach_type t)8775 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8776 {
8777 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8778 		return NULL;
8779 
8780 	return attach_type_name[t];
8781 }
8782 
libbpf_bpf_link_type_str(enum bpf_link_type t)8783 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8784 {
8785 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8786 		return NULL;
8787 
8788 	return link_type_name[t];
8789 }
8790 
libbpf_bpf_map_type_str(enum bpf_map_type t)8791 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8792 {
8793 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8794 		return NULL;
8795 
8796 	return map_type_name[t];
8797 }
8798 
libbpf_bpf_prog_type_str(enum bpf_prog_type t)8799 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8800 {
8801 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8802 		return NULL;
8803 
8804 	return prog_type_name[t];
8805 }
8806 
find_struct_ops_map_by_offset(struct bpf_object * obj,size_t offset)8807 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8808 						     size_t offset)
8809 {
8810 	struct bpf_map *map;
8811 	size_t i;
8812 
8813 	for (i = 0; i < obj->nr_maps; i++) {
8814 		map = &obj->maps[i];
8815 		if (!bpf_map__is_struct_ops(map))
8816 			continue;
8817 		if (map->sec_offset <= offset &&
8818 		    offset - map->sec_offset < map->def.value_size)
8819 			return map;
8820 	}
8821 
8822 	return NULL;
8823 }
8824 
8825 /* Collect the reloc from ELF and populate the st_ops->progs[] */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)8826 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8827 					    Elf64_Shdr *shdr, Elf_Data *data)
8828 {
8829 	const struct btf_member *member;
8830 	struct bpf_struct_ops *st_ops;
8831 	struct bpf_program *prog;
8832 	unsigned int shdr_idx;
8833 	const struct btf *btf;
8834 	struct bpf_map *map;
8835 	unsigned int moff, insn_idx;
8836 	const char *name;
8837 	__u32 member_idx;
8838 	Elf64_Sym *sym;
8839 	Elf64_Rel *rel;
8840 	int i, nrels;
8841 
8842 	btf = obj->btf;
8843 	nrels = shdr->sh_size / shdr->sh_entsize;
8844 	for (i = 0; i < nrels; i++) {
8845 		rel = elf_rel_by_idx(data, i);
8846 		if (!rel) {
8847 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8848 			return -LIBBPF_ERRNO__FORMAT;
8849 		}
8850 
8851 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8852 		if (!sym) {
8853 			pr_warn("struct_ops reloc: symbol %zx not found\n",
8854 				(size_t)ELF64_R_SYM(rel->r_info));
8855 			return -LIBBPF_ERRNO__FORMAT;
8856 		}
8857 
8858 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8859 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8860 		if (!map) {
8861 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8862 				(size_t)rel->r_offset);
8863 			return -EINVAL;
8864 		}
8865 
8866 		moff = rel->r_offset - map->sec_offset;
8867 		shdr_idx = sym->st_shndx;
8868 		st_ops = map->st_ops;
8869 		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",
8870 			 map->name,
8871 			 (long long)(rel->r_info >> 32),
8872 			 (long long)sym->st_value,
8873 			 shdr_idx, (size_t)rel->r_offset,
8874 			 map->sec_offset, sym->st_name, name);
8875 
8876 		if (shdr_idx >= SHN_LORESERVE) {
8877 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8878 				map->name, (size_t)rel->r_offset, shdr_idx);
8879 			return -LIBBPF_ERRNO__RELOC;
8880 		}
8881 		if (sym->st_value % BPF_INSN_SZ) {
8882 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8883 				map->name, (unsigned long long)sym->st_value);
8884 			return -LIBBPF_ERRNO__FORMAT;
8885 		}
8886 		insn_idx = sym->st_value / BPF_INSN_SZ;
8887 
8888 		member = find_member_by_offset(st_ops->type, moff * 8);
8889 		if (!member) {
8890 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8891 				map->name, moff);
8892 			return -EINVAL;
8893 		}
8894 		member_idx = member - btf_members(st_ops->type);
8895 		name = btf__name_by_offset(btf, member->name_off);
8896 
8897 		if (!resolve_func_ptr(btf, member->type, NULL)) {
8898 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8899 				map->name, name);
8900 			return -EINVAL;
8901 		}
8902 
8903 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8904 		if (!prog) {
8905 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8906 				map->name, shdr_idx, name);
8907 			return -EINVAL;
8908 		}
8909 
8910 		/* prevent the use of BPF prog with invalid type */
8911 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8912 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8913 				map->name, prog->name);
8914 			return -EINVAL;
8915 		}
8916 
8917 		/* if we haven't yet processed this BPF program, record proper
8918 		 * attach_btf_id and member_idx
8919 		 */
8920 		if (!prog->attach_btf_id) {
8921 			prog->attach_btf_id = st_ops->type_id;
8922 			prog->expected_attach_type = member_idx;
8923 		}
8924 
8925 		/* struct_ops BPF prog can be re-used between multiple
8926 		 * .struct_ops as long as it's the same struct_ops struct
8927 		 * definition and the same function pointer field
8928 		 */
8929 		if (prog->attach_btf_id != st_ops->type_id ||
8930 		    prog->expected_attach_type != member_idx) {
8931 			pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
8932 				map->name, prog->name, prog->sec_name, prog->type,
8933 				prog->attach_btf_id, prog->expected_attach_type, name);
8934 			return -EINVAL;
8935 		}
8936 
8937 		st_ops->progs[member_idx] = prog;
8938 	}
8939 
8940 	return 0;
8941 }
8942 
8943 #define BTF_TRACE_PREFIX "btf_trace_"
8944 #define BTF_LSM_PREFIX "bpf_lsm_"
8945 #define BTF_ITER_PREFIX "bpf_iter_"
8946 #define BTF_MAX_NAME_SIZE 128
8947 
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)8948 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8949 				const char **prefix, int *kind)
8950 {
8951 	switch (attach_type) {
8952 	case BPF_TRACE_RAW_TP:
8953 		*prefix = BTF_TRACE_PREFIX;
8954 		*kind = BTF_KIND_TYPEDEF;
8955 		break;
8956 	case BPF_LSM_MAC:
8957 	case BPF_LSM_CGROUP:
8958 		*prefix = BTF_LSM_PREFIX;
8959 		*kind = BTF_KIND_FUNC;
8960 		break;
8961 	case BPF_TRACE_ITER:
8962 		*prefix = BTF_ITER_PREFIX;
8963 		*kind = BTF_KIND_FUNC;
8964 		break;
8965 	default:
8966 		*prefix = "";
8967 		*kind = BTF_KIND_FUNC;
8968 	}
8969 }
8970 
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)8971 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8972 				   const char *name, __u32 kind)
8973 {
8974 	char btf_type_name[BTF_MAX_NAME_SIZE];
8975 	int ret;
8976 
8977 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
8978 		       "%s%s", prefix, name);
8979 	/* snprintf returns the number of characters written excluding the
8980 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8981 	 * indicates truncation.
8982 	 */
8983 	if (ret < 0 || ret >= sizeof(btf_type_name))
8984 		return -ENAMETOOLONG;
8985 	return btf__find_by_name_kind(btf, btf_type_name, kind);
8986 }
8987 
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)8988 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8989 				     enum bpf_attach_type attach_type)
8990 {
8991 	const char *prefix;
8992 	int kind;
8993 
8994 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8995 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
8996 }
8997 
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)8998 int libbpf_find_vmlinux_btf_id(const char *name,
8999 			       enum bpf_attach_type attach_type)
9000 {
9001 	struct btf *btf;
9002 	int err;
9003 
9004 	btf = btf__load_vmlinux_btf();
9005 	err = libbpf_get_error(btf);
9006 	if (err) {
9007 		pr_warn("vmlinux BTF is not found\n");
9008 		return libbpf_err(err);
9009 	}
9010 
9011 	err = find_attach_btf_id(btf, name, attach_type);
9012 	if (err <= 0)
9013 		pr_warn("%s is not found in vmlinux BTF\n", name);
9014 
9015 	btf__free(btf);
9016 	return libbpf_err(err);
9017 }
9018 
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd)9019 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9020 {
9021 	struct bpf_prog_info info;
9022 	__u32 info_len = sizeof(info);
9023 	struct btf *btf;
9024 	int err;
9025 
9026 	memset(&info, 0, info_len);
9027 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9028 	if (err) {
9029 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9030 			attach_prog_fd, err);
9031 		return err;
9032 	}
9033 
9034 	err = -EINVAL;
9035 	if (!info.btf_id) {
9036 		pr_warn("The target program doesn't have BTF\n");
9037 		goto out;
9038 	}
9039 	btf = btf__load_from_kernel_by_id(info.btf_id);
9040 	err = libbpf_get_error(btf);
9041 	if (err) {
9042 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9043 		goto out;
9044 	}
9045 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9046 	btf__free(btf);
9047 	if (err <= 0) {
9048 		pr_warn("%s is not found in prog's BTF\n", name);
9049 		goto out;
9050 	}
9051 out:
9052 	return err;
9053 }
9054 
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)9055 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9056 			      enum bpf_attach_type attach_type,
9057 			      int *btf_obj_fd, int *btf_type_id)
9058 {
9059 	int ret, i;
9060 
9061 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9062 	if (ret > 0) {
9063 		*btf_obj_fd = 0; /* vmlinux BTF */
9064 		*btf_type_id = ret;
9065 		return 0;
9066 	}
9067 	if (ret != -ENOENT)
9068 		return ret;
9069 
9070 	ret = load_module_btfs(obj);
9071 	if (ret)
9072 		return ret;
9073 
9074 	for (i = 0; i < obj->btf_module_cnt; i++) {
9075 		const struct module_btf *mod = &obj->btf_modules[i];
9076 
9077 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9078 		if (ret > 0) {
9079 			*btf_obj_fd = mod->fd;
9080 			*btf_type_id = ret;
9081 			return 0;
9082 		}
9083 		if (ret == -ENOENT)
9084 			continue;
9085 
9086 		return ret;
9087 	}
9088 
9089 	return -ESRCH;
9090 }
9091 
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)9092 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9093 				     int *btf_obj_fd, int *btf_type_id)
9094 {
9095 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9096 	__u32 attach_prog_fd = prog->attach_prog_fd;
9097 	int err = 0;
9098 
9099 	/* BPF program's BTF ID */
9100 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9101 		if (!attach_prog_fd) {
9102 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9103 			return -EINVAL;
9104 		}
9105 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9106 		if (err < 0) {
9107 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9108 				 prog->name, attach_prog_fd, attach_name, err);
9109 			return err;
9110 		}
9111 		*btf_obj_fd = 0;
9112 		*btf_type_id = err;
9113 		return 0;
9114 	}
9115 
9116 	/* kernel/module BTF ID */
9117 	if (prog->obj->gen_loader) {
9118 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9119 		*btf_obj_fd = 0;
9120 		*btf_type_id = 1;
9121 	} else {
9122 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9123 	}
9124 	if (err) {
9125 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9126 			prog->name, attach_name, err);
9127 		return err;
9128 	}
9129 	return 0;
9130 }
9131 
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)9132 int libbpf_attach_type_by_name(const char *name,
9133 			       enum bpf_attach_type *attach_type)
9134 {
9135 	char *type_names;
9136 	const struct bpf_sec_def *sec_def;
9137 
9138 	if (!name)
9139 		return libbpf_err(-EINVAL);
9140 
9141 	sec_def = find_sec_def(name);
9142 	if (!sec_def) {
9143 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9144 		type_names = libbpf_get_type_names(true);
9145 		if (type_names != NULL) {
9146 			pr_debug("attachable section(type) names are:%s\n", type_names);
9147 			free(type_names);
9148 		}
9149 
9150 		return libbpf_err(-EINVAL);
9151 	}
9152 
9153 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9154 		return libbpf_err(-EINVAL);
9155 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9156 		return libbpf_err(-EINVAL);
9157 
9158 	*attach_type = sec_def->expected_attach_type;
9159 	return 0;
9160 }
9161 
bpf_map__fd(const struct bpf_map * map)9162 int bpf_map__fd(const struct bpf_map *map)
9163 {
9164 	return map ? map->fd : libbpf_err(-EINVAL);
9165 }
9166 
map_uses_real_name(const struct bpf_map * map)9167 static bool map_uses_real_name(const struct bpf_map *map)
9168 {
9169 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9170 	 * their user-visible name differs from kernel-visible name. Users see
9171 	 * such map's corresponding ELF section name as a map name.
9172 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9173 	 * maps to know which name has to be returned to the user.
9174 	 */
9175 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9176 		return true;
9177 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9178 		return true;
9179 	return false;
9180 }
9181 
bpf_map__name(const struct bpf_map * map)9182 const char *bpf_map__name(const struct bpf_map *map)
9183 {
9184 	if (!map)
9185 		return NULL;
9186 
9187 	if (map_uses_real_name(map))
9188 		return map->real_name;
9189 
9190 	return map->name;
9191 }
9192 
bpf_map__type(const struct bpf_map * map)9193 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9194 {
9195 	return map->def.type;
9196 }
9197 
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)9198 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9199 {
9200 	if (map->fd >= 0)
9201 		return libbpf_err(-EBUSY);
9202 	map->def.type = type;
9203 	return 0;
9204 }
9205 
bpf_map__map_flags(const struct bpf_map * map)9206 __u32 bpf_map__map_flags(const struct bpf_map *map)
9207 {
9208 	return map->def.map_flags;
9209 }
9210 
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)9211 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9212 {
9213 	if (map->fd >= 0)
9214 		return libbpf_err(-EBUSY);
9215 	map->def.map_flags = flags;
9216 	return 0;
9217 }
9218 
bpf_map__map_extra(const struct bpf_map * map)9219 __u64 bpf_map__map_extra(const struct bpf_map *map)
9220 {
9221 	return map->map_extra;
9222 }
9223 
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)9224 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9225 {
9226 	if (map->fd >= 0)
9227 		return libbpf_err(-EBUSY);
9228 	map->map_extra = map_extra;
9229 	return 0;
9230 }
9231 
bpf_map__numa_node(const struct bpf_map * map)9232 __u32 bpf_map__numa_node(const struct bpf_map *map)
9233 {
9234 	return map->numa_node;
9235 }
9236 
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)9237 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9238 {
9239 	if (map->fd >= 0)
9240 		return libbpf_err(-EBUSY);
9241 	map->numa_node = numa_node;
9242 	return 0;
9243 }
9244 
bpf_map__key_size(const struct bpf_map * map)9245 __u32 bpf_map__key_size(const struct bpf_map *map)
9246 {
9247 	return map->def.key_size;
9248 }
9249 
bpf_map__set_key_size(struct bpf_map * map,__u32 size)9250 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9251 {
9252 	if (map->fd >= 0)
9253 		return libbpf_err(-EBUSY);
9254 	map->def.key_size = size;
9255 	return 0;
9256 }
9257 
bpf_map__value_size(const struct bpf_map * map)9258 __u32 bpf_map__value_size(const struct bpf_map *map)
9259 {
9260 	return map->def.value_size;
9261 }
9262 
bpf_map__set_value_size(struct bpf_map * map,__u32 size)9263 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9264 {
9265 	if (map->fd >= 0)
9266 		return libbpf_err(-EBUSY);
9267 	map->def.value_size = size;
9268 	return 0;
9269 }
9270 
bpf_map__btf_key_type_id(const struct bpf_map * map)9271 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9272 {
9273 	return map ? map->btf_key_type_id : 0;
9274 }
9275 
bpf_map__btf_value_type_id(const struct bpf_map * map)9276 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9277 {
9278 	return map ? map->btf_value_type_id : 0;
9279 }
9280 
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)9281 int bpf_map__set_initial_value(struct bpf_map *map,
9282 			       const void *data, size_t size)
9283 {
9284 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9285 	    size != map->def.value_size || map->fd >= 0)
9286 		return libbpf_err(-EINVAL);
9287 
9288 	memcpy(map->mmaped, data, size);
9289 	return 0;
9290 }
9291 
bpf_map__initial_value(struct bpf_map * map,size_t * psize)9292 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9293 {
9294 	if (!map->mmaped)
9295 		return NULL;
9296 	*psize = map->def.value_size;
9297 	return map->mmaped;
9298 }
9299 
bpf_map__is_internal(const struct bpf_map * map)9300 bool bpf_map__is_internal(const struct bpf_map *map)
9301 {
9302 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9303 }
9304 
bpf_map__ifindex(const struct bpf_map * map)9305 __u32 bpf_map__ifindex(const struct bpf_map *map)
9306 {
9307 	return map->map_ifindex;
9308 }
9309 
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)9310 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9311 {
9312 	if (map->fd >= 0)
9313 		return libbpf_err(-EBUSY);
9314 	map->map_ifindex = ifindex;
9315 	return 0;
9316 }
9317 
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)9318 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9319 {
9320 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9321 		pr_warn("error: unsupported map type\n");
9322 		return libbpf_err(-EINVAL);
9323 	}
9324 	if (map->inner_map_fd != -1) {
9325 		pr_warn("error: inner_map_fd already specified\n");
9326 		return libbpf_err(-EINVAL);
9327 	}
9328 	if (map->inner_map) {
9329 		bpf_map__destroy(map->inner_map);
9330 		zfree(&map->inner_map);
9331 	}
9332 	map->inner_map_fd = fd;
9333 	return 0;
9334 }
9335 
9336 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)9337 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9338 {
9339 	ssize_t idx;
9340 	struct bpf_map *s, *e;
9341 
9342 	if (!obj || !obj->maps)
9343 		return errno = EINVAL, NULL;
9344 
9345 	s = obj->maps;
9346 	e = obj->maps + obj->nr_maps;
9347 
9348 	if ((m < s) || (m >= e)) {
9349 		pr_warn("error in %s: map handler doesn't belong to object\n",
9350 			 __func__);
9351 		return errno = EINVAL, NULL;
9352 	}
9353 
9354 	idx = (m - obj->maps) + i;
9355 	if (idx >= obj->nr_maps || idx < 0)
9356 		return NULL;
9357 	return &obj->maps[idx];
9358 }
9359 
9360 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)9361 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9362 {
9363 	if (prev == NULL)
9364 		return obj->maps;
9365 
9366 	return __bpf_map__iter(prev, obj, 1);
9367 }
9368 
9369 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)9370 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9371 {
9372 	if (next == NULL) {
9373 		if (!obj->nr_maps)
9374 			return NULL;
9375 		return obj->maps + obj->nr_maps - 1;
9376 	}
9377 
9378 	return __bpf_map__iter(next, obj, -1);
9379 }
9380 
9381 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)9382 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9383 {
9384 	struct bpf_map *pos;
9385 
9386 	bpf_object__for_each_map(pos, obj) {
9387 		/* if it's a special internal map name (which always starts
9388 		 * with dot) then check if that special name matches the
9389 		 * real map name (ELF section name)
9390 		 */
9391 		if (name[0] == '.') {
9392 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9393 				return pos;
9394 			continue;
9395 		}
9396 		/* otherwise map name has to be an exact match */
9397 		if (map_uses_real_name(pos)) {
9398 			if (strcmp(pos->real_name, name) == 0)
9399 				return pos;
9400 			continue;
9401 		}
9402 		if (strcmp(pos->name, name) == 0)
9403 			return pos;
9404 	}
9405 	return errno = ENOENT, NULL;
9406 }
9407 
9408 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)9409 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9410 {
9411 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9412 }
9413 
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)9414 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9415 			   size_t value_sz, bool check_value_sz)
9416 {
9417 	if (map->fd <= 0)
9418 		return -ENOENT;
9419 
9420 	if (map->def.key_size != key_sz) {
9421 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9422 			map->name, key_sz, map->def.key_size);
9423 		return -EINVAL;
9424 	}
9425 
9426 	if (!check_value_sz)
9427 		return 0;
9428 
9429 	switch (map->def.type) {
9430 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9431 	case BPF_MAP_TYPE_PERCPU_HASH:
9432 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9433 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9434 		int num_cpu = libbpf_num_possible_cpus();
9435 		size_t elem_sz = roundup(map->def.value_size, 8);
9436 
9437 		if (value_sz != num_cpu * elem_sz) {
9438 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9439 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9440 			return -EINVAL;
9441 		}
9442 		break;
9443 	}
9444 	default:
9445 		if (map->def.value_size != value_sz) {
9446 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9447 				map->name, value_sz, map->def.value_size);
9448 			return -EINVAL;
9449 		}
9450 		break;
9451 	}
9452 	return 0;
9453 }
9454 
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)9455 int bpf_map__lookup_elem(const struct bpf_map *map,
9456 			 const void *key, size_t key_sz,
9457 			 void *value, size_t value_sz, __u64 flags)
9458 {
9459 	int err;
9460 
9461 	err = validate_map_op(map, key_sz, value_sz, true);
9462 	if (err)
9463 		return libbpf_err(err);
9464 
9465 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9466 }
9467 
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)9468 int bpf_map__update_elem(const struct bpf_map *map,
9469 			 const void *key, size_t key_sz,
9470 			 const void *value, size_t value_sz, __u64 flags)
9471 {
9472 	int err;
9473 
9474 	err = validate_map_op(map, key_sz, value_sz, true);
9475 	if (err)
9476 		return libbpf_err(err);
9477 
9478 	return bpf_map_update_elem(map->fd, key, value, flags);
9479 }
9480 
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)9481 int bpf_map__delete_elem(const struct bpf_map *map,
9482 			 const void *key, size_t key_sz, __u64 flags)
9483 {
9484 	int err;
9485 
9486 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9487 	if (err)
9488 		return libbpf_err(err);
9489 
9490 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9491 }
9492 
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)9493 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9494 				    const void *key, size_t key_sz,
9495 				    void *value, size_t value_sz, __u64 flags)
9496 {
9497 	int err;
9498 
9499 	err = validate_map_op(map, key_sz, value_sz, true);
9500 	if (err)
9501 		return libbpf_err(err);
9502 
9503 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9504 }
9505 
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)9506 int bpf_map__get_next_key(const struct bpf_map *map,
9507 			  const void *cur_key, void *next_key, size_t key_sz)
9508 {
9509 	int err;
9510 
9511 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9512 	if (err)
9513 		return libbpf_err(err);
9514 
9515 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9516 }
9517 
libbpf_get_error(const void * ptr)9518 long libbpf_get_error(const void *ptr)
9519 {
9520 	if (!IS_ERR_OR_NULL(ptr))
9521 		return 0;
9522 
9523 	if (IS_ERR(ptr))
9524 		errno = -PTR_ERR(ptr);
9525 
9526 	/* If ptr == NULL, then errno should be already set by the failing
9527 	 * API, because libbpf never returns NULL on success and it now always
9528 	 * sets errno on error. So no extra errno handling for ptr == NULL
9529 	 * case.
9530 	 */
9531 	return -errno;
9532 }
9533 
9534 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)9535 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9536 {
9537 	int ret;
9538 
9539 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9540 	return libbpf_err_errno(ret);
9541 }
9542 
9543 /* Release "ownership" of underlying BPF resource (typically, BPF program
9544  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9545  * link, when destructed through bpf_link__destroy() call won't attempt to
9546  * detach/unregisted that BPF resource. This is useful in situations where,
9547  * say, attached BPF program has to outlive userspace program that attached it
9548  * in the system. Depending on type of BPF program, though, there might be
9549  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9550  * exit of userspace program doesn't trigger automatic detachment and clean up
9551  * inside the kernel.
9552  */
bpf_link__disconnect(struct bpf_link * link)9553 void bpf_link__disconnect(struct bpf_link *link)
9554 {
9555 	link->disconnected = true;
9556 }
9557 
bpf_link__destroy(struct bpf_link * link)9558 int bpf_link__destroy(struct bpf_link *link)
9559 {
9560 	int err = 0;
9561 
9562 	if (IS_ERR_OR_NULL(link))
9563 		return 0;
9564 
9565 	if (!link->disconnected && link->detach)
9566 		err = link->detach(link);
9567 	if (link->pin_path)
9568 		free(link->pin_path);
9569 	if (link->dealloc)
9570 		link->dealloc(link);
9571 	else
9572 		free(link);
9573 
9574 	return libbpf_err(err);
9575 }
9576 
bpf_link__fd(const struct bpf_link * link)9577 int bpf_link__fd(const struct bpf_link *link)
9578 {
9579 	return link->fd;
9580 }
9581 
bpf_link__pin_path(const struct bpf_link * link)9582 const char *bpf_link__pin_path(const struct bpf_link *link)
9583 {
9584 	return link->pin_path;
9585 }
9586 
bpf_link__detach_fd(struct bpf_link * link)9587 static int bpf_link__detach_fd(struct bpf_link *link)
9588 {
9589 	return libbpf_err_errno(close(link->fd));
9590 }
9591 
bpf_link__open(const char * path)9592 struct bpf_link *bpf_link__open(const char *path)
9593 {
9594 	struct bpf_link *link;
9595 	int fd;
9596 
9597 	fd = bpf_obj_get(path);
9598 	if (fd < 0) {
9599 		fd = -errno;
9600 		pr_warn("failed to open link at %s: %d\n", path, fd);
9601 		return libbpf_err_ptr(fd);
9602 	}
9603 
9604 	link = calloc(1, sizeof(*link));
9605 	if (!link) {
9606 		close(fd);
9607 		return libbpf_err_ptr(-ENOMEM);
9608 	}
9609 	link->detach = &bpf_link__detach_fd;
9610 	link->fd = fd;
9611 
9612 	link->pin_path = strdup(path);
9613 	if (!link->pin_path) {
9614 		bpf_link__destroy(link);
9615 		return libbpf_err_ptr(-ENOMEM);
9616 	}
9617 
9618 	return link;
9619 }
9620 
bpf_link__detach(struct bpf_link * link)9621 int bpf_link__detach(struct bpf_link *link)
9622 {
9623 	return bpf_link_detach(link->fd) ? -errno : 0;
9624 }
9625 
bpf_link__pin(struct bpf_link * link,const char * path)9626 int bpf_link__pin(struct bpf_link *link, const char *path)
9627 {
9628 	int err;
9629 
9630 	if (link->pin_path)
9631 		return libbpf_err(-EBUSY);
9632 	err = make_parent_dir(path);
9633 	if (err)
9634 		return libbpf_err(err);
9635 	err = check_path(path);
9636 	if (err)
9637 		return libbpf_err(err);
9638 
9639 	link->pin_path = strdup(path);
9640 	if (!link->pin_path)
9641 		return libbpf_err(-ENOMEM);
9642 
9643 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9644 		err = -errno;
9645 		zfree(&link->pin_path);
9646 		return libbpf_err(err);
9647 	}
9648 
9649 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9650 	return 0;
9651 }
9652 
bpf_link__unpin(struct bpf_link * link)9653 int bpf_link__unpin(struct bpf_link *link)
9654 {
9655 	int err;
9656 
9657 	if (!link->pin_path)
9658 		return libbpf_err(-EINVAL);
9659 
9660 	err = unlink(link->pin_path);
9661 	if (err != 0)
9662 		return -errno;
9663 
9664 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9665 	zfree(&link->pin_path);
9666 	return 0;
9667 }
9668 
9669 struct bpf_link_perf {
9670 	struct bpf_link link;
9671 	int perf_event_fd;
9672 	/* legacy kprobe support: keep track of probe identifier and type */
9673 	char *legacy_probe_name;
9674 	bool legacy_is_kprobe;
9675 	bool legacy_is_retprobe;
9676 };
9677 
9678 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9679 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9680 
bpf_link_perf_detach(struct bpf_link * link)9681 static int bpf_link_perf_detach(struct bpf_link *link)
9682 {
9683 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9684 	int err = 0;
9685 
9686 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9687 		err = -errno;
9688 
9689 	if (perf_link->perf_event_fd != link->fd)
9690 		close(perf_link->perf_event_fd);
9691 	close(link->fd);
9692 
9693 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9694 	if (perf_link->legacy_probe_name) {
9695 		if (perf_link->legacy_is_kprobe) {
9696 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9697 							 perf_link->legacy_is_retprobe);
9698 		} else {
9699 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9700 							 perf_link->legacy_is_retprobe);
9701 		}
9702 	}
9703 
9704 	return err;
9705 }
9706 
bpf_link_perf_dealloc(struct bpf_link * link)9707 static void bpf_link_perf_dealloc(struct bpf_link *link)
9708 {
9709 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9710 
9711 	free(perf_link->legacy_probe_name);
9712 	free(perf_link);
9713 }
9714 
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)9715 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9716 						     const struct bpf_perf_event_opts *opts)
9717 {
9718 	char errmsg[STRERR_BUFSIZE];
9719 	struct bpf_link_perf *link;
9720 	int prog_fd, link_fd = -1, err;
9721 
9722 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9723 		return libbpf_err_ptr(-EINVAL);
9724 
9725 	if (pfd < 0) {
9726 		pr_warn("prog '%s': invalid perf event FD %d\n",
9727 			prog->name, pfd);
9728 		return libbpf_err_ptr(-EINVAL);
9729 	}
9730 	prog_fd = bpf_program__fd(prog);
9731 	if (prog_fd < 0) {
9732 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9733 			prog->name);
9734 		return libbpf_err_ptr(-EINVAL);
9735 	}
9736 
9737 	link = calloc(1, sizeof(*link));
9738 	if (!link)
9739 		return libbpf_err_ptr(-ENOMEM);
9740 	link->link.detach = &bpf_link_perf_detach;
9741 	link->link.dealloc = &bpf_link_perf_dealloc;
9742 	link->perf_event_fd = pfd;
9743 
9744 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9745 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9746 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9747 
9748 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9749 		if (link_fd < 0) {
9750 			err = -errno;
9751 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9752 				prog->name, pfd,
9753 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9754 			goto err_out;
9755 		}
9756 		link->link.fd = link_fd;
9757 	} else {
9758 		if (OPTS_GET(opts, bpf_cookie, 0)) {
9759 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
9760 			err = -EOPNOTSUPP;
9761 			goto err_out;
9762 		}
9763 
9764 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9765 			err = -errno;
9766 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9767 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9768 			if (err == -EPROTO)
9769 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9770 					prog->name, pfd);
9771 			goto err_out;
9772 		}
9773 		link->link.fd = pfd;
9774 	}
9775 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9776 		err = -errno;
9777 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9778 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9779 		goto err_out;
9780 	}
9781 
9782 	return &link->link;
9783 err_out:
9784 	if (link_fd >= 0)
9785 		close(link_fd);
9786 	free(link);
9787 	return libbpf_err_ptr(err);
9788 }
9789 
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)9790 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9791 {
9792 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9793 }
9794 
9795 /*
9796  * this function is expected to parse integer in the range of [0, 2^31-1] from
9797  * given file using scanf format string fmt. If actual parsed value is
9798  * negative, the result might be indistinguishable from error
9799  */
parse_uint_from_file(const char * file,const char * fmt)9800 static int parse_uint_from_file(const char *file, const char *fmt)
9801 {
9802 	char buf[STRERR_BUFSIZE];
9803 	int err, ret;
9804 	FILE *f;
9805 
9806 	f = fopen(file, "r");
9807 	if (!f) {
9808 		err = -errno;
9809 		pr_debug("failed to open '%s': %s\n", file,
9810 			 libbpf_strerror_r(err, buf, sizeof(buf)));
9811 		return err;
9812 	}
9813 	err = fscanf(f, fmt, &ret);
9814 	if (err != 1) {
9815 		err = err == EOF ? -EIO : -errno;
9816 		pr_debug("failed to parse '%s': %s\n", file,
9817 			libbpf_strerror_r(err, buf, sizeof(buf)));
9818 		fclose(f);
9819 		return err;
9820 	}
9821 	fclose(f);
9822 	return ret;
9823 }
9824 
determine_kprobe_perf_type(void)9825 static int determine_kprobe_perf_type(void)
9826 {
9827 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
9828 
9829 	return parse_uint_from_file(file, "%d\n");
9830 }
9831 
determine_uprobe_perf_type(void)9832 static int determine_uprobe_perf_type(void)
9833 {
9834 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
9835 
9836 	return parse_uint_from_file(file, "%d\n");
9837 }
9838 
determine_kprobe_retprobe_bit(void)9839 static int determine_kprobe_retprobe_bit(void)
9840 {
9841 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9842 
9843 	return parse_uint_from_file(file, "config:%d\n");
9844 }
9845 
determine_uprobe_retprobe_bit(void)9846 static int determine_uprobe_retprobe_bit(void)
9847 {
9848 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9849 
9850 	return parse_uint_from_file(file, "config:%d\n");
9851 }
9852 
9853 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9854 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9855 
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)9856 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9857 				 uint64_t offset, int pid, size_t ref_ctr_off)
9858 {
9859 	const size_t attr_sz = sizeof(struct perf_event_attr);
9860 	struct perf_event_attr attr;
9861 	char errmsg[STRERR_BUFSIZE];
9862 	int type, pfd;
9863 
9864 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9865 		return -EINVAL;
9866 
9867 	memset(&attr, 0, attr_sz);
9868 
9869 	type = uprobe ? determine_uprobe_perf_type()
9870 		      : determine_kprobe_perf_type();
9871 	if (type < 0) {
9872 		pr_warn("failed to determine %s perf type: %s\n",
9873 			uprobe ? "uprobe" : "kprobe",
9874 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9875 		return type;
9876 	}
9877 	if (retprobe) {
9878 		int bit = uprobe ? determine_uprobe_retprobe_bit()
9879 				 : determine_kprobe_retprobe_bit();
9880 
9881 		if (bit < 0) {
9882 			pr_warn("failed to determine %s retprobe bit: %s\n",
9883 				uprobe ? "uprobe" : "kprobe",
9884 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9885 			return bit;
9886 		}
9887 		attr.config |= 1 << bit;
9888 	}
9889 	attr.size = attr_sz;
9890 	attr.type = type;
9891 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9892 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9893 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
9894 
9895 	/* pid filter is meaningful only for uprobes */
9896 	pfd = syscall(__NR_perf_event_open, &attr,
9897 		      pid < 0 ? -1 : pid /* pid */,
9898 		      pid == -1 ? 0 : -1 /* cpu */,
9899 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9900 	return pfd >= 0 ? pfd : -errno;
9901 }
9902 
append_to_file(const char * file,const char * fmt,...)9903 static int append_to_file(const char *file, const char *fmt, ...)
9904 {
9905 	int fd, n, err = 0;
9906 	va_list ap;
9907 
9908 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9909 	if (fd < 0)
9910 		return -errno;
9911 
9912 	va_start(ap, fmt);
9913 	n = vdprintf(fd, fmt, ap);
9914 	va_end(ap);
9915 
9916 	if (n < 0)
9917 		err = -errno;
9918 
9919 	close(fd);
9920 	return err;
9921 }
9922 
9923 #define DEBUGFS "/sys/kernel/debug/tracing"
9924 #define TRACEFS "/sys/kernel/tracing"
9925 
use_debugfs(void)9926 static bool use_debugfs(void)
9927 {
9928 	static int has_debugfs = -1;
9929 
9930 	if (has_debugfs < 0)
9931 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
9932 
9933 	return has_debugfs == 1;
9934 }
9935 
tracefs_path(void)9936 static const char *tracefs_path(void)
9937 {
9938 	return use_debugfs() ? DEBUGFS : TRACEFS;
9939 }
9940 
tracefs_kprobe_events(void)9941 static const char *tracefs_kprobe_events(void)
9942 {
9943 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
9944 }
9945 
tracefs_uprobe_events(void)9946 static const char *tracefs_uprobe_events(void)
9947 {
9948 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
9949 }
9950 
gen_kprobe_legacy_event_name(char * buf,size_t buf_sz,const char * kfunc_name,size_t offset)9951 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9952 					 const char *kfunc_name, size_t offset)
9953 {
9954 	static int index = 0;
9955 
9956 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
9957 		 __sync_fetch_and_add(&index, 1));
9958 }
9959 
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)9960 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9961 				   const char *kfunc_name, size_t offset)
9962 {
9963 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
9964 			      retprobe ? 'r' : 'p',
9965 			      retprobe ? "kretprobes" : "kprobes",
9966 			      probe_name, kfunc_name, offset);
9967 }
9968 
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)9969 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9970 {
9971 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
9972 			      retprobe ? "kretprobes" : "kprobes", probe_name);
9973 }
9974 
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)9975 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9976 {
9977 	char file[256];
9978 
9979 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
9980 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
9981 
9982 	return parse_uint_from_file(file, "%d\n");
9983 }
9984 
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)9985 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9986 					 const char *kfunc_name, size_t offset, int pid)
9987 {
9988 	const size_t attr_sz = sizeof(struct perf_event_attr);
9989 	struct perf_event_attr attr;
9990 	char errmsg[STRERR_BUFSIZE];
9991 	int type, pfd, err;
9992 
9993 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9994 	if (err < 0) {
9995 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9996 			kfunc_name, offset,
9997 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9998 		return err;
9999 	}
10000 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10001 	if (type < 0) {
10002 		err = type;
10003 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10004 			kfunc_name, offset,
10005 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10006 		goto err_clean_legacy;
10007 	}
10008 
10009 	memset(&attr, 0, attr_sz);
10010 	attr.size = attr_sz;
10011 	attr.config = type;
10012 	attr.type = PERF_TYPE_TRACEPOINT;
10013 
10014 	pfd = syscall(__NR_perf_event_open, &attr,
10015 		      pid < 0 ? -1 : pid, /* pid */
10016 		      pid == -1 ? 0 : -1, /* cpu */
10017 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10018 	if (pfd < 0) {
10019 		err = -errno;
10020 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10021 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10022 		goto err_clean_legacy;
10023 	}
10024 	return pfd;
10025 
10026 err_clean_legacy:
10027 	/* Clear the newly added legacy kprobe_event */
10028 	remove_kprobe_event_legacy(probe_name, retprobe);
10029 	return err;
10030 }
10031 
arch_specific_syscall_pfx(void)10032 static const char *arch_specific_syscall_pfx(void)
10033 {
10034 #if defined(__x86_64__)
10035 	return "x64";
10036 #elif defined(__i386__)
10037 	return "ia32";
10038 #elif defined(__s390x__)
10039 	return "s390x";
10040 #elif defined(__s390__)
10041 	return "s390";
10042 #elif defined(__arm__)
10043 	return "arm";
10044 #elif defined(__aarch64__)
10045 	return "arm64";
10046 #elif defined(__mips__)
10047 	return "mips";
10048 #elif defined(__riscv)
10049 	return "riscv";
10050 #elif defined(__powerpc__)
10051 	return "powerpc";
10052 #elif defined(__powerpc64__)
10053 	return "powerpc64";
10054 #else
10055 	return NULL;
10056 #endif
10057 }
10058 
probe_kern_syscall_wrapper(void)10059 static int probe_kern_syscall_wrapper(void)
10060 {
10061 	char syscall_name[64];
10062 	const char *ksys_pfx;
10063 
10064 	ksys_pfx = arch_specific_syscall_pfx();
10065 	if (!ksys_pfx)
10066 		return 0;
10067 
10068 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10069 
10070 	if (determine_kprobe_perf_type() >= 0) {
10071 		int pfd;
10072 
10073 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10074 		if (pfd >= 0)
10075 			close(pfd);
10076 
10077 		return pfd >= 0 ? 1 : 0;
10078 	} else { /* legacy mode */
10079 		char probe_name[128];
10080 
10081 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10082 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10083 			return 0;
10084 
10085 		(void)remove_kprobe_event_legacy(probe_name, false);
10086 		return 1;
10087 	}
10088 }
10089 
10090 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)10091 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10092 				const char *func_name,
10093 				const struct bpf_kprobe_opts *opts)
10094 {
10095 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10096 	char errmsg[STRERR_BUFSIZE];
10097 	char *legacy_probe = NULL;
10098 	struct bpf_link *link;
10099 	size_t offset;
10100 	bool retprobe, legacy;
10101 	int pfd, err;
10102 
10103 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10104 		return libbpf_err_ptr(-EINVAL);
10105 
10106 	retprobe = OPTS_GET(opts, retprobe, false);
10107 	offset = OPTS_GET(opts, offset, 0);
10108 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10109 
10110 	legacy = determine_kprobe_perf_type() < 0;
10111 	if (!legacy) {
10112 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10113 					    func_name, offset,
10114 					    -1 /* pid */, 0 /* ref_ctr_off */);
10115 	} else {
10116 		char probe_name[256];
10117 
10118 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10119 					     func_name, offset);
10120 
10121 		legacy_probe = strdup(probe_name);
10122 		if (!legacy_probe)
10123 			return libbpf_err_ptr(-ENOMEM);
10124 
10125 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10126 						    offset, -1 /* pid */);
10127 	}
10128 	if (pfd < 0) {
10129 		err = -errno;
10130 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10131 			prog->name, retprobe ? "kretprobe" : "kprobe",
10132 			func_name, offset,
10133 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10134 		goto err_out;
10135 	}
10136 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10137 	err = libbpf_get_error(link);
10138 	if (err) {
10139 		close(pfd);
10140 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10141 			prog->name, retprobe ? "kretprobe" : "kprobe",
10142 			func_name, offset,
10143 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10144 		goto err_clean_legacy;
10145 	}
10146 	if (legacy) {
10147 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10148 
10149 		perf_link->legacy_probe_name = legacy_probe;
10150 		perf_link->legacy_is_kprobe = true;
10151 		perf_link->legacy_is_retprobe = retprobe;
10152 	}
10153 
10154 	return link;
10155 
10156 err_clean_legacy:
10157 	if (legacy)
10158 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10159 err_out:
10160 	free(legacy_probe);
10161 	return libbpf_err_ptr(err);
10162 }
10163 
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)10164 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10165 					    bool retprobe,
10166 					    const char *func_name)
10167 {
10168 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10169 		.retprobe = retprobe,
10170 	);
10171 
10172 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10173 }
10174 
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)10175 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10176 					      const char *syscall_name,
10177 					      const struct bpf_ksyscall_opts *opts)
10178 {
10179 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10180 	char func_name[128];
10181 
10182 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10183 		return libbpf_err_ptr(-EINVAL);
10184 
10185 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10186 		/* arch_specific_syscall_pfx() should never return NULL here
10187 		 * because it is guarded by kernel_supports(). However, since
10188 		 * compiler does not know that we have an explicit conditional
10189 		 * as well.
10190 		 */
10191 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10192 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10193 	} else {
10194 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10195 	}
10196 
10197 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10198 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10199 
10200 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10201 }
10202 
10203 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)10204 static bool glob_match(const char *str, const char *pat)
10205 {
10206 	while (*str && *pat && *pat != '*') {
10207 		if (*pat == '?') {      /* Matches any single character */
10208 			str++;
10209 			pat++;
10210 			continue;
10211 		}
10212 		if (*str != *pat)
10213 			return false;
10214 		str++;
10215 		pat++;
10216 	}
10217 	/* Check wild card */
10218 	if (*pat == '*') {
10219 		while (*pat == '*')
10220 			pat++;
10221 		if (!*pat) /* Tail wild card matches all */
10222 			return true;
10223 		while (*str)
10224 			if (glob_match(str++, pat))
10225 				return true;
10226 	}
10227 	return !*str && !*pat;
10228 }
10229 
10230 struct kprobe_multi_resolve {
10231 	const char *pattern;
10232 	unsigned long *addrs;
10233 	size_t cap;
10234 	size_t cnt;
10235 };
10236 
10237 static int
resolve_kprobe_multi_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)10238 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10239 			const char *sym_name, void *ctx)
10240 {
10241 	struct kprobe_multi_resolve *res = ctx;
10242 	int err;
10243 
10244 	if (!glob_match(sym_name, res->pattern))
10245 		return 0;
10246 
10247 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10248 				res->cnt + 1);
10249 	if (err)
10250 		return err;
10251 
10252 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10253 	return 0;
10254 }
10255 
10256 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)10257 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10258 				      const char *pattern,
10259 				      const struct bpf_kprobe_multi_opts *opts)
10260 {
10261 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10262 	struct kprobe_multi_resolve res = {
10263 		.pattern = pattern,
10264 	};
10265 	struct bpf_link *link = NULL;
10266 	char errmsg[STRERR_BUFSIZE];
10267 	const unsigned long *addrs;
10268 	int err, link_fd, prog_fd;
10269 	const __u64 *cookies;
10270 	const char **syms;
10271 	bool retprobe;
10272 	size_t cnt;
10273 
10274 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10275 		return libbpf_err_ptr(-EINVAL);
10276 
10277 	syms    = OPTS_GET(opts, syms, false);
10278 	addrs   = OPTS_GET(opts, addrs, false);
10279 	cnt     = OPTS_GET(opts, cnt, false);
10280 	cookies = OPTS_GET(opts, cookies, false);
10281 
10282 	if (!pattern && !addrs && !syms)
10283 		return libbpf_err_ptr(-EINVAL);
10284 	if (pattern && (addrs || syms || cookies || cnt))
10285 		return libbpf_err_ptr(-EINVAL);
10286 	if (!pattern && !cnt)
10287 		return libbpf_err_ptr(-EINVAL);
10288 	if (addrs && syms)
10289 		return libbpf_err_ptr(-EINVAL);
10290 
10291 	if (pattern) {
10292 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10293 		if (err)
10294 			goto error;
10295 		if (!res.cnt) {
10296 			err = -ENOENT;
10297 			goto error;
10298 		}
10299 		addrs = res.addrs;
10300 		cnt = res.cnt;
10301 	}
10302 
10303 	retprobe = OPTS_GET(opts, retprobe, false);
10304 
10305 	lopts.kprobe_multi.syms = syms;
10306 	lopts.kprobe_multi.addrs = addrs;
10307 	lopts.kprobe_multi.cookies = cookies;
10308 	lopts.kprobe_multi.cnt = cnt;
10309 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10310 
10311 	link = calloc(1, sizeof(*link));
10312 	if (!link) {
10313 		err = -ENOMEM;
10314 		goto error;
10315 	}
10316 	link->detach = &bpf_link__detach_fd;
10317 
10318 	prog_fd = bpf_program__fd(prog);
10319 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10320 	if (link_fd < 0) {
10321 		err = -errno;
10322 		pr_warn("prog '%s': failed to attach: %s\n",
10323 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10324 		goto error;
10325 	}
10326 	link->fd = link_fd;
10327 	free(res.addrs);
10328 	return link;
10329 
10330 error:
10331 	free(link);
10332 	free(res.addrs);
10333 	return libbpf_err_ptr(err);
10334 }
10335 
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10336 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10337 {
10338 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10339 	unsigned long offset = 0;
10340 	const char *func_name;
10341 	char *func;
10342 	int n;
10343 
10344 	*link = NULL;
10345 
10346 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10347 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10348 		return 0;
10349 
10350 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10351 	if (opts.retprobe)
10352 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10353 	else
10354 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10355 
10356 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10357 	if (n < 1) {
10358 		pr_warn("kprobe name is invalid: %s\n", func_name);
10359 		return -EINVAL;
10360 	}
10361 	if (opts.retprobe && offset != 0) {
10362 		free(func);
10363 		pr_warn("kretprobes do not support offset specification\n");
10364 		return -EINVAL;
10365 	}
10366 
10367 	opts.offset = offset;
10368 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10369 	free(func);
10370 	return libbpf_get_error(*link);
10371 }
10372 
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10373 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10374 {
10375 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10376 	const char *syscall_name;
10377 
10378 	*link = NULL;
10379 
10380 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10381 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10382 		return 0;
10383 
10384 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10385 	if (opts.retprobe)
10386 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10387 	else
10388 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10389 
10390 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10391 	return *link ? 0 : -errno;
10392 }
10393 
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10394 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10395 {
10396 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10397 	const char *spec;
10398 	char *pattern;
10399 	int n;
10400 
10401 	*link = NULL;
10402 
10403 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10404 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10405 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10406 		return 0;
10407 
10408 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10409 	if (opts.retprobe)
10410 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10411 	else
10412 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10413 
10414 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10415 	if (n < 1) {
10416 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10417 		return -EINVAL;
10418 	}
10419 
10420 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10421 	free(pattern);
10422 	return libbpf_get_error(*link);
10423 }
10424 
gen_uprobe_legacy_event_name(char * buf,size_t buf_sz,const char * binary_path,uint64_t offset)10425 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10426 					 const char *binary_path, uint64_t offset)
10427 {
10428 	int i;
10429 
10430 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10431 
10432 	/* sanitize binary_path in the probe name */
10433 	for (i = 0; buf[i]; i++) {
10434 		if (!isalnum(buf[i]))
10435 			buf[i] = '_';
10436 	}
10437 }
10438 
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)10439 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10440 					  const char *binary_path, size_t offset)
10441 {
10442 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10443 			      retprobe ? 'r' : 'p',
10444 			      retprobe ? "uretprobes" : "uprobes",
10445 			      probe_name, binary_path, offset);
10446 }
10447 
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)10448 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10449 {
10450 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10451 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10452 }
10453 
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)10454 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10455 {
10456 	char file[512];
10457 
10458 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10459 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10460 
10461 	return parse_uint_from_file(file, "%d\n");
10462 }
10463 
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)10464 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10465 					 const char *binary_path, size_t offset, int pid)
10466 {
10467 	const size_t attr_sz = sizeof(struct perf_event_attr);
10468 	struct perf_event_attr attr;
10469 	int type, pfd, err;
10470 
10471 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10472 	if (err < 0) {
10473 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10474 			binary_path, (size_t)offset, err);
10475 		return err;
10476 	}
10477 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10478 	if (type < 0) {
10479 		err = type;
10480 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10481 			binary_path, offset, err);
10482 		goto err_clean_legacy;
10483 	}
10484 
10485 	memset(&attr, 0, attr_sz);
10486 	attr.size = attr_sz;
10487 	attr.config = type;
10488 	attr.type = PERF_TYPE_TRACEPOINT;
10489 
10490 	pfd = syscall(__NR_perf_event_open, &attr,
10491 		      pid < 0 ? -1 : pid, /* pid */
10492 		      pid == -1 ? 0 : -1, /* cpu */
10493 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10494 	if (pfd < 0) {
10495 		err = -errno;
10496 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10497 		goto err_clean_legacy;
10498 	}
10499 	return pfd;
10500 
10501 err_clean_legacy:
10502 	/* Clear the newly added legacy uprobe_event */
10503 	remove_uprobe_event_legacy(probe_name, retprobe);
10504 	return err;
10505 }
10506 
10507 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
elf_find_next_scn_by_type(Elf * elf,int sh_type,Elf_Scn * scn)10508 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10509 {
10510 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10511 		GElf_Shdr sh;
10512 
10513 		if (!gelf_getshdr(scn, &sh))
10514 			continue;
10515 		if (sh.sh_type == sh_type)
10516 			return scn;
10517 	}
10518 	return NULL;
10519 }
10520 
10521 /* Find offset of function name in object specified by path.  "name" matches
10522  * symbol name or name@@LIB for library functions.
10523  */
elf_find_func_offset(const char * binary_path,const char * name)10524 static long elf_find_func_offset(const char *binary_path, const char *name)
10525 {
10526 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10527 	bool is_shared_lib, is_name_qualified;
10528 	char errmsg[STRERR_BUFSIZE];
10529 	long ret = -ENOENT;
10530 	size_t name_len;
10531 	GElf_Ehdr ehdr;
10532 	Elf *elf;
10533 
10534 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10535 	if (fd < 0) {
10536 		ret = -errno;
10537 		pr_warn("failed to open %s: %s\n", binary_path,
10538 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10539 		return ret;
10540 	}
10541 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10542 	if (!elf) {
10543 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10544 		close(fd);
10545 		return -LIBBPF_ERRNO__FORMAT;
10546 	}
10547 	if (!gelf_getehdr(elf, &ehdr)) {
10548 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10549 		ret = -LIBBPF_ERRNO__FORMAT;
10550 		goto out;
10551 	}
10552 	/* for shared lib case, we do not need to calculate relative offset */
10553 	is_shared_lib = ehdr.e_type == ET_DYN;
10554 
10555 	name_len = strlen(name);
10556 	/* Does name specify "@@LIB"? */
10557 	is_name_qualified = strstr(name, "@@") != NULL;
10558 
10559 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
10560 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10561 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10562 	 * reported as a warning/error.
10563 	 */
10564 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10565 		size_t nr_syms, strtabidx, idx;
10566 		Elf_Data *symbols = NULL;
10567 		Elf_Scn *scn = NULL;
10568 		int last_bind = -1;
10569 		const char *sname;
10570 		GElf_Shdr sh;
10571 
10572 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10573 		if (!scn) {
10574 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10575 				 binary_path);
10576 			continue;
10577 		}
10578 		if (!gelf_getshdr(scn, &sh))
10579 			continue;
10580 		strtabidx = sh.sh_link;
10581 		symbols = elf_getdata(scn, 0);
10582 		if (!symbols) {
10583 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10584 				binary_path, elf_errmsg(-1));
10585 			ret = -LIBBPF_ERRNO__FORMAT;
10586 			goto out;
10587 		}
10588 		nr_syms = symbols->d_size / sh.sh_entsize;
10589 
10590 		for (idx = 0; idx < nr_syms; idx++) {
10591 			int curr_bind;
10592 			GElf_Sym sym;
10593 			Elf_Scn *sym_scn;
10594 			GElf_Shdr sym_sh;
10595 
10596 			if (!gelf_getsym(symbols, idx, &sym))
10597 				continue;
10598 
10599 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10600 				continue;
10601 
10602 			sname = elf_strptr(elf, strtabidx, sym.st_name);
10603 			if (!sname)
10604 				continue;
10605 
10606 			curr_bind = GELF_ST_BIND(sym.st_info);
10607 
10608 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
10609 			if (strncmp(sname, name, name_len) != 0)
10610 				continue;
10611 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
10612 			 * additional characters in sname should be of the form "@@LIB".
10613 			 */
10614 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10615 				continue;
10616 
10617 			if (ret >= 0) {
10618 				/* handle multiple matches */
10619 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10620 					/* Only accept one non-weak bind. */
10621 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10622 						sname, name, binary_path);
10623 					ret = -LIBBPF_ERRNO__FORMAT;
10624 					goto out;
10625 				} else if (curr_bind == STB_WEAK) {
10626 					/* already have a non-weak bind, and
10627 					 * this is a weak bind, so ignore.
10628 					 */
10629 					continue;
10630 				}
10631 			}
10632 
10633 			/* Transform symbol's virtual address (absolute for
10634 			 * binaries and relative for shared libs) into file
10635 			 * offset, which is what kernel is expecting for
10636 			 * uprobe/uretprobe attachment.
10637 			 * See Documentation/trace/uprobetracer.rst for more
10638 			 * details.
10639 			 * This is done by looking up symbol's containing
10640 			 * section's header and using it's virtual address
10641 			 * (sh_addr) and corresponding file offset (sh_offset)
10642 			 * to transform sym.st_value (virtual address) into
10643 			 * desired final file offset.
10644 			 */
10645 			sym_scn = elf_getscn(elf, sym.st_shndx);
10646 			if (!sym_scn)
10647 				continue;
10648 			if (!gelf_getshdr(sym_scn, &sym_sh))
10649 				continue;
10650 
10651 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10652 			last_bind = curr_bind;
10653 		}
10654 		if (ret > 0)
10655 			break;
10656 	}
10657 
10658 	if (ret > 0) {
10659 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10660 			 ret);
10661 	} else {
10662 		if (ret == 0) {
10663 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10664 				is_shared_lib ? "should not be 0 in a shared library" :
10665 						"try using shared library path instead");
10666 			ret = -ENOENT;
10667 		} else {
10668 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10669 		}
10670 	}
10671 out:
10672 	elf_end(elf);
10673 	close(fd);
10674 	return ret;
10675 }
10676 
arch_specific_lib_paths(void)10677 static const char *arch_specific_lib_paths(void)
10678 {
10679 	/*
10680 	 * Based on https://packages.debian.org/sid/libc6.
10681 	 *
10682 	 * Assume that the traced program is built for the same architecture
10683 	 * as libbpf, which should cover the vast majority of cases.
10684 	 */
10685 #if defined(__x86_64__)
10686 	return "/lib/x86_64-linux-gnu";
10687 #elif defined(__i386__)
10688 	return "/lib/i386-linux-gnu";
10689 #elif defined(__s390x__)
10690 	return "/lib/s390x-linux-gnu";
10691 #elif defined(__s390__)
10692 	return "/lib/s390-linux-gnu";
10693 #elif defined(__arm__) && defined(__SOFTFP__)
10694 	return "/lib/arm-linux-gnueabi";
10695 #elif defined(__arm__) && !defined(__SOFTFP__)
10696 	return "/lib/arm-linux-gnueabihf";
10697 #elif defined(__aarch64__)
10698 	return "/lib/aarch64-linux-gnu";
10699 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10700 	return "/lib/mips64el-linux-gnuabi64";
10701 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10702 	return "/lib/mipsel-linux-gnu";
10703 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10704 	return "/lib/powerpc64le-linux-gnu";
10705 #elif defined(__sparc__) && defined(__arch64__)
10706 	return "/lib/sparc64-linux-gnu";
10707 #elif defined(__riscv) && __riscv_xlen == 64
10708 	return "/lib/riscv64-linux-gnu";
10709 #else
10710 	return NULL;
10711 #endif
10712 }
10713 
10714 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)10715 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10716 {
10717 	const char *search_paths[3] = {};
10718 	int i, perm;
10719 
10720 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10721 		search_paths[0] = getenv("LD_LIBRARY_PATH");
10722 		search_paths[1] = "/usr/lib64:/usr/lib";
10723 		search_paths[2] = arch_specific_lib_paths();
10724 		perm = R_OK;
10725 	} else {
10726 		search_paths[0] = getenv("PATH");
10727 		search_paths[1] = "/usr/bin:/usr/sbin";
10728 		perm = R_OK | X_OK;
10729 	}
10730 
10731 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10732 		const char *s;
10733 
10734 		if (!search_paths[i])
10735 			continue;
10736 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10737 			char *next_path;
10738 			int seg_len;
10739 
10740 			if (s[0] == ':')
10741 				s++;
10742 			next_path = strchr(s, ':');
10743 			seg_len = next_path ? next_path - s : strlen(s);
10744 			if (!seg_len)
10745 				continue;
10746 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10747 			/* ensure it has required permissions */
10748 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
10749 				continue;
10750 			pr_debug("resolved '%s' to '%s'\n", file, result);
10751 			return 0;
10752 		}
10753 	}
10754 	return -ENOENT;
10755 }
10756 
10757 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)10758 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10759 				const char *binary_path, size_t func_offset,
10760 				const struct bpf_uprobe_opts *opts)
10761 {
10762 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10763 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10764 	char full_binary_path[PATH_MAX];
10765 	struct bpf_link *link;
10766 	size_t ref_ctr_off;
10767 	int pfd, err;
10768 	bool retprobe, legacy;
10769 	const char *func_name;
10770 
10771 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10772 		return libbpf_err_ptr(-EINVAL);
10773 
10774 	retprobe = OPTS_GET(opts, retprobe, false);
10775 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10776 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10777 
10778 	if (!binary_path)
10779 		return libbpf_err_ptr(-EINVAL);
10780 
10781 	if (!strchr(binary_path, '/')) {
10782 		err = resolve_full_path(binary_path, full_binary_path,
10783 					sizeof(full_binary_path));
10784 		if (err) {
10785 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10786 				prog->name, binary_path, err);
10787 			return libbpf_err_ptr(err);
10788 		}
10789 		binary_path = full_binary_path;
10790 	}
10791 	func_name = OPTS_GET(opts, func_name, NULL);
10792 	if (func_name) {
10793 		long sym_off;
10794 
10795 		sym_off = elf_find_func_offset(binary_path, func_name);
10796 		if (sym_off < 0)
10797 			return libbpf_err_ptr(sym_off);
10798 		func_offset += sym_off;
10799 	}
10800 
10801 	legacy = determine_uprobe_perf_type() < 0;
10802 	if (!legacy) {
10803 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10804 					    func_offset, pid, ref_ctr_off);
10805 	} else {
10806 		char probe_name[PATH_MAX + 64];
10807 
10808 		if (ref_ctr_off)
10809 			return libbpf_err_ptr(-EINVAL);
10810 
10811 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10812 					     binary_path, func_offset);
10813 
10814 		legacy_probe = strdup(probe_name);
10815 		if (!legacy_probe)
10816 			return libbpf_err_ptr(-ENOMEM);
10817 
10818 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10819 						    binary_path, func_offset, pid);
10820 	}
10821 	if (pfd < 0) {
10822 		err = -errno;
10823 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10824 			prog->name, retprobe ? "uretprobe" : "uprobe",
10825 			binary_path, func_offset,
10826 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10827 		goto err_out;
10828 	}
10829 
10830 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10831 	err = libbpf_get_error(link);
10832 	if (err) {
10833 		close(pfd);
10834 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10835 			prog->name, retprobe ? "uretprobe" : "uprobe",
10836 			binary_path, func_offset,
10837 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10838 		goto err_clean_legacy;
10839 	}
10840 	if (legacy) {
10841 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10842 
10843 		perf_link->legacy_probe_name = legacy_probe;
10844 		perf_link->legacy_is_kprobe = false;
10845 		perf_link->legacy_is_retprobe = retprobe;
10846 	}
10847 	return link;
10848 
10849 err_clean_legacy:
10850 	if (legacy)
10851 		remove_uprobe_event_legacy(legacy_probe, retprobe);
10852 err_out:
10853 	free(legacy_probe);
10854 	return libbpf_err_ptr(err);
10855 }
10856 
10857 /* Format of u[ret]probe section definition supporting auto-attach:
10858  * u[ret]probe/binary:function[+offset]
10859  *
10860  * binary can be an absolute/relative path or a filename; the latter is resolved to a
10861  * full binary path via bpf_program__attach_uprobe_opts.
10862  *
10863  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
10864  * specified (and auto-attach is not possible) or the above format is specified for
10865  * auto-attach.
10866  */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10867 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10868 {
10869 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
10870 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
10871 	int n, ret = -EINVAL;
10872 	long offset = 0;
10873 
10874 	*link = NULL;
10875 
10876 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
10877 		   &probe_type, &binary_path, &func_name, &offset);
10878 	switch (n) {
10879 	case 1:
10880 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
10881 		ret = 0;
10882 		break;
10883 	case 2:
10884 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
10885 			prog->name, prog->sec_name);
10886 		break;
10887 	case 3:
10888 	case 4:
10889 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
10890 				strcmp(probe_type, "uretprobe.s") == 0;
10891 		if (opts.retprobe && offset != 0) {
10892 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
10893 				prog->name);
10894 			break;
10895 		}
10896 		opts.func_name = func_name;
10897 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
10898 		ret = libbpf_get_error(*link);
10899 		break;
10900 	default:
10901 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
10902 			prog->sec_name);
10903 		break;
10904 	}
10905 	free(probe_type);
10906 	free(binary_path);
10907 	free(func_name);
10908 
10909 	return ret;
10910 }
10911 
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)10912 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
10913 					    bool retprobe, pid_t pid,
10914 					    const char *binary_path,
10915 					    size_t func_offset)
10916 {
10917 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10918 
10919 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10920 }
10921 
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)10922 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
10923 					  pid_t pid, const char *binary_path,
10924 					  const char *usdt_provider, const char *usdt_name,
10925 					  const struct bpf_usdt_opts *opts)
10926 {
10927 	char resolved_path[512];
10928 	struct bpf_object *obj = prog->obj;
10929 	struct bpf_link *link;
10930 	__u64 usdt_cookie;
10931 	int err;
10932 
10933 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10934 		return libbpf_err_ptr(-EINVAL);
10935 
10936 	if (bpf_program__fd(prog) < 0) {
10937 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10938 			prog->name);
10939 		return libbpf_err_ptr(-EINVAL);
10940 	}
10941 
10942 	if (!binary_path)
10943 		return libbpf_err_ptr(-EINVAL);
10944 
10945 	if (!strchr(binary_path, '/')) {
10946 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
10947 		if (err) {
10948 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10949 				prog->name, binary_path, err);
10950 			return libbpf_err_ptr(err);
10951 		}
10952 		binary_path = resolved_path;
10953 	}
10954 
10955 	/* USDT manager is instantiated lazily on first USDT attach. It will
10956 	 * be destroyed together with BPF object in bpf_object__close().
10957 	 */
10958 	if (IS_ERR(obj->usdt_man))
10959 		return libbpf_ptr(obj->usdt_man);
10960 	if (!obj->usdt_man) {
10961 		obj->usdt_man = usdt_manager_new(obj);
10962 		if (IS_ERR(obj->usdt_man))
10963 			return libbpf_ptr(obj->usdt_man);
10964 	}
10965 
10966 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
10967 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
10968 				        usdt_provider, usdt_name, usdt_cookie);
10969 	err = libbpf_get_error(link);
10970 	if (err)
10971 		return libbpf_err_ptr(err);
10972 	return link;
10973 }
10974 
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10975 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10976 {
10977 	char *path = NULL, *provider = NULL, *name = NULL;
10978 	const char *sec_name;
10979 	int n, err;
10980 
10981 	sec_name = bpf_program__section_name(prog);
10982 	if (strcmp(sec_name, "usdt") == 0) {
10983 		/* no auto-attach for just SEC("usdt") */
10984 		*link = NULL;
10985 		return 0;
10986 	}
10987 
10988 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
10989 	if (n != 3) {
10990 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
10991 			sec_name);
10992 		err = -EINVAL;
10993 	} else {
10994 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
10995 						 provider, name, NULL);
10996 		err = libbpf_get_error(*link);
10997 	}
10998 	free(path);
10999 	free(provider);
11000 	free(name);
11001 	return err;
11002 }
11003 
determine_tracepoint_id(const char * tp_category,const char * tp_name)11004 static int determine_tracepoint_id(const char *tp_category,
11005 				   const char *tp_name)
11006 {
11007 	char file[PATH_MAX];
11008 	int ret;
11009 
11010 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11011 		       tracefs_path(), tp_category, tp_name);
11012 	if (ret < 0)
11013 		return -errno;
11014 	if (ret >= sizeof(file)) {
11015 		pr_debug("tracepoint %s/%s path is too long\n",
11016 			 tp_category, tp_name);
11017 		return -E2BIG;
11018 	}
11019 	return parse_uint_from_file(file, "%d\n");
11020 }
11021 
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)11022 static int perf_event_open_tracepoint(const char *tp_category,
11023 				      const char *tp_name)
11024 {
11025 	const size_t attr_sz = sizeof(struct perf_event_attr);
11026 	struct perf_event_attr attr;
11027 	char errmsg[STRERR_BUFSIZE];
11028 	int tp_id, pfd, err;
11029 
11030 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11031 	if (tp_id < 0) {
11032 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11033 			tp_category, tp_name,
11034 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11035 		return tp_id;
11036 	}
11037 
11038 	memset(&attr, 0, attr_sz);
11039 	attr.type = PERF_TYPE_TRACEPOINT;
11040 	attr.size = attr_sz;
11041 	attr.config = tp_id;
11042 
11043 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11044 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11045 	if (pfd < 0) {
11046 		err = -errno;
11047 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11048 			tp_category, tp_name,
11049 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11050 		return err;
11051 	}
11052 	return pfd;
11053 }
11054 
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)11055 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11056 						     const char *tp_category,
11057 						     const char *tp_name,
11058 						     const struct bpf_tracepoint_opts *opts)
11059 {
11060 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11061 	char errmsg[STRERR_BUFSIZE];
11062 	struct bpf_link *link;
11063 	int pfd, err;
11064 
11065 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11066 		return libbpf_err_ptr(-EINVAL);
11067 
11068 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11069 
11070 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11071 	if (pfd < 0) {
11072 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11073 			prog->name, tp_category, tp_name,
11074 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11075 		return libbpf_err_ptr(pfd);
11076 	}
11077 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11078 	err = libbpf_get_error(link);
11079 	if (err) {
11080 		close(pfd);
11081 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11082 			prog->name, tp_category, tp_name,
11083 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11084 		return libbpf_err_ptr(err);
11085 	}
11086 	return link;
11087 }
11088 
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)11089 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11090 						const char *tp_category,
11091 						const char *tp_name)
11092 {
11093 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11094 }
11095 
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11096 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11097 {
11098 	char *sec_name, *tp_cat, *tp_name;
11099 
11100 	*link = NULL;
11101 
11102 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11103 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11104 		return 0;
11105 
11106 	sec_name = strdup(prog->sec_name);
11107 	if (!sec_name)
11108 		return -ENOMEM;
11109 
11110 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11111 	if (str_has_pfx(prog->sec_name, "tp/"))
11112 		tp_cat = sec_name + sizeof("tp/") - 1;
11113 	else
11114 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11115 	tp_name = strchr(tp_cat, '/');
11116 	if (!tp_name) {
11117 		free(sec_name);
11118 		return -EINVAL;
11119 	}
11120 	*tp_name = '\0';
11121 	tp_name++;
11122 
11123 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11124 	free(sec_name);
11125 	return libbpf_get_error(*link);
11126 }
11127 
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)11128 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11129 						    const char *tp_name)
11130 {
11131 	char errmsg[STRERR_BUFSIZE];
11132 	struct bpf_link *link;
11133 	int prog_fd, pfd;
11134 
11135 	prog_fd = bpf_program__fd(prog);
11136 	if (prog_fd < 0) {
11137 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11138 		return libbpf_err_ptr(-EINVAL);
11139 	}
11140 
11141 	link = calloc(1, sizeof(*link));
11142 	if (!link)
11143 		return libbpf_err_ptr(-ENOMEM);
11144 	link->detach = &bpf_link__detach_fd;
11145 
11146 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11147 	if (pfd < 0) {
11148 		pfd = -errno;
11149 		free(link);
11150 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11151 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11152 		return libbpf_err_ptr(pfd);
11153 	}
11154 	link->fd = pfd;
11155 	return link;
11156 }
11157 
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11158 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11159 {
11160 	static const char *const prefixes[] = {
11161 		"raw_tp",
11162 		"raw_tracepoint",
11163 		"raw_tp.w",
11164 		"raw_tracepoint.w",
11165 	};
11166 	size_t i;
11167 	const char *tp_name = NULL;
11168 
11169 	*link = NULL;
11170 
11171 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11172 		size_t pfx_len;
11173 
11174 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11175 			continue;
11176 
11177 		pfx_len = strlen(prefixes[i]);
11178 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11179 		if (prog->sec_name[pfx_len] == '\0')
11180 			return 0;
11181 
11182 		if (prog->sec_name[pfx_len] != '/')
11183 			continue;
11184 
11185 		tp_name = prog->sec_name + pfx_len + 1;
11186 		break;
11187 	}
11188 
11189 	if (!tp_name) {
11190 		pr_warn("prog '%s': invalid section name '%s'\n",
11191 			prog->name, prog->sec_name);
11192 		return -EINVAL;
11193 	}
11194 
11195 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11196 	return libbpf_get_error(*link);
11197 }
11198 
11199 /* 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)11200 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11201 						   const struct bpf_trace_opts *opts)
11202 {
11203 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11204 	char errmsg[STRERR_BUFSIZE];
11205 	struct bpf_link *link;
11206 	int prog_fd, pfd;
11207 
11208 	if (!OPTS_VALID(opts, bpf_trace_opts))
11209 		return libbpf_err_ptr(-EINVAL);
11210 
11211 	prog_fd = bpf_program__fd(prog);
11212 	if (prog_fd < 0) {
11213 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11214 		return libbpf_err_ptr(-EINVAL);
11215 	}
11216 
11217 	link = calloc(1, sizeof(*link));
11218 	if (!link)
11219 		return libbpf_err_ptr(-ENOMEM);
11220 	link->detach = &bpf_link__detach_fd;
11221 
11222 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11223 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11224 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11225 	if (pfd < 0) {
11226 		pfd = -errno;
11227 		free(link);
11228 		pr_warn("prog '%s': failed to attach: %s\n",
11229 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11230 		return libbpf_err_ptr(pfd);
11231 	}
11232 	link->fd = pfd;
11233 	return link;
11234 }
11235 
bpf_program__attach_trace(const struct bpf_program * prog)11236 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11237 {
11238 	return bpf_program__attach_btf_id(prog, NULL);
11239 }
11240 
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11241 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11242 						const struct bpf_trace_opts *opts)
11243 {
11244 	return bpf_program__attach_btf_id(prog, opts);
11245 }
11246 
bpf_program__attach_lsm(const struct bpf_program * prog)11247 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11248 {
11249 	return bpf_program__attach_btf_id(prog, NULL);
11250 }
11251 
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11252 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11253 {
11254 	*link = bpf_program__attach_trace(prog);
11255 	return libbpf_get_error(*link);
11256 }
11257 
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11258 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11259 {
11260 	*link = bpf_program__attach_lsm(prog);
11261 	return libbpf_get_error(*link);
11262 }
11263 
11264 static struct bpf_link *
bpf_program__attach_fd(const struct bpf_program * prog,int target_fd,int btf_id,const char * target_name)11265 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11266 		       const char *target_name)
11267 {
11268 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11269 			    .target_btf_id = btf_id);
11270 	enum bpf_attach_type attach_type;
11271 	char errmsg[STRERR_BUFSIZE];
11272 	struct bpf_link *link;
11273 	int prog_fd, link_fd;
11274 
11275 	prog_fd = bpf_program__fd(prog);
11276 	if (prog_fd < 0) {
11277 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11278 		return libbpf_err_ptr(-EINVAL);
11279 	}
11280 
11281 	link = calloc(1, sizeof(*link));
11282 	if (!link)
11283 		return libbpf_err_ptr(-ENOMEM);
11284 	link->detach = &bpf_link__detach_fd;
11285 
11286 	attach_type = bpf_program__expected_attach_type(prog);
11287 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11288 	if (link_fd < 0) {
11289 		link_fd = -errno;
11290 		free(link);
11291 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11292 			prog->name, target_name,
11293 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11294 		return libbpf_err_ptr(link_fd);
11295 	}
11296 	link->fd = link_fd;
11297 	return link;
11298 }
11299 
11300 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)11301 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11302 {
11303 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11304 }
11305 
11306 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)11307 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11308 {
11309 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11310 }
11311 
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)11312 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11313 {
11314 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11315 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11316 }
11317 
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)11318 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11319 					      int target_fd,
11320 					      const char *attach_func_name)
11321 {
11322 	int btf_id;
11323 
11324 	if (!!target_fd != !!attach_func_name) {
11325 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11326 			prog->name);
11327 		return libbpf_err_ptr(-EINVAL);
11328 	}
11329 
11330 	if (prog->type != BPF_PROG_TYPE_EXT) {
11331 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11332 			prog->name);
11333 		return libbpf_err_ptr(-EINVAL);
11334 	}
11335 
11336 	if (target_fd) {
11337 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11338 		if (btf_id < 0)
11339 			return libbpf_err_ptr(btf_id);
11340 
11341 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11342 	} else {
11343 		/* no target, so use raw_tracepoint_open for compatibility
11344 		 * with old kernels
11345 		 */
11346 		return bpf_program__attach_trace(prog);
11347 	}
11348 }
11349 
11350 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)11351 bpf_program__attach_iter(const struct bpf_program *prog,
11352 			 const struct bpf_iter_attach_opts *opts)
11353 {
11354 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11355 	char errmsg[STRERR_BUFSIZE];
11356 	struct bpf_link *link;
11357 	int prog_fd, link_fd;
11358 	__u32 target_fd = 0;
11359 
11360 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11361 		return libbpf_err_ptr(-EINVAL);
11362 
11363 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11364 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11365 
11366 	prog_fd = bpf_program__fd(prog);
11367 	if (prog_fd < 0) {
11368 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11369 		return libbpf_err_ptr(-EINVAL);
11370 	}
11371 
11372 	link = calloc(1, sizeof(*link));
11373 	if (!link)
11374 		return libbpf_err_ptr(-ENOMEM);
11375 	link->detach = &bpf_link__detach_fd;
11376 
11377 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11378 				  &link_create_opts);
11379 	if (link_fd < 0) {
11380 		link_fd = -errno;
11381 		free(link);
11382 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11383 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11384 		return libbpf_err_ptr(link_fd);
11385 	}
11386 	link->fd = link_fd;
11387 	return link;
11388 }
11389 
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11390 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11391 {
11392 	*link = bpf_program__attach_iter(prog, NULL);
11393 	return libbpf_get_error(*link);
11394 }
11395 
bpf_program__attach(const struct bpf_program * prog)11396 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11397 {
11398 	struct bpf_link *link = NULL;
11399 	int err;
11400 
11401 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11402 		return libbpf_err_ptr(-EOPNOTSUPP);
11403 
11404 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11405 	if (err)
11406 		return libbpf_err_ptr(err);
11407 
11408 	/* When calling bpf_program__attach() explicitly, auto-attach support
11409 	 * is expected to work, so NULL returned link is considered an error.
11410 	 * This is different for skeleton's attach, see comment in
11411 	 * bpf_object__attach_skeleton().
11412 	 */
11413 	if (!link)
11414 		return libbpf_err_ptr(-EOPNOTSUPP);
11415 
11416 	return link;
11417 }
11418 
bpf_link__detach_struct_ops(struct bpf_link * link)11419 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11420 {
11421 	__u32 zero = 0;
11422 
11423 	if (bpf_map_delete_elem(link->fd, &zero))
11424 		return -errno;
11425 
11426 	return 0;
11427 }
11428 
bpf_map__attach_struct_ops(const struct bpf_map * map)11429 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11430 {
11431 	struct bpf_struct_ops *st_ops;
11432 	struct bpf_link *link;
11433 	__u32 i, zero = 0;
11434 	int err;
11435 
11436 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11437 		return libbpf_err_ptr(-EINVAL);
11438 
11439 	link = calloc(1, sizeof(*link));
11440 	if (!link)
11441 		return libbpf_err_ptr(-EINVAL);
11442 
11443 	st_ops = map->st_ops;
11444 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
11445 		struct bpf_program *prog = st_ops->progs[i];
11446 		void *kern_data;
11447 		int prog_fd;
11448 
11449 		if (!prog)
11450 			continue;
11451 
11452 		prog_fd = bpf_program__fd(prog);
11453 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11454 		*(unsigned long *)kern_data = prog_fd;
11455 	}
11456 
11457 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11458 	if (err) {
11459 		err = -errno;
11460 		free(link);
11461 		return libbpf_err_ptr(err);
11462 	}
11463 
11464 	link->detach = bpf_link__detach_struct_ops;
11465 	link->fd = map->fd;
11466 
11467 	return link;
11468 }
11469 
11470 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11471 							  void *private_data);
11472 
11473 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)11474 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11475 		       void **copy_mem, size_t *copy_size,
11476 		       bpf_perf_event_print_t fn, void *private_data)
11477 {
11478 	struct perf_event_mmap_page *header = mmap_mem;
11479 	__u64 data_head = ring_buffer_read_head(header);
11480 	__u64 data_tail = header->data_tail;
11481 	void *base = ((__u8 *)header) + page_size;
11482 	int ret = LIBBPF_PERF_EVENT_CONT;
11483 	struct perf_event_header *ehdr;
11484 	size_t ehdr_size;
11485 
11486 	while (data_head != data_tail) {
11487 		ehdr = base + (data_tail & (mmap_size - 1));
11488 		ehdr_size = ehdr->size;
11489 
11490 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11491 			void *copy_start = ehdr;
11492 			size_t len_first = base + mmap_size - copy_start;
11493 			size_t len_secnd = ehdr_size - len_first;
11494 
11495 			if (*copy_size < ehdr_size) {
11496 				free(*copy_mem);
11497 				*copy_mem = malloc(ehdr_size);
11498 				if (!*copy_mem) {
11499 					*copy_size = 0;
11500 					ret = LIBBPF_PERF_EVENT_ERROR;
11501 					break;
11502 				}
11503 				*copy_size = ehdr_size;
11504 			}
11505 
11506 			memcpy(*copy_mem, copy_start, len_first);
11507 			memcpy(*copy_mem + len_first, base, len_secnd);
11508 			ehdr = *copy_mem;
11509 		}
11510 
11511 		ret = fn(ehdr, private_data);
11512 		data_tail += ehdr_size;
11513 		if (ret != LIBBPF_PERF_EVENT_CONT)
11514 			break;
11515 	}
11516 
11517 	ring_buffer_write_tail(header, data_tail);
11518 	return libbpf_err(ret);
11519 }
11520 
11521 struct perf_buffer;
11522 
11523 struct perf_buffer_params {
11524 	struct perf_event_attr *attr;
11525 	/* if event_cb is specified, it takes precendence */
11526 	perf_buffer_event_fn event_cb;
11527 	/* sample_cb and lost_cb are higher-level common-case callbacks */
11528 	perf_buffer_sample_fn sample_cb;
11529 	perf_buffer_lost_fn lost_cb;
11530 	void *ctx;
11531 	int cpu_cnt;
11532 	int *cpus;
11533 	int *map_keys;
11534 };
11535 
11536 struct perf_cpu_buf {
11537 	struct perf_buffer *pb;
11538 	void *base; /* mmap()'ed memory */
11539 	void *buf; /* for reconstructing segmented data */
11540 	size_t buf_size;
11541 	int fd;
11542 	int cpu;
11543 	int map_key;
11544 };
11545 
11546 struct perf_buffer {
11547 	perf_buffer_event_fn event_cb;
11548 	perf_buffer_sample_fn sample_cb;
11549 	perf_buffer_lost_fn lost_cb;
11550 	void *ctx; /* passed into callbacks */
11551 
11552 	size_t page_size;
11553 	size_t mmap_size;
11554 	struct perf_cpu_buf **cpu_bufs;
11555 	struct epoll_event *events;
11556 	int cpu_cnt; /* number of allocated CPU buffers */
11557 	int epoll_fd; /* perf event FD */
11558 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11559 };
11560 
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)11561 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11562 				      struct perf_cpu_buf *cpu_buf)
11563 {
11564 	if (!cpu_buf)
11565 		return;
11566 	if (cpu_buf->base &&
11567 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11568 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11569 	if (cpu_buf->fd >= 0) {
11570 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11571 		close(cpu_buf->fd);
11572 	}
11573 	free(cpu_buf->buf);
11574 	free(cpu_buf);
11575 }
11576 
perf_buffer__free(struct perf_buffer * pb)11577 void perf_buffer__free(struct perf_buffer *pb)
11578 {
11579 	int i;
11580 
11581 	if (IS_ERR_OR_NULL(pb))
11582 		return;
11583 	if (pb->cpu_bufs) {
11584 		for (i = 0; i < pb->cpu_cnt; i++) {
11585 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11586 
11587 			if (!cpu_buf)
11588 				continue;
11589 
11590 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11591 			perf_buffer__free_cpu_buf(pb, cpu_buf);
11592 		}
11593 		free(pb->cpu_bufs);
11594 	}
11595 	if (pb->epoll_fd >= 0)
11596 		close(pb->epoll_fd);
11597 	free(pb->events);
11598 	free(pb);
11599 }
11600 
11601 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)11602 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11603 			  int cpu, int map_key)
11604 {
11605 	struct perf_cpu_buf *cpu_buf;
11606 	char msg[STRERR_BUFSIZE];
11607 	int err;
11608 
11609 	cpu_buf = calloc(1, sizeof(*cpu_buf));
11610 	if (!cpu_buf)
11611 		return ERR_PTR(-ENOMEM);
11612 
11613 	cpu_buf->pb = pb;
11614 	cpu_buf->cpu = cpu;
11615 	cpu_buf->map_key = map_key;
11616 
11617 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11618 			      -1, PERF_FLAG_FD_CLOEXEC);
11619 	if (cpu_buf->fd < 0) {
11620 		err = -errno;
11621 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11622 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11623 		goto error;
11624 	}
11625 
11626 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11627 			     PROT_READ | PROT_WRITE, MAP_SHARED,
11628 			     cpu_buf->fd, 0);
11629 	if (cpu_buf->base == MAP_FAILED) {
11630 		cpu_buf->base = NULL;
11631 		err = -errno;
11632 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11633 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11634 		goto error;
11635 	}
11636 
11637 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11638 		err = -errno;
11639 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11640 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11641 		goto error;
11642 	}
11643 
11644 	return cpu_buf;
11645 
11646 error:
11647 	perf_buffer__free_cpu_buf(pb, cpu_buf);
11648 	return (struct perf_cpu_buf *)ERR_PTR(err);
11649 }
11650 
11651 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11652 					      struct perf_buffer_params *p);
11653 
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)11654 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11655 				     perf_buffer_sample_fn sample_cb,
11656 				     perf_buffer_lost_fn lost_cb,
11657 				     void *ctx,
11658 				     const struct perf_buffer_opts *opts)
11659 {
11660 	const size_t attr_sz = sizeof(struct perf_event_attr);
11661 	struct perf_buffer_params p = {};
11662 	struct perf_event_attr attr;
11663 
11664 	if (!OPTS_VALID(opts, perf_buffer_opts))
11665 		return libbpf_err_ptr(-EINVAL);
11666 
11667 	memset(&attr, 0, attr_sz);
11668 	attr.size = attr_sz;
11669 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11670 	attr.type = PERF_TYPE_SOFTWARE;
11671 	attr.sample_type = PERF_SAMPLE_RAW;
11672 	attr.sample_period = 1;
11673 	attr.wakeup_events = 1;
11674 
11675 	p.attr = &attr;
11676 	p.sample_cb = sample_cb;
11677 	p.lost_cb = lost_cb;
11678 	p.ctx = ctx;
11679 
11680 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11681 }
11682 
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)11683 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11684 					 struct perf_event_attr *attr,
11685 					 perf_buffer_event_fn event_cb, void *ctx,
11686 					 const struct perf_buffer_raw_opts *opts)
11687 {
11688 	struct perf_buffer_params p = {};
11689 
11690 	if (!attr)
11691 		return libbpf_err_ptr(-EINVAL);
11692 
11693 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11694 		return libbpf_err_ptr(-EINVAL);
11695 
11696 	p.attr = attr;
11697 	p.event_cb = event_cb;
11698 	p.ctx = ctx;
11699 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11700 	p.cpus = OPTS_GET(opts, cpus, NULL);
11701 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
11702 
11703 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11704 }
11705 
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)11706 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11707 					      struct perf_buffer_params *p)
11708 {
11709 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
11710 	struct bpf_map_info map;
11711 	char msg[STRERR_BUFSIZE];
11712 	struct perf_buffer *pb;
11713 	bool *online = NULL;
11714 	__u32 map_info_len;
11715 	int err, i, j, n;
11716 
11717 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
11718 		pr_warn("page count should be power of two, but is %zu\n",
11719 			page_cnt);
11720 		return ERR_PTR(-EINVAL);
11721 	}
11722 
11723 	/* best-effort sanity checks */
11724 	memset(&map, 0, sizeof(map));
11725 	map_info_len = sizeof(map);
11726 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11727 	if (err) {
11728 		err = -errno;
11729 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11730 		 * -EBADFD, -EFAULT, or -E2BIG on real error
11731 		 */
11732 		if (err != -EINVAL) {
11733 			pr_warn("failed to get map info for map FD %d: %s\n",
11734 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11735 			return ERR_PTR(err);
11736 		}
11737 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11738 			 map_fd);
11739 	} else {
11740 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11741 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11742 				map.name);
11743 			return ERR_PTR(-EINVAL);
11744 		}
11745 	}
11746 
11747 	pb = calloc(1, sizeof(*pb));
11748 	if (!pb)
11749 		return ERR_PTR(-ENOMEM);
11750 
11751 	pb->event_cb = p->event_cb;
11752 	pb->sample_cb = p->sample_cb;
11753 	pb->lost_cb = p->lost_cb;
11754 	pb->ctx = p->ctx;
11755 
11756 	pb->page_size = getpagesize();
11757 	pb->mmap_size = pb->page_size * page_cnt;
11758 	pb->map_fd = map_fd;
11759 
11760 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11761 	if (pb->epoll_fd < 0) {
11762 		err = -errno;
11763 		pr_warn("failed to create epoll instance: %s\n",
11764 			libbpf_strerror_r(err, msg, sizeof(msg)));
11765 		goto error;
11766 	}
11767 
11768 	if (p->cpu_cnt > 0) {
11769 		pb->cpu_cnt = p->cpu_cnt;
11770 	} else {
11771 		pb->cpu_cnt = libbpf_num_possible_cpus();
11772 		if (pb->cpu_cnt < 0) {
11773 			err = pb->cpu_cnt;
11774 			goto error;
11775 		}
11776 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
11777 			pb->cpu_cnt = map.max_entries;
11778 	}
11779 
11780 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11781 	if (!pb->events) {
11782 		err = -ENOMEM;
11783 		pr_warn("failed to allocate events: out of memory\n");
11784 		goto error;
11785 	}
11786 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11787 	if (!pb->cpu_bufs) {
11788 		err = -ENOMEM;
11789 		pr_warn("failed to allocate buffers: out of memory\n");
11790 		goto error;
11791 	}
11792 
11793 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11794 	if (err) {
11795 		pr_warn("failed to get online CPU mask: %d\n", err);
11796 		goto error;
11797 	}
11798 
11799 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11800 		struct perf_cpu_buf *cpu_buf;
11801 		int cpu, map_key;
11802 
11803 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11804 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11805 
11806 		/* in case user didn't explicitly requested particular CPUs to
11807 		 * be attached to, skip offline/not present CPUs
11808 		 */
11809 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11810 			continue;
11811 
11812 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11813 		if (IS_ERR(cpu_buf)) {
11814 			err = PTR_ERR(cpu_buf);
11815 			goto error;
11816 		}
11817 
11818 		pb->cpu_bufs[j] = cpu_buf;
11819 
11820 		err = bpf_map_update_elem(pb->map_fd, &map_key,
11821 					  &cpu_buf->fd, 0);
11822 		if (err) {
11823 			err = -errno;
11824 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11825 				cpu, map_key, cpu_buf->fd,
11826 				libbpf_strerror_r(err, msg, sizeof(msg)));
11827 			goto error;
11828 		}
11829 
11830 		pb->events[j].events = EPOLLIN;
11831 		pb->events[j].data.ptr = cpu_buf;
11832 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11833 			      &pb->events[j]) < 0) {
11834 			err = -errno;
11835 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11836 				cpu, cpu_buf->fd,
11837 				libbpf_strerror_r(err, msg, sizeof(msg)));
11838 			goto error;
11839 		}
11840 		j++;
11841 	}
11842 	pb->cpu_cnt = j;
11843 	free(online);
11844 
11845 	return pb;
11846 
11847 error:
11848 	free(online);
11849 	if (pb)
11850 		perf_buffer__free(pb);
11851 	return ERR_PTR(err);
11852 }
11853 
11854 struct perf_sample_raw {
11855 	struct perf_event_header header;
11856 	uint32_t size;
11857 	char data[];
11858 };
11859 
11860 struct perf_sample_lost {
11861 	struct perf_event_header header;
11862 	uint64_t id;
11863 	uint64_t lost;
11864 	uint64_t sample_id;
11865 };
11866 
11867 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)11868 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11869 {
11870 	struct perf_cpu_buf *cpu_buf = ctx;
11871 	struct perf_buffer *pb = cpu_buf->pb;
11872 	void *data = e;
11873 
11874 	/* user wants full control over parsing perf event */
11875 	if (pb->event_cb)
11876 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11877 
11878 	switch (e->type) {
11879 	case PERF_RECORD_SAMPLE: {
11880 		struct perf_sample_raw *s = data;
11881 
11882 		if (pb->sample_cb)
11883 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11884 		break;
11885 	}
11886 	case PERF_RECORD_LOST: {
11887 		struct perf_sample_lost *s = data;
11888 
11889 		if (pb->lost_cb)
11890 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11891 		break;
11892 	}
11893 	default:
11894 		pr_warn("unknown perf sample type %d\n", e->type);
11895 		return LIBBPF_PERF_EVENT_ERROR;
11896 	}
11897 	return LIBBPF_PERF_EVENT_CONT;
11898 }
11899 
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)11900 static int perf_buffer__process_records(struct perf_buffer *pb,
11901 					struct perf_cpu_buf *cpu_buf)
11902 {
11903 	enum bpf_perf_event_ret ret;
11904 
11905 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11906 				     pb->page_size, &cpu_buf->buf,
11907 				     &cpu_buf->buf_size,
11908 				     perf_buffer__process_record, cpu_buf);
11909 	if (ret != LIBBPF_PERF_EVENT_CONT)
11910 		return ret;
11911 	return 0;
11912 }
11913 
perf_buffer__epoll_fd(const struct perf_buffer * pb)11914 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11915 {
11916 	return pb->epoll_fd;
11917 }
11918 
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)11919 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11920 {
11921 	int i, cnt, err;
11922 
11923 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11924 	if (cnt < 0)
11925 		return -errno;
11926 
11927 	for (i = 0; i < cnt; i++) {
11928 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11929 
11930 		err = perf_buffer__process_records(pb, cpu_buf);
11931 		if (err) {
11932 			pr_warn("error while processing records: %d\n", err);
11933 			return libbpf_err(err);
11934 		}
11935 	}
11936 	return cnt;
11937 }
11938 
11939 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11940  * manager.
11941  */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)11942 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11943 {
11944 	return pb->cpu_cnt;
11945 }
11946 
11947 /*
11948  * Return perf_event FD of a ring buffer in *buf_idx* slot of
11949  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11950  * select()/poll()/epoll() Linux syscalls.
11951  */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)11952 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11953 {
11954 	struct perf_cpu_buf *cpu_buf;
11955 
11956 	if (buf_idx >= pb->cpu_cnt)
11957 		return libbpf_err(-EINVAL);
11958 
11959 	cpu_buf = pb->cpu_bufs[buf_idx];
11960 	if (!cpu_buf)
11961 		return libbpf_err(-ENOENT);
11962 
11963 	return cpu_buf->fd;
11964 }
11965 
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)11966 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
11967 {
11968 	struct perf_cpu_buf *cpu_buf;
11969 
11970 	if (buf_idx >= pb->cpu_cnt)
11971 		return libbpf_err(-EINVAL);
11972 
11973 	cpu_buf = pb->cpu_bufs[buf_idx];
11974 	if (!cpu_buf)
11975 		return libbpf_err(-ENOENT);
11976 
11977 	*buf = cpu_buf->base;
11978 	*buf_size = pb->mmap_size;
11979 	return 0;
11980 }
11981 
11982 /*
11983  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11984  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11985  * consume, do nothing and return success.
11986  * Returns:
11987  *   - 0 on success;
11988  *   - <0 on failure.
11989  */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)11990 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11991 {
11992 	struct perf_cpu_buf *cpu_buf;
11993 
11994 	if (buf_idx >= pb->cpu_cnt)
11995 		return libbpf_err(-EINVAL);
11996 
11997 	cpu_buf = pb->cpu_bufs[buf_idx];
11998 	if (!cpu_buf)
11999 		return libbpf_err(-ENOENT);
12000 
12001 	return perf_buffer__process_records(pb, cpu_buf);
12002 }
12003 
perf_buffer__consume(struct perf_buffer * pb)12004 int perf_buffer__consume(struct perf_buffer *pb)
12005 {
12006 	int i, err;
12007 
12008 	for (i = 0; i < pb->cpu_cnt; i++) {
12009 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12010 
12011 		if (!cpu_buf)
12012 			continue;
12013 
12014 		err = perf_buffer__process_records(pb, cpu_buf);
12015 		if (err) {
12016 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12017 			return libbpf_err(err);
12018 		}
12019 	}
12020 	return 0;
12021 }
12022 
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)12023 int bpf_program__set_attach_target(struct bpf_program *prog,
12024 				   int attach_prog_fd,
12025 				   const char *attach_func_name)
12026 {
12027 	int btf_obj_fd = 0, btf_id = 0, err;
12028 
12029 	if (!prog || attach_prog_fd < 0)
12030 		return libbpf_err(-EINVAL);
12031 
12032 	if (prog->obj->loaded)
12033 		return libbpf_err(-EINVAL);
12034 
12035 	if (attach_prog_fd && !attach_func_name) {
12036 		/* remember attach_prog_fd and let bpf_program__load() find
12037 		 * BTF ID during the program load
12038 		 */
12039 		prog->attach_prog_fd = attach_prog_fd;
12040 		return 0;
12041 	}
12042 
12043 	if (attach_prog_fd) {
12044 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12045 						 attach_prog_fd);
12046 		if (btf_id < 0)
12047 			return libbpf_err(btf_id);
12048 	} else {
12049 		if (!attach_func_name)
12050 			return libbpf_err(-EINVAL);
12051 
12052 		/* load btf_vmlinux, if not yet */
12053 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12054 		if (err)
12055 			return libbpf_err(err);
12056 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12057 					 prog->expected_attach_type,
12058 					 &btf_obj_fd, &btf_id);
12059 		if (err)
12060 			return libbpf_err(err);
12061 	}
12062 
12063 	prog->attach_btf_id = btf_id;
12064 	prog->attach_btf_obj_fd = btf_obj_fd;
12065 	prog->attach_prog_fd = attach_prog_fd;
12066 	return 0;
12067 }
12068 
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)12069 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12070 {
12071 	int err = 0, n, len, start, end = -1;
12072 	bool *tmp;
12073 
12074 	*mask = NULL;
12075 	*mask_sz = 0;
12076 
12077 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12078 	while (*s) {
12079 		if (*s == ',' || *s == '\n') {
12080 			s++;
12081 			continue;
12082 		}
12083 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12084 		if (n <= 0 || n > 2) {
12085 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12086 			err = -EINVAL;
12087 			goto cleanup;
12088 		} else if (n == 1) {
12089 			end = start;
12090 		}
12091 		if (start < 0 || start > end) {
12092 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12093 				start, end, s);
12094 			err = -EINVAL;
12095 			goto cleanup;
12096 		}
12097 		tmp = realloc(*mask, end + 1);
12098 		if (!tmp) {
12099 			err = -ENOMEM;
12100 			goto cleanup;
12101 		}
12102 		*mask = tmp;
12103 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12104 		memset(tmp + start, 1, end - start + 1);
12105 		*mask_sz = end + 1;
12106 		s += len;
12107 	}
12108 	if (!*mask_sz) {
12109 		pr_warn("Empty CPU range\n");
12110 		return -EINVAL;
12111 	}
12112 	return 0;
12113 cleanup:
12114 	free(*mask);
12115 	*mask = NULL;
12116 	return err;
12117 }
12118 
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)12119 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12120 {
12121 	int fd, err = 0, len;
12122 	char buf[128];
12123 
12124 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12125 	if (fd < 0) {
12126 		err = -errno;
12127 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12128 		return err;
12129 	}
12130 	len = read(fd, buf, sizeof(buf));
12131 	close(fd);
12132 	if (len <= 0) {
12133 		err = len ? -errno : -EINVAL;
12134 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12135 		return err;
12136 	}
12137 	if (len >= sizeof(buf)) {
12138 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12139 		return -E2BIG;
12140 	}
12141 	buf[len] = '\0';
12142 
12143 	return parse_cpu_mask_str(buf, mask, mask_sz);
12144 }
12145 
libbpf_num_possible_cpus(void)12146 int libbpf_num_possible_cpus(void)
12147 {
12148 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12149 	static int cpus;
12150 	int err, n, i, tmp_cpus;
12151 	bool *mask;
12152 
12153 	tmp_cpus = READ_ONCE(cpus);
12154 	if (tmp_cpus > 0)
12155 		return tmp_cpus;
12156 
12157 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12158 	if (err)
12159 		return libbpf_err(err);
12160 
12161 	tmp_cpus = 0;
12162 	for (i = 0; i < n; i++) {
12163 		if (mask[i])
12164 			tmp_cpus++;
12165 	}
12166 	free(mask);
12167 
12168 	WRITE_ONCE(cpus, tmp_cpus);
12169 	return tmp_cpus;
12170 }
12171 
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt)12172 static int populate_skeleton_maps(const struct bpf_object *obj,
12173 				  struct bpf_map_skeleton *maps,
12174 				  size_t map_cnt)
12175 {
12176 	int i;
12177 
12178 	for (i = 0; i < map_cnt; i++) {
12179 		struct bpf_map **map = maps[i].map;
12180 		const char *name = maps[i].name;
12181 		void **mmaped = maps[i].mmaped;
12182 
12183 		*map = bpf_object__find_map_by_name(obj, name);
12184 		if (!*map) {
12185 			pr_warn("failed to find skeleton map '%s'\n", name);
12186 			return -ESRCH;
12187 		}
12188 
12189 		/* externs shouldn't be pre-setup from user code */
12190 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12191 			*mmaped = (*map)->mmaped;
12192 	}
12193 	return 0;
12194 }
12195 
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt)12196 static int populate_skeleton_progs(const struct bpf_object *obj,
12197 				   struct bpf_prog_skeleton *progs,
12198 				   size_t prog_cnt)
12199 {
12200 	int i;
12201 
12202 	for (i = 0; i < prog_cnt; i++) {
12203 		struct bpf_program **prog = progs[i].prog;
12204 		const char *name = progs[i].name;
12205 
12206 		*prog = bpf_object__find_program_by_name(obj, name);
12207 		if (!*prog) {
12208 			pr_warn("failed to find skeleton program '%s'\n", name);
12209 			return -ESRCH;
12210 		}
12211 	}
12212 	return 0;
12213 }
12214 
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)12215 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12216 			      const struct bpf_object_open_opts *opts)
12217 {
12218 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12219 		.object_name = s->name,
12220 	);
12221 	struct bpf_object *obj;
12222 	int err;
12223 
12224 	/* Attempt to preserve opts->object_name, unless overriden by user
12225 	 * explicitly. Overwriting object name for skeletons is discouraged,
12226 	 * as it breaks global data maps, because they contain object name
12227 	 * prefix as their own map name prefix. When skeleton is generated,
12228 	 * bpftool is making an assumption that this name will stay the same.
12229 	 */
12230 	if (opts) {
12231 		memcpy(&skel_opts, opts, sizeof(*opts));
12232 		if (!opts->object_name)
12233 			skel_opts.object_name = s->name;
12234 	}
12235 
12236 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12237 	err = libbpf_get_error(obj);
12238 	if (err) {
12239 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12240 			s->name, err);
12241 		return libbpf_err(err);
12242 	}
12243 
12244 	*s->obj = obj;
12245 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12246 	if (err) {
12247 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12248 		return libbpf_err(err);
12249 	}
12250 
12251 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12252 	if (err) {
12253 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12254 		return libbpf_err(err);
12255 	}
12256 
12257 	return 0;
12258 }
12259 
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)12260 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12261 {
12262 	int err, len, var_idx, i;
12263 	const char *var_name;
12264 	const struct bpf_map *map;
12265 	struct btf *btf;
12266 	__u32 map_type_id;
12267 	const struct btf_type *map_type, *var_type;
12268 	const struct bpf_var_skeleton *var_skel;
12269 	struct btf_var_secinfo *var;
12270 
12271 	if (!s->obj)
12272 		return libbpf_err(-EINVAL);
12273 
12274 	btf = bpf_object__btf(s->obj);
12275 	if (!btf) {
12276 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12277 		        bpf_object__name(s->obj));
12278 		return libbpf_err(-errno);
12279 	}
12280 
12281 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12282 	if (err) {
12283 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12284 		return libbpf_err(err);
12285 	}
12286 
12287 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12288 	if (err) {
12289 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12290 		return libbpf_err(err);
12291 	}
12292 
12293 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12294 		var_skel = &s->vars[var_idx];
12295 		map = *var_skel->map;
12296 		map_type_id = bpf_map__btf_value_type_id(map);
12297 		map_type = btf__type_by_id(btf, map_type_id);
12298 
12299 		if (!btf_is_datasec(map_type)) {
12300 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12301 				bpf_map__name(map),
12302 				__btf_kind_str(btf_kind(map_type)));
12303 			return libbpf_err(-EINVAL);
12304 		}
12305 
12306 		len = btf_vlen(map_type);
12307 		var = btf_var_secinfos(map_type);
12308 		for (i = 0; i < len; i++, var++) {
12309 			var_type = btf__type_by_id(btf, var->type);
12310 			var_name = btf__name_by_offset(btf, var_type->name_off);
12311 			if (strcmp(var_name, var_skel->name) == 0) {
12312 				*var_skel->addr = map->mmaped + var->offset;
12313 				break;
12314 			}
12315 		}
12316 	}
12317 	return 0;
12318 }
12319 
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)12320 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12321 {
12322 	if (!s)
12323 		return;
12324 	free(s->maps);
12325 	free(s->progs);
12326 	free(s->vars);
12327 	free(s);
12328 }
12329 
bpf_object__load_skeleton(struct bpf_object_skeleton * s)12330 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12331 {
12332 	int i, err;
12333 
12334 	err = bpf_object__load(*s->obj);
12335 	if (err) {
12336 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12337 		return libbpf_err(err);
12338 	}
12339 
12340 	for (i = 0; i < s->map_cnt; i++) {
12341 		struct bpf_map *map = *s->maps[i].map;
12342 		size_t mmap_sz = bpf_map_mmap_sz(map);
12343 		int prot, map_fd = bpf_map__fd(map);
12344 		void **mmaped = s->maps[i].mmaped;
12345 
12346 		if (!mmaped)
12347 			continue;
12348 
12349 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12350 			*mmaped = NULL;
12351 			continue;
12352 		}
12353 
12354 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12355 			prot = PROT_READ;
12356 		else
12357 			prot = PROT_READ | PROT_WRITE;
12358 
12359 		/* Remap anonymous mmap()-ed "map initialization image" as
12360 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12361 		 * memory address. This will cause kernel to change process'
12362 		 * page table to point to a different piece of kernel memory,
12363 		 * but from userspace point of view memory address (and its
12364 		 * contents, being identical at this point) will stay the
12365 		 * same. This mapping will be released by bpf_object__close()
12366 		 * as per normal clean up procedure, so we don't need to worry
12367 		 * about it from skeleton's clean up perspective.
12368 		 */
12369 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
12370 				MAP_SHARED | MAP_FIXED, map_fd, 0);
12371 		if (*mmaped == MAP_FAILED) {
12372 			err = -errno;
12373 			*mmaped = NULL;
12374 			pr_warn("failed to re-mmap() map '%s': %d\n",
12375 				 bpf_map__name(map), err);
12376 			return libbpf_err(err);
12377 		}
12378 	}
12379 
12380 	return 0;
12381 }
12382 
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)12383 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12384 {
12385 	int i, err;
12386 
12387 	for (i = 0; i < s->prog_cnt; i++) {
12388 		struct bpf_program *prog = *s->progs[i].prog;
12389 		struct bpf_link **link = s->progs[i].link;
12390 
12391 		if (!prog->autoload || !prog->autoattach)
12392 			continue;
12393 
12394 		/* auto-attaching not supported for this program */
12395 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12396 			continue;
12397 
12398 		/* if user already set the link manually, don't attempt auto-attach */
12399 		if (*link)
12400 			continue;
12401 
12402 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12403 		if (err) {
12404 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12405 				bpf_program__name(prog), err);
12406 			return libbpf_err(err);
12407 		}
12408 
12409 		/* It's possible that for some SEC() definitions auto-attach
12410 		 * is supported in some cases (e.g., if definition completely
12411 		 * specifies target information), but is not in other cases.
12412 		 * SEC("uprobe") is one such case. If user specified target
12413 		 * binary and function name, such BPF program can be
12414 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12415 		 * attach to fail. It should just be skipped.
12416 		 * attach_fn signals such case with returning 0 (no error) and
12417 		 * setting link to NULL.
12418 		 */
12419 	}
12420 
12421 	return 0;
12422 }
12423 
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)12424 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12425 {
12426 	int i;
12427 
12428 	for (i = 0; i < s->prog_cnt; i++) {
12429 		struct bpf_link **link = s->progs[i].link;
12430 
12431 		bpf_link__destroy(*link);
12432 		*link = NULL;
12433 	}
12434 }
12435 
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)12436 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12437 {
12438 	if (!s)
12439 		return;
12440 
12441 	if (s->progs)
12442 		bpf_object__detach_skeleton(s);
12443 	if (s->obj)
12444 		bpf_object__close(*s->obj);
12445 	free(s->maps);
12446 	free(s->progs);
12447 	free(s);
12448 }
12449