xref: /linux/tools/lib/bpf/libbpf.c (revision 05a06be722896e51f65dbbb6a3610f85a8353d6b)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48 
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73 
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 	[BPF_STRUCT_OPS]		= "struct_ops",
120 };
121 
122 static const char * const link_type_name[] = {
123 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
124 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
125 	[BPF_LINK_TYPE_TRACING]			= "tracing",
126 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
127 	[BPF_LINK_TYPE_ITER]			= "iter",
128 	[BPF_LINK_TYPE_NETNS]			= "netns",
129 	[BPF_LINK_TYPE_XDP]			= "xdp",
130 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
131 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
132 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
133 };
134 
135 static const char * const map_type_name[] = {
136 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
137 	[BPF_MAP_TYPE_HASH]			= "hash",
138 	[BPF_MAP_TYPE_ARRAY]			= "array",
139 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
140 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
141 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
142 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
143 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
144 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
145 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
146 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
147 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
148 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
149 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
150 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
151 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
152 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
153 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
154 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
155 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
156 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
157 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
158 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
159 	[BPF_MAP_TYPE_QUEUE]			= "queue",
160 	[BPF_MAP_TYPE_STACK]			= "stack",
161 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
162 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
163 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
164 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
165 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
166 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
167 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
168 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
169 };
170 
171 static const char * const prog_type_name[] = {
172 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
173 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
174 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
175 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
176 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
177 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
178 	[BPF_PROG_TYPE_XDP]			= "xdp",
179 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
180 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
181 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
182 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
183 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
184 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
185 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
186 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
187 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
188 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
189 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
190 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
191 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
192 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
193 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
194 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
195 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
196 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
197 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
198 	[BPF_PROG_TYPE_TRACING]			= "tracing",
199 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
200 	[BPF_PROG_TYPE_EXT]			= "ext",
201 	[BPF_PROG_TYPE_LSM]			= "lsm",
202 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
203 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
204 };
205 
206 static int __base_pr(enum libbpf_print_level level, const char *format,
207 		     va_list args)
208 {
209 	if (level == LIBBPF_DEBUG)
210 		return 0;
211 
212 	return vfprintf(stderr, format, args);
213 }
214 
215 static libbpf_print_fn_t __libbpf_pr = __base_pr;
216 
217 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
218 {
219 	libbpf_print_fn_t old_print_fn;
220 
221 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
222 
223 	return old_print_fn;
224 }
225 
226 __printf(2, 3)
227 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
228 {
229 	va_list args;
230 	int old_errno;
231 	libbpf_print_fn_t print_fn;
232 
233 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
234 	if (!print_fn)
235 		return;
236 
237 	old_errno = errno;
238 
239 	va_start(args, format);
240 	__libbpf_pr(level, format, args);
241 	va_end(args);
242 
243 	errno = old_errno;
244 }
245 
246 static void pr_perm_msg(int err)
247 {
248 	struct rlimit limit;
249 	char buf[100];
250 
251 	if (err != -EPERM || geteuid() != 0)
252 		return;
253 
254 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
255 	if (err)
256 		return;
257 
258 	if (limit.rlim_cur == RLIM_INFINITY)
259 		return;
260 
261 	if (limit.rlim_cur < 1024)
262 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
263 	else if (limit.rlim_cur < 1024*1024)
264 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
265 	else
266 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
267 
268 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
269 		buf);
270 }
271 
272 #define STRERR_BUFSIZE  128
273 
274 /* Copied from tools/perf/util/util.h */
275 #ifndef zfree
276 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
277 #endif
278 
279 #ifndef zclose
280 # define zclose(fd) ({			\
281 	int ___err = 0;			\
282 	if ((fd) >= 0)			\
283 		___err = close((fd));	\
284 	fd = -1;			\
285 	___err; })
286 #endif
287 
288 static inline __u64 ptr_to_u64(const void *ptr)
289 {
290 	return (__u64) (unsigned long) ptr;
291 }
292 
293 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
294 {
295 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
296 	return 0;
297 }
298 
299 __u32 libbpf_major_version(void)
300 {
301 	return LIBBPF_MAJOR_VERSION;
302 }
303 
304 __u32 libbpf_minor_version(void)
305 {
306 	return LIBBPF_MINOR_VERSION;
307 }
308 
309 const char *libbpf_version_string(void)
310 {
311 #define __S(X) #X
312 #define _S(X) __S(X)
313 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
314 #undef _S
315 #undef __S
316 }
317 
318 enum reloc_type {
319 	RELO_LD64,
320 	RELO_CALL,
321 	RELO_DATA,
322 	RELO_EXTERN_LD64,
323 	RELO_EXTERN_CALL,
324 	RELO_SUBPROG_ADDR,
325 	RELO_CORE,
326 };
327 
328 struct reloc_desc {
329 	enum reloc_type type;
330 	int insn_idx;
331 	union {
332 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
333 		struct {
334 			int map_idx;
335 			int sym_off;
336 		};
337 	};
338 };
339 
340 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
341 enum sec_def_flags {
342 	SEC_NONE = 0,
343 	/* expected_attach_type is optional, if kernel doesn't support that */
344 	SEC_EXP_ATTACH_OPT = 1,
345 	/* legacy, only used by libbpf_get_type_names() and
346 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
347 	 * This used to be associated with cgroup (and few other) BPF programs
348 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
349 	 * meaningless nowadays, though.
350 	 */
351 	SEC_ATTACHABLE = 2,
352 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
353 	/* attachment target is specified through BTF ID in either kernel or
354 	 * other BPF program's BTF object
355 	 */
356 	SEC_ATTACH_BTF = 4,
357 	/* BPF program type allows sleeping/blocking in kernel */
358 	SEC_SLEEPABLE = 8,
359 	/* BPF program support non-linear XDP buffer */
360 	SEC_XDP_FRAGS = 16,
361 };
362 
363 struct bpf_sec_def {
364 	char *sec;
365 	enum bpf_prog_type prog_type;
366 	enum bpf_attach_type expected_attach_type;
367 	long cookie;
368 	int handler_id;
369 
370 	libbpf_prog_setup_fn_t prog_setup_fn;
371 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
372 	libbpf_prog_attach_fn_t prog_attach_fn;
373 };
374 
375 /*
376  * bpf_prog should be a better name but it has been used in
377  * linux/filter.h.
378  */
379 struct bpf_program {
380 	char *name;
381 	char *sec_name;
382 	size_t sec_idx;
383 	const struct bpf_sec_def *sec_def;
384 	/* this program's instruction offset (in number of instructions)
385 	 * within its containing ELF section
386 	 */
387 	size_t sec_insn_off;
388 	/* number of original instructions in ELF section belonging to this
389 	 * program, not taking into account subprogram instructions possible
390 	 * appended later during relocation
391 	 */
392 	size_t sec_insn_cnt;
393 	/* Offset (in number of instructions) of the start of instruction
394 	 * belonging to this BPF program  within its containing main BPF
395 	 * program. For the entry-point (main) BPF program, this is always
396 	 * zero. For a sub-program, this gets reset before each of main BPF
397 	 * programs are processed and relocated and is used to determined
398 	 * whether sub-program was already appended to the main program, and
399 	 * if yes, at which instruction offset.
400 	 */
401 	size_t sub_insn_off;
402 
403 	/* instructions that belong to BPF program; insns[0] is located at
404 	 * sec_insn_off instruction within its ELF section in ELF file, so
405 	 * when mapping ELF file instruction index to the local instruction,
406 	 * one needs to subtract sec_insn_off; and vice versa.
407 	 */
408 	struct bpf_insn *insns;
409 	/* actual number of instruction in this BPF program's image; for
410 	 * entry-point BPF programs this includes the size of main program
411 	 * itself plus all the used sub-programs, appended at the end
412 	 */
413 	size_t insns_cnt;
414 
415 	struct reloc_desc *reloc_desc;
416 	int nr_reloc;
417 
418 	/* BPF verifier log settings */
419 	char *log_buf;
420 	size_t log_size;
421 	__u32 log_level;
422 
423 	struct bpf_object *obj;
424 
425 	int fd;
426 	bool autoload;
427 	bool autoattach;
428 	bool mark_btf_static;
429 	enum bpf_prog_type type;
430 	enum bpf_attach_type expected_attach_type;
431 
432 	int prog_ifindex;
433 	__u32 attach_btf_obj_fd;
434 	__u32 attach_btf_id;
435 	__u32 attach_prog_fd;
436 
437 	void *func_info;
438 	__u32 func_info_rec_size;
439 	__u32 func_info_cnt;
440 
441 	void *line_info;
442 	__u32 line_info_rec_size;
443 	__u32 line_info_cnt;
444 	__u32 prog_flags;
445 };
446 
447 struct bpf_struct_ops {
448 	const char *tname;
449 	const struct btf_type *type;
450 	struct bpf_program **progs;
451 	__u32 *kern_func_off;
452 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
453 	void *data;
454 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
455 	 *      btf_vmlinux's format.
456 	 * struct bpf_struct_ops_tcp_congestion_ops {
457 	 *	[... some other kernel fields ...]
458 	 *	struct tcp_congestion_ops data;
459 	 * }
460 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
461 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
462 	 * from "data".
463 	 */
464 	void *kern_vdata;
465 	__u32 type_id;
466 };
467 
468 #define DATA_SEC ".data"
469 #define BSS_SEC ".bss"
470 #define RODATA_SEC ".rodata"
471 #define KCONFIG_SEC ".kconfig"
472 #define KSYMS_SEC ".ksyms"
473 #define STRUCT_OPS_SEC ".struct_ops"
474 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
475 
476 enum libbpf_map_type {
477 	LIBBPF_MAP_UNSPEC,
478 	LIBBPF_MAP_DATA,
479 	LIBBPF_MAP_BSS,
480 	LIBBPF_MAP_RODATA,
481 	LIBBPF_MAP_KCONFIG,
482 };
483 
484 struct bpf_map_def {
485 	unsigned int type;
486 	unsigned int key_size;
487 	unsigned int value_size;
488 	unsigned int max_entries;
489 	unsigned int map_flags;
490 };
491 
492 struct bpf_map {
493 	struct bpf_object *obj;
494 	char *name;
495 	/* real_name is defined for special internal maps (.rodata*,
496 	 * .data*, .bss, .kconfig) and preserves their original ELF section
497 	 * name. This is important to be able to find corresponding BTF
498 	 * DATASEC information.
499 	 */
500 	char *real_name;
501 	int fd;
502 	int sec_idx;
503 	size_t sec_offset;
504 	int map_ifindex;
505 	int inner_map_fd;
506 	struct bpf_map_def def;
507 	__u32 numa_node;
508 	__u32 btf_var_idx;
509 	__u32 btf_key_type_id;
510 	__u32 btf_value_type_id;
511 	__u32 btf_vmlinux_value_type_id;
512 	enum libbpf_map_type libbpf_type;
513 	void *mmaped;
514 	struct bpf_struct_ops *st_ops;
515 	struct bpf_map *inner_map;
516 	void **init_slots;
517 	int init_slots_sz;
518 	char *pin_path;
519 	bool pinned;
520 	bool reused;
521 	bool autocreate;
522 	__u64 map_extra;
523 };
524 
525 enum extern_type {
526 	EXT_UNKNOWN,
527 	EXT_KCFG,
528 	EXT_KSYM,
529 };
530 
531 enum kcfg_type {
532 	KCFG_UNKNOWN,
533 	KCFG_CHAR,
534 	KCFG_BOOL,
535 	KCFG_INT,
536 	KCFG_TRISTATE,
537 	KCFG_CHAR_ARR,
538 };
539 
540 struct extern_desc {
541 	enum extern_type type;
542 	int sym_idx;
543 	int btf_id;
544 	int sec_btf_id;
545 	const char *name;
546 	bool is_set;
547 	bool is_weak;
548 	union {
549 		struct {
550 			enum kcfg_type type;
551 			int sz;
552 			int align;
553 			int data_off;
554 			bool is_signed;
555 		} kcfg;
556 		struct {
557 			unsigned long long addr;
558 
559 			/* target btf_id of the corresponding kernel var. */
560 			int kernel_btf_obj_fd;
561 			int kernel_btf_id;
562 
563 			/* local btf_id of the ksym extern's type. */
564 			__u32 type_id;
565 			/* BTF fd index to be patched in for insn->off, this is
566 			 * 0 for vmlinux BTF, index in obj->fd_array for module
567 			 * BTF
568 			 */
569 			__s16 btf_fd_idx;
570 		} ksym;
571 	};
572 };
573 
574 struct module_btf {
575 	struct btf *btf;
576 	char *name;
577 	__u32 id;
578 	int fd;
579 	int fd_array_idx;
580 };
581 
582 enum sec_type {
583 	SEC_UNUSED = 0,
584 	SEC_RELO,
585 	SEC_BSS,
586 	SEC_DATA,
587 	SEC_RODATA,
588 };
589 
590 struct elf_sec_desc {
591 	enum sec_type sec_type;
592 	Elf64_Shdr *shdr;
593 	Elf_Data *data;
594 };
595 
596 struct elf_state {
597 	int fd;
598 	const void *obj_buf;
599 	size_t obj_buf_sz;
600 	Elf *elf;
601 	Elf64_Ehdr *ehdr;
602 	Elf_Data *symbols;
603 	Elf_Data *st_ops_data;
604 	Elf_Data *st_ops_link_data;
605 	size_t shstrndx; /* section index for section name strings */
606 	size_t strtabidx;
607 	struct elf_sec_desc *secs;
608 	size_t sec_cnt;
609 	int btf_maps_shndx;
610 	__u32 btf_maps_sec_btf_id;
611 	int text_shndx;
612 	int symbols_shndx;
613 	int st_ops_shndx;
614 	int st_ops_link_shndx;
615 };
616 
617 struct usdt_manager;
618 
619 struct bpf_object {
620 	char name[BPF_OBJ_NAME_LEN];
621 	char license[64];
622 	__u32 kern_version;
623 
624 	struct bpf_program *programs;
625 	size_t nr_programs;
626 	struct bpf_map *maps;
627 	size_t nr_maps;
628 	size_t maps_cap;
629 
630 	char *kconfig;
631 	struct extern_desc *externs;
632 	int nr_extern;
633 	int kconfig_map_idx;
634 
635 	bool loaded;
636 	bool has_subcalls;
637 	bool has_rodata;
638 
639 	struct bpf_gen *gen_loader;
640 
641 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
642 	struct elf_state efile;
643 
644 	struct btf *btf;
645 	struct btf_ext *btf_ext;
646 
647 	/* Parse and load BTF vmlinux if any of the programs in the object need
648 	 * it at load time.
649 	 */
650 	struct btf *btf_vmlinux;
651 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
652 	 * override for vmlinux BTF.
653 	 */
654 	char *btf_custom_path;
655 	/* vmlinux BTF override for CO-RE relocations */
656 	struct btf *btf_vmlinux_override;
657 	/* Lazily initialized kernel module BTFs */
658 	struct module_btf *btf_modules;
659 	bool btf_modules_loaded;
660 	size_t btf_module_cnt;
661 	size_t btf_module_cap;
662 
663 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
664 	char *log_buf;
665 	size_t log_size;
666 	__u32 log_level;
667 
668 	int *fd_array;
669 	size_t fd_array_cap;
670 	size_t fd_array_cnt;
671 
672 	struct usdt_manager *usdt_man;
673 
674 	char path[];
675 };
676 
677 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
678 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
679 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
680 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
681 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
682 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
683 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
684 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
685 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
686 
687 void bpf_program__unload(struct bpf_program *prog)
688 {
689 	if (!prog)
690 		return;
691 
692 	zclose(prog->fd);
693 
694 	zfree(&prog->func_info);
695 	zfree(&prog->line_info);
696 }
697 
698 static void bpf_program__exit(struct bpf_program *prog)
699 {
700 	if (!prog)
701 		return;
702 
703 	bpf_program__unload(prog);
704 	zfree(&prog->name);
705 	zfree(&prog->sec_name);
706 	zfree(&prog->insns);
707 	zfree(&prog->reloc_desc);
708 
709 	prog->nr_reloc = 0;
710 	prog->insns_cnt = 0;
711 	prog->sec_idx = -1;
712 }
713 
714 static bool insn_is_subprog_call(const struct bpf_insn *insn)
715 {
716 	return BPF_CLASS(insn->code) == BPF_JMP &&
717 	       BPF_OP(insn->code) == BPF_CALL &&
718 	       BPF_SRC(insn->code) == BPF_K &&
719 	       insn->src_reg == BPF_PSEUDO_CALL &&
720 	       insn->dst_reg == 0 &&
721 	       insn->off == 0;
722 }
723 
724 static bool is_call_insn(const struct bpf_insn *insn)
725 {
726 	return insn->code == (BPF_JMP | BPF_CALL);
727 }
728 
729 static bool insn_is_pseudo_func(struct bpf_insn *insn)
730 {
731 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
732 }
733 
734 static int
735 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
736 		      const char *name, size_t sec_idx, const char *sec_name,
737 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
738 {
739 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
740 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
741 			sec_name, name, sec_off, insn_data_sz);
742 		return -EINVAL;
743 	}
744 
745 	memset(prog, 0, sizeof(*prog));
746 	prog->obj = obj;
747 
748 	prog->sec_idx = sec_idx;
749 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
750 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
751 	/* insns_cnt can later be increased by appending used subprograms */
752 	prog->insns_cnt = prog->sec_insn_cnt;
753 
754 	prog->type = BPF_PROG_TYPE_UNSPEC;
755 	prog->fd = -1;
756 
757 	/* libbpf's convention for SEC("?abc...") is that it's just like
758 	 * SEC("abc...") but the corresponding bpf_program starts out with
759 	 * autoload set to false.
760 	 */
761 	if (sec_name[0] == '?') {
762 		prog->autoload = false;
763 		/* from now on forget there was ? in section name */
764 		sec_name++;
765 	} else {
766 		prog->autoload = true;
767 	}
768 
769 	prog->autoattach = true;
770 
771 	/* inherit object's log_level */
772 	prog->log_level = obj->log_level;
773 
774 	prog->sec_name = strdup(sec_name);
775 	if (!prog->sec_name)
776 		goto errout;
777 
778 	prog->name = strdup(name);
779 	if (!prog->name)
780 		goto errout;
781 
782 	prog->insns = malloc(insn_data_sz);
783 	if (!prog->insns)
784 		goto errout;
785 	memcpy(prog->insns, insn_data, insn_data_sz);
786 
787 	return 0;
788 errout:
789 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
790 	bpf_program__exit(prog);
791 	return -ENOMEM;
792 }
793 
794 static int
795 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
796 			 const char *sec_name, int sec_idx)
797 {
798 	Elf_Data *symbols = obj->efile.symbols;
799 	struct bpf_program *prog, *progs;
800 	void *data = sec_data->d_buf;
801 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
802 	int nr_progs, err, i;
803 	const char *name;
804 	Elf64_Sym *sym;
805 
806 	progs = obj->programs;
807 	nr_progs = obj->nr_programs;
808 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
809 
810 	for (i = 0; i < nr_syms; i++) {
811 		sym = elf_sym_by_idx(obj, i);
812 
813 		if (sym->st_shndx != sec_idx)
814 			continue;
815 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
816 			continue;
817 
818 		prog_sz = sym->st_size;
819 		sec_off = sym->st_value;
820 
821 		name = elf_sym_str(obj, sym->st_name);
822 		if (!name) {
823 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
824 				sec_name, sec_off);
825 			return -LIBBPF_ERRNO__FORMAT;
826 		}
827 
828 		if (sec_off + prog_sz > sec_sz) {
829 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
830 				sec_name, sec_off);
831 			return -LIBBPF_ERRNO__FORMAT;
832 		}
833 
834 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
835 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
836 			return -ENOTSUP;
837 		}
838 
839 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
840 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
841 
842 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
843 		if (!progs) {
844 			/*
845 			 * In this case the original obj->programs
846 			 * is still valid, so don't need special treat for
847 			 * bpf_close_object().
848 			 */
849 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
850 				sec_name, name);
851 			return -ENOMEM;
852 		}
853 		obj->programs = progs;
854 
855 		prog = &progs[nr_progs];
856 
857 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
858 					    sec_off, data + sec_off, prog_sz);
859 		if (err)
860 			return err;
861 
862 		/* if function is a global/weak symbol, but has restricted
863 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
864 		 * as static to enable more permissive BPF verification mode
865 		 * with more outside context available to BPF verifier
866 		 */
867 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
868 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
869 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
870 			prog->mark_btf_static = true;
871 
872 		nr_progs++;
873 		obj->nr_programs = nr_progs;
874 	}
875 
876 	return 0;
877 }
878 
879 static const struct btf_member *
880 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
881 {
882 	struct btf_member *m;
883 	int i;
884 
885 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
886 		if (btf_member_bit_offset(t, i) == bit_offset)
887 			return m;
888 	}
889 
890 	return NULL;
891 }
892 
893 static const struct btf_member *
894 find_member_by_name(const struct btf *btf, const struct btf_type *t,
895 		    const char *name)
896 {
897 	struct btf_member *m;
898 	int i;
899 
900 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
901 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
902 			return m;
903 	}
904 
905 	return NULL;
906 }
907 
908 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
909 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
910 				   const char *name, __u32 kind);
911 
912 static int
913 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
914 			   const struct btf_type **type, __u32 *type_id,
915 			   const struct btf_type **vtype, __u32 *vtype_id,
916 			   const struct btf_member **data_member)
917 {
918 	const struct btf_type *kern_type, *kern_vtype;
919 	const struct btf_member *kern_data_member;
920 	__s32 kern_vtype_id, kern_type_id;
921 	__u32 i;
922 
923 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
924 	if (kern_type_id < 0) {
925 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
926 			tname);
927 		return kern_type_id;
928 	}
929 	kern_type = btf__type_by_id(btf, kern_type_id);
930 
931 	/* Find the corresponding "map_value" type that will be used
932 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
933 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
934 	 * btf_vmlinux.
935 	 */
936 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
937 						tname, BTF_KIND_STRUCT);
938 	if (kern_vtype_id < 0) {
939 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
940 			STRUCT_OPS_VALUE_PREFIX, tname);
941 		return kern_vtype_id;
942 	}
943 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
944 
945 	/* Find "struct tcp_congestion_ops" from
946 	 * struct bpf_struct_ops_tcp_congestion_ops {
947 	 *	[ ... ]
948 	 *	struct tcp_congestion_ops data;
949 	 * }
950 	 */
951 	kern_data_member = btf_members(kern_vtype);
952 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
953 		if (kern_data_member->type == kern_type_id)
954 			break;
955 	}
956 	if (i == btf_vlen(kern_vtype)) {
957 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
958 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
959 		return -EINVAL;
960 	}
961 
962 	*type = kern_type;
963 	*type_id = kern_type_id;
964 	*vtype = kern_vtype;
965 	*vtype_id = kern_vtype_id;
966 	*data_member = kern_data_member;
967 
968 	return 0;
969 }
970 
971 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
972 {
973 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
974 }
975 
976 /* Init the map's fields that depend on kern_btf */
977 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
978 					 const struct btf *btf,
979 					 const struct btf *kern_btf)
980 {
981 	const struct btf_member *member, *kern_member, *kern_data_member;
982 	const struct btf_type *type, *kern_type, *kern_vtype;
983 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
984 	struct bpf_struct_ops *st_ops;
985 	void *data, *kern_data;
986 	const char *tname;
987 	int err;
988 
989 	st_ops = map->st_ops;
990 	type = st_ops->type;
991 	tname = st_ops->tname;
992 	err = find_struct_ops_kern_types(kern_btf, tname,
993 					 &kern_type, &kern_type_id,
994 					 &kern_vtype, &kern_vtype_id,
995 					 &kern_data_member);
996 	if (err)
997 		return err;
998 
999 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1000 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1001 
1002 	map->def.value_size = kern_vtype->size;
1003 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1004 
1005 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1006 	if (!st_ops->kern_vdata)
1007 		return -ENOMEM;
1008 
1009 	data = st_ops->data;
1010 	kern_data_off = kern_data_member->offset / 8;
1011 	kern_data = st_ops->kern_vdata + kern_data_off;
1012 
1013 	member = btf_members(type);
1014 	for (i = 0; i < btf_vlen(type); i++, member++) {
1015 		const struct btf_type *mtype, *kern_mtype;
1016 		__u32 mtype_id, kern_mtype_id;
1017 		void *mdata, *kern_mdata;
1018 		__s64 msize, kern_msize;
1019 		__u32 moff, kern_moff;
1020 		__u32 kern_member_idx;
1021 		const char *mname;
1022 
1023 		mname = btf__name_by_offset(btf, member->name_off);
1024 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1025 		if (!kern_member) {
1026 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1027 				map->name, mname);
1028 			return -ENOTSUP;
1029 		}
1030 
1031 		kern_member_idx = kern_member - btf_members(kern_type);
1032 		if (btf_member_bitfield_size(type, i) ||
1033 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1034 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1035 				map->name, mname);
1036 			return -ENOTSUP;
1037 		}
1038 
1039 		moff = member->offset / 8;
1040 		kern_moff = kern_member->offset / 8;
1041 
1042 		mdata = data + moff;
1043 		kern_mdata = kern_data + kern_moff;
1044 
1045 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1046 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1047 						    &kern_mtype_id);
1048 		if (BTF_INFO_KIND(mtype->info) !=
1049 		    BTF_INFO_KIND(kern_mtype->info)) {
1050 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1051 				map->name, mname, BTF_INFO_KIND(mtype->info),
1052 				BTF_INFO_KIND(kern_mtype->info));
1053 			return -ENOTSUP;
1054 		}
1055 
1056 		if (btf_is_ptr(mtype)) {
1057 			struct bpf_program *prog;
1058 
1059 			prog = st_ops->progs[i];
1060 			if (!prog)
1061 				continue;
1062 
1063 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1064 							    kern_mtype->type,
1065 							    &kern_mtype_id);
1066 
1067 			/* mtype->type must be a func_proto which was
1068 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1069 			 * so only check kern_mtype for func_proto here.
1070 			 */
1071 			if (!btf_is_func_proto(kern_mtype)) {
1072 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1073 					map->name, mname);
1074 				return -ENOTSUP;
1075 			}
1076 
1077 			prog->attach_btf_id = kern_type_id;
1078 			prog->expected_attach_type = kern_member_idx;
1079 
1080 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1081 
1082 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1083 				 map->name, mname, prog->name, moff,
1084 				 kern_moff);
1085 
1086 			continue;
1087 		}
1088 
1089 		msize = btf__resolve_size(btf, mtype_id);
1090 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1091 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1092 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1093 				map->name, mname, (ssize_t)msize,
1094 				(ssize_t)kern_msize);
1095 			return -ENOTSUP;
1096 		}
1097 
1098 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1099 			 map->name, mname, (unsigned int)msize,
1100 			 moff, kern_moff);
1101 		memcpy(kern_mdata, mdata, msize);
1102 	}
1103 
1104 	return 0;
1105 }
1106 
1107 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1108 {
1109 	struct bpf_map *map;
1110 	size_t i;
1111 	int err;
1112 
1113 	for (i = 0; i < obj->nr_maps; i++) {
1114 		map = &obj->maps[i];
1115 
1116 		if (!bpf_map__is_struct_ops(map))
1117 			continue;
1118 
1119 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1120 						    obj->btf_vmlinux);
1121 		if (err)
1122 			return err;
1123 	}
1124 
1125 	return 0;
1126 }
1127 
1128 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1129 				int shndx, Elf_Data *data, __u32 map_flags)
1130 {
1131 	const struct btf_type *type, *datasec;
1132 	const struct btf_var_secinfo *vsi;
1133 	struct bpf_struct_ops *st_ops;
1134 	const char *tname, *var_name;
1135 	__s32 type_id, datasec_id;
1136 	const struct btf *btf;
1137 	struct bpf_map *map;
1138 	__u32 i;
1139 
1140 	if (shndx == -1)
1141 		return 0;
1142 
1143 	btf = obj->btf;
1144 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1145 					    BTF_KIND_DATASEC);
1146 	if (datasec_id < 0) {
1147 		pr_warn("struct_ops init: DATASEC %s not found\n",
1148 			sec_name);
1149 		return -EINVAL;
1150 	}
1151 
1152 	datasec = btf__type_by_id(btf, datasec_id);
1153 	vsi = btf_var_secinfos(datasec);
1154 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1155 		type = btf__type_by_id(obj->btf, vsi->type);
1156 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1157 
1158 		type_id = btf__resolve_type(obj->btf, vsi->type);
1159 		if (type_id < 0) {
1160 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1161 				vsi->type, sec_name);
1162 			return -EINVAL;
1163 		}
1164 
1165 		type = btf__type_by_id(obj->btf, type_id);
1166 		tname = btf__name_by_offset(obj->btf, type->name_off);
1167 		if (!tname[0]) {
1168 			pr_warn("struct_ops init: anonymous type is not supported\n");
1169 			return -ENOTSUP;
1170 		}
1171 		if (!btf_is_struct(type)) {
1172 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1173 			return -EINVAL;
1174 		}
1175 
1176 		map = bpf_object__add_map(obj);
1177 		if (IS_ERR(map))
1178 			return PTR_ERR(map);
1179 
1180 		map->sec_idx = shndx;
1181 		map->sec_offset = vsi->offset;
1182 		map->name = strdup(var_name);
1183 		if (!map->name)
1184 			return -ENOMEM;
1185 
1186 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1187 		map->def.key_size = sizeof(int);
1188 		map->def.value_size = type->size;
1189 		map->def.max_entries = 1;
1190 		map->def.map_flags = map_flags;
1191 
1192 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1193 		if (!map->st_ops)
1194 			return -ENOMEM;
1195 		st_ops = map->st_ops;
1196 		st_ops->data = malloc(type->size);
1197 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1198 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1199 					       sizeof(*st_ops->kern_func_off));
1200 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1201 			return -ENOMEM;
1202 
1203 		if (vsi->offset + type->size > data->d_size) {
1204 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1205 				var_name, sec_name);
1206 			return -EINVAL;
1207 		}
1208 
1209 		memcpy(st_ops->data,
1210 		       data->d_buf + vsi->offset,
1211 		       type->size);
1212 		st_ops->tname = tname;
1213 		st_ops->type = type;
1214 		st_ops->type_id = type_id;
1215 
1216 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1217 			 tname, type_id, var_name, vsi->offset);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1224 {
1225 	int err;
1226 
1227 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1228 				   obj->efile.st_ops_data, 0);
1229 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1230 					  obj->efile.st_ops_link_shndx,
1231 					  obj->efile.st_ops_link_data,
1232 					  BPF_F_LINK);
1233 	return err;
1234 }
1235 
1236 static struct bpf_object *bpf_object__new(const char *path,
1237 					  const void *obj_buf,
1238 					  size_t obj_buf_sz,
1239 					  const char *obj_name)
1240 {
1241 	struct bpf_object *obj;
1242 	char *end;
1243 
1244 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1245 	if (!obj) {
1246 		pr_warn("alloc memory failed for %s\n", path);
1247 		return ERR_PTR(-ENOMEM);
1248 	}
1249 
1250 	strcpy(obj->path, path);
1251 	if (obj_name) {
1252 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1253 	} else {
1254 		/* Using basename() GNU version which doesn't modify arg. */
1255 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1256 		end = strchr(obj->name, '.');
1257 		if (end)
1258 			*end = 0;
1259 	}
1260 
1261 	obj->efile.fd = -1;
1262 	/*
1263 	 * Caller of this function should also call
1264 	 * bpf_object__elf_finish() after data collection to return
1265 	 * obj_buf to user. If not, we should duplicate the buffer to
1266 	 * avoid user freeing them before elf finish.
1267 	 */
1268 	obj->efile.obj_buf = obj_buf;
1269 	obj->efile.obj_buf_sz = obj_buf_sz;
1270 	obj->efile.btf_maps_shndx = -1;
1271 	obj->efile.st_ops_shndx = -1;
1272 	obj->efile.st_ops_link_shndx = -1;
1273 	obj->kconfig_map_idx = -1;
1274 
1275 	obj->kern_version = get_kernel_version();
1276 	obj->loaded = false;
1277 
1278 	return obj;
1279 }
1280 
1281 static void bpf_object__elf_finish(struct bpf_object *obj)
1282 {
1283 	if (!obj->efile.elf)
1284 		return;
1285 
1286 	elf_end(obj->efile.elf);
1287 	obj->efile.elf = NULL;
1288 	obj->efile.symbols = NULL;
1289 	obj->efile.st_ops_data = NULL;
1290 	obj->efile.st_ops_link_data = NULL;
1291 
1292 	zfree(&obj->efile.secs);
1293 	obj->efile.sec_cnt = 0;
1294 	zclose(obj->efile.fd);
1295 	obj->efile.obj_buf = NULL;
1296 	obj->efile.obj_buf_sz = 0;
1297 }
1298 
1299 static int bpf_object__elf_init(struct bpf_object *obj)
1300 {
1301 	Elf64_Ehdr *ehdr;
1302 	int err = 0;
1303 	Elf *elf;
1304 
1305 	if (obj->efile.elf) {
1306 		pr_warn("elf: init internal error\n");
1307 		return -LIBBPF_ERRNO__LIBELF;
1308 	}
1309 
1310 	if (obj->efile.obj_buf_sz > 0) {
1311 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1312 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1313 	} else {
1314 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1315 		if (obj->efile.fd < 0) {
1316 			char errmsg[STRERR_BUFSIZE], *cp;
1317 
1318 			err = -errno;
1319 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1320 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1321 			return err;
1322 		}
1323 
1324 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1325 	}
1326 
1327 	if (!elf) {
1328 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1329 		err = -LIBBPF_ERRNO__LIBELF;
1330 		goto errout;
1331 	}
1332 
1333 	obj->efile.elf = elf;
1334 
1335 	if (elf_kind(elf) != ELF_K_ELF) {
1336 		err = -LIBBPF_ERRNO__FORMAT;
1337 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1338 		goto errout;
1339 	}
1340 
1341 	if (gelf_getclass(elf) != ELFCLASS64) {
1342 		err = -LIBBPF_ERRNO__FORMAT;
1343 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1344 		goto errout;
1345 	}
1346 
1347 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1348 	if (!obj->efile.ehdr) {
1349 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1350 		err = -LIBBPF_ERRNO__FORMAT;
1351 		goto errout;
1352 	}
1353 
1354 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1355 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1356 			obj->path, elf_errmsg(-1));
1357 		err = -LIBBPF_ERRNO__FORMAT;
1358 		goto errout;
1359 	}
1360 
1361 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1362 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1363 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1364 			obj->path, elf_errmsg(-1));
1365 		err = -LIBBPF_ERRNO__FORMAT;
1366 		goto errout;
1367 	}
1368 
1369 	/* Old LLVM set e_machine to EM_NONE */
1370 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1371 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1372 		err = -LIBBPF_ERRNO__FORMAT;
1373 		goto errout;
1374 	}
1375 
1376 	return 0;
1377 errout:
1378 	bpf_object__elf_finish(obj);
1379 	return err;
1380 }
1381 
1382 static int bpf_object__check_endianness(struct bpf_object *obj)
1383 {
1384 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1385 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1386 		return 0;
1387 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1388 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1389 		return 0;
1390 #else
1391 # error "Unrecognized __BYTE_ORDER__"
1392 #endif
1393 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1394 	return -LIBBPF_ERRNO__ENDIAN;
1395 }
1396 
1397 static int
1398 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1399 {
1400 	if (!data) {
1401 		pr_warn("invalid license section in %s\n", obj->path);
1402 		return -LIBBPF_ERRNO__FORMAT;
1403 	}
1404 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1405 	 * go over allowed ELF data section buffer
1406 	 */
1407 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1408 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1409 	return 0;
1410 }
1411 
1412 static int
1413 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1414 {
1415 	__u32 kver;
1416 
1417 	if (!data || size != sizeof(kver)) {
1418 		pr_warn("invalid kver section in %s\n", obj->path);
1419 		return -LIBBPF_ERRNO__FORMAT;
1420 	}
1421 	memcpy(&kver, data, sizeof(kver));
1422 	obj->kern_version = kver;
1423 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1424 	return 0;
1425 }
1426 
1427 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1428 {
1429 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1430 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1431 		return true;
1432 	return false;
1433 }
1434 
1435 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1436 {
1437 	Elf_Data *data;
1438 	Elf_Scn *scn;
1439 
1440 	if (!name)
1441 		return -EINVAL;
1442 
1443 	scn = elf_sec_by_name(obj, name);
1444 	data = elf_sec_data(obj, scn);
1445 	if (data) {
1446 		*size = data->d_size;
1447 		return 0; /* found it */
1448 	}
1449 
1450 	return -ENOENT;
1451 }
1452 
1453 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1454 {
1455 	Elf_Data *symbols = obj->efile.symbols;
1456 	const char *sname;
1457 	size_t si;
1458 
1459 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1460 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1461 
1462 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1463 			continue;
1464 
1465 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1466 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1467 			continue;
1468 
1469 		sname = elf_sym_str(obj, sym->st_name);
1470 		if (!sname) {
1471 			pr_warn("failed to get sym name string for var %s\n", name);
1472 			return ERR_PTR(-EIO);
1473 		}
1474 		if (strcmp(name, sname) == 0)
1475 			return sym;
1476 	}
1477 
1478 	return ERR_PTR(-ENOENT);
1479 }
1480 
1481 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1482 {
1483 	struct bpf_map *map;
1484 	int err;
1485 
1486 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1487 				sizeof(*obj->maps), obj->nr_maps + 1);
1488 	if (err)
1489 		return ERR_PTR(err);
1490 
1491 	map = &obj->maps[obj->nr_maps++];
1492 	map->obj = obj;
1493 	map->fd = -1;
1494 	map->inner_map_fd = -1;
1495 	map->autocreate = true;
1496 
1497 	return map;
1498 }
1499 
1500 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1501 {
1502 	long page_sz = sysconf(_SC_PAGE_SIZE);
1503 	size_t map_sz;
1504 
1505 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1506 	map_sz = roundup(map_sz, page_sz);
1507 	return map_sz;
1508 }
1509 
1510 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1511 {
1512 	char map_name[BPF_OBJ_NAME_LEN], *p;
1513 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1514 
1515 	/* This is one of the more confusing parts of libbpf for various
1516 	 * reasons, some of which are historical. The original idea for naming
1517 	 * internal names was to include as much of BPF object name prefix as
1518 	 * possible, so that it can be distinguished from similar internal
1519 	 * maps of a different BPF object.
1520 	 * As an example, let's say we have bpf_object named 'my_object_name'
1521 	 * and internal map corresponding to '.rodata' ELF section. The final
1522 	 * map name advertised to user and to the kernel will be
1523 	 * 'my_objec.rodata', taking first 8 characters of object name and
1524 	 * entire 7 characters of '.rodata'.
1525 	 * Somewhat confusingly, if internal map ELF section name is shorter
1526 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1527 	 * for the suffix, even though we only have 4 actual characters, and
1528 	 * resulting map will be called 'my_objec.bss', not even using all 15
1529 	 * characters allowed by the kernel. Oh well, at least the truncated
1530 	 * object name is somewhat consistent in this case. But if the map
1531 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1532 	 * (8 chars) and thus will be left with only first 7 characters of the
1533 	 * object name ('my_obje'). Happy guessing, user, that the final map
1534 	 * name will be "my_obje.kconfig".
1535 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1536 	 * and .data.* data sections, it's possible that ELF section name is
1537 	 * longer than allowed 15 chars, so we now need to be careful to take
1538 	 * only up to 15 first characters of ELF name, taking no BPF object
1539 	 * name characters at all. So '.rodata.abracadabra' will result in
1540 	 * '.rodata.abracad' kernel and user-visible name.
1541 	 * We need to keep this convoluted logic intact for .data, .bss and
1542 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1543 	 * maps we use their ELF names as is, not prepending bpf_object name
1544 	 * in front. We still need to truncate them to 15 characters for the
1545 	 * kernel. Full name can be recovered for such maps by using DATASEC
1546 	 * BTF type associated with such map's value type, though.
1547 	 */
1548 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1549 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1550 
1551 	/* if there are two or more dots in map name, it's a custom dot map */
1552 	if (strchr(real_name + 1, '.') != NULL)
1553 		pfx_len = 0;
1554 	else
1555 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1556 
1557 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1558 		 sfx_len, real_name);
1559 
1560 	/* sanitise map name to characters allowed by kernel */
1561 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1562 		if (!isalnum(*p) && *p != '_' && *p != '.')
1563 			*p = '_';
1564 
1565 	return strdup(map_name);
1566 }
1567 
1568 static int
1569 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1570 
1571 /* Internal BPF map is mmap()'able only if at least one of corresponding
1572  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1573  * variable and it's not marked as __hidden (which turns it into, effectively,
1574  * a STATIC variable).
1575  */
1576 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1577 {
1578 	const struct btf_type *t, *vt;
1579 	struct btf_var_secinfo *vsi;
1580 	int i, n;
1581 
1582 	if (!map->btf_value_type_id)
1583 		return false;
1584 
1585 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1586 	if (!btf_is_datasec(t))
1587 		return false;
1588 
1589 	vsi = btf_var_secinfos(t);
1590 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1591 		vt = btf__type_by_id(obj->btf, vsi->type);
1592 		if (!btf_is_var(vt))
1593 			continue;
1594 
1595 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1596 			return true;
1597 	}
1598 
1599 	return false;
1600 }
1601 
1602 static int
1603 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1604 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1605 {
1606 	struct bpf_map_def *def;
1607 	struct bpf_map *map;
1608 	int err;
1609 
1610 	map = bpf_object__add_map(obj);
1611 	if (IS_ERR(map))
1612 		return PTR_ERR(map);
1613 
1614 	map->libbpf_type = type;
1615 	map->sec_idx = sec_idx;
1616 	map->sec_offset = 0;
1617 	map->real_name = strdup(real_name);
1618 	map->name = internal_map_name(obj, real_name);
1619 	if (!map->real_name || !map->name) {
1620 		zfree(&map->real_name);
1621 		zfree(&map->name);
1622 		return -ENOMEM;
1623 	}
1624 
1625 	def = &map->def;
1626 	def->type = BPF_MAP_TYPE_ARRAY;
1627 	def->key_size = sizeof(int);
1628 	def->value_size = data_sz;
1629 	def->max_entries = 1;
1630 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1631 			 ? BPF_F_RDONLY_PROG : 0;
1632 
1633 	/* failures are fine because of maps like .rodata.str1.1 */
1634 	(void) map_fill_btf_type_info(obj, map);
1635 
1636 	if (map_is_mmapable(obj, map))
1637 		def->map_flags |= BPF_F_MMAPABLE;
1638 
1639 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1640 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1641 
1642 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1643 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1644 	if (map->mmaped == MAP_FAILED) {
1645 		err = -errno;
1646 		map->mmaped = NULL;
1647 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1648 			map->name, err);
1649 		zfree(&map->real_name);
1650 		zfree(&map->name);
1651 		return err;
1652 	}
1653 
1654 	if (data)
1655 		memcpy(map->mmaped, data, data_sz);
1656 
1657 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1658 	return 0;
1659 }
1660 
1661 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1662 {
1663 	struct elf_sec_desc *sec_desc;
1664 	const char *sec_name;
1665 	int err = 0, sec_idx;
1666 
1667 	/*
1668 	 * Populate obj->maps with libbpf internal maps.
1669 	 */
1670 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1671 		sec_desc = &obj->efile.secs[sec_idx];
1672 
1673 		/* Skip recognized sections with size 0. */
1674 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1675 			continue;
1676 
1677 		switch (sec_desc->sec_type) {
1678 		case SEC_DATA:
1679 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1680 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1681 							    sec_name, sec_idx,
1682 							    sec_desc->data->d_buf,
1683 							    sec_desc->data->d_size);
1684 			break;
1685 		case SEC_RODATA:
1686 			obj->has_rodata = true;
1687 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1688 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1689 							    sec_name, sec_idx,
1690 							    sec_desc->data->d_buf,
1691 							    sec_desc->data->d_size);
1692 			break;
1693 		case SEC_BSS:
1694 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1695 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1696 							    sec_name, sec_idx,
1697 							    NULL,
1698 							    sec_desc->data->d_size);
1699 			break;
1700 		default:
1701 			/* skip */
1702 			break;
1703 		}
1704 		if (err)
1705 			return err;
1706 	}
1707 	return 0;
1708 }
1709 
1710 
1711 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1712 					       const void *name)
1713 {
1714 	int i;
1715 
1716 	for (i = 0; i < obj->nr_extern; i++) {
1717 		if (strcmp(obj->externs[i].name, name) == 0)
1718 			return &obj->externs[i];
1719 	}
1720 	return NULL;
1721 }
1722 
1723 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1724 			      char value)
1725 {
1726 	switch (ext->kcfg.type) {
1727 	case KCFG_BOOL:
1728 		if (value == 'm') {
1729 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1730 				ext->name, value);
1731 			return -EINVAL;
1732 		}
1733 		*(bool *)ext_val = value == 'y' ? true : false;
1734 		break;
1735 	case KCFG_TRISTATE:
1736 		if (value == 'y')
1737 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1738 		else if (value == 'm')
1739 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1740 		else /* value == 'n' */
1741 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1742 		break;
1743 	case KCFG_CHAR:
1744 		*(char *)ext_val = value;
1745 		break;
1746 	case KCFG_UNKNOWN:
1747 	case KCFG_INT:
1748 	case KCFG_CHAR_ARR:
1749 	default:
1750 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1751 			ext->name, value);
1752 		return -EINVAL;
1753 	}
1754 	ext->is_set = true;
1755 	return 0;
1756 }
1757 
1758 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1759 			      const char *value)
1760 {
1761 	size_t len;
1762 
1763 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1764 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1765 			ext->name, value);
1766 		return -EINVAL;
1767 	}
1768 
1769 	len = strlen(value);
1770 	if (value[len - 1] != '"') {
1771 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1772 			ext->name, value);
1773 		return -EINVAL;
1774 	}
1775 
1776 	/* strip quotes */
1777 	len -= 2;
1778 	if (len >= ext->kcfg.sz) {
1779 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1780 			ext->name, value, len, ext->kcfg.sz - 1);
1781 		len = ext->kcfg.sz - 1;
1782 	}
1783 	memcpy(ext_val, value + 1, len);
1784 	ext_val[len] = '\0';
1785 	ext->is_set = true;
1786 	return 0;
1787 }
1788 
1789 static int parse_u64(const char *value, __u64 *res)
1790 {
1791 	char *value_end;
1792 	int err;
1793 
1794 	errno = 0;
1795 	*res = strtoull(value, &value_end, 0);
1796 	if (errno) {
1797 		err = -errno;
1798 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1799 		return err;
1800 	}
1801 	if (*value_end) {
1802 		pr_warn("failed to parse '%s' as integer completely\n", value);
1803 		return -EINVAL;
1804 	}
1805 	return 0;
1806 }
1807 
1808 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1809 {
1810 	int bit_sz = ext->kcfg.sz * 8;
1811 
1812 	if (ext->kcfg.sz == 8)
1813 		return true;
1814 
1815 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1816 	 * bytes size without any loss of information. If the target integer
1817 	 * is signed, we rely on the following limits of integer type of
1818 	 * Y bits and subsequent transformation:
1819 	 *
1820 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1821 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1822 	 *            0 <= X + 2^(Y-1) <  2^Y
1823 	 *
1824 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1825 	 *  zero.
1826 	 */
1827 	if (ext->kcfg.is_signed)
1828 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1829 	else
1830 		return (v >> bit_sz) == 0;
1831 }
1832 
1833 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1834 			      __u64 value)
1835 {
1836 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1837 	    ext->kcfg.type != KCFG_BOOL) {
1838 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1839 			ext->name, (unsigned long long)value);
1840 		return -EINVAL;
1841 	}
1842 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1843 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1844 			ext->name, (unsigned long long)value);
1845 		return -EINVAL;
1846 
1847 	}
1848 	if (!is_kcfg_value_in_range(ext, value)) {
1849 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1850 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1851 		return -ERANGE;
1852 	}
1853 	switch (ext->kcfg.sz) {
1854 	case 1:
1855 		*(__u8 *)ext_val = value;
1856 		break;
1857 	case 2:
1858 		*(__u16 *)ext_val = value;
1859 		break;
1860 	case 4:
1861 		*(__u32 *)ext_val = value;
1862 		break;
1863 	case 8:
1864 		*(__u64 *)ext_val = value;
1865 		break;
1866 	default:
1867 		return -EINVAL;
1868 	}
1869 	ext->is_set = true;
1870 	return 0;
1871 }
1872 
1873 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1874 					    char *buf, void *data)
1875 {
1876 	struct extern_desc *ext;
1877 	char *sep, *value;
1878 	int len, err = 0;
1879 	void *ext_val;
1880 	__u64 num;
1881 
1882 	if (!str_has_pfx(buf, "CONFIG_"))
1883 		return 0;
1884 
1885 	sep = strchr(buf, '=');
1886 	if (!sep) {
1887 		pr_warn("failed to parse '%s': no separator\n", buf);
1888 		return -EINVAL;
1889 	}
1890 
1891 	/* Trim ending '\n' */
1892 	len = strlen(buf);
1893 	if (buf[len - 1] == '\n')
1894 		buf[len - 1] = '\0';
1895 	/* Split on '=' and ensure that a value is present. */
1896 	*sep = '\0';
1897 	if (!sep[1]) {
1898 		*sep = '=';
1899 		pr_warn("failed to parse '%s': no value\n", buf);
1900 		return -EINVAL;
1901 	}
1902 
1903 	ext = find_extern_by_name(obj, buf);
1904 	if (!ext || ext->is_set)
1905 		return 0;
1906 
1907 	ext_val = data + ext->kcfg.data_off;
1908 	value = sep + 1;
1909 
1910 	switch (*value) {
1911 	case 'y': case 'n': case 'm':
1912 		err = set_kcfg_value_tri(ext, ext_val, *value);
1913 		break;
1914 	case '"':
1915 		err = set_kcfg_value_str(ext, ext_val, value);
1916 		break;
1917 	default:
1918 		/* assume integer */
1919 		err = parse_u64(value, &num);
1920 		if (err) {
1921 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1922 			return err;
1923 		}
1924 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1925 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1926 			return -EINVAL;
1927 		}
1928 		err = set_kcfg_value_num(ext, ext_val, num);
1929 		break;
1930 	}
1931 	if (err)
1932 		return err;
1933 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1934 	return 0;
1935 }
1936 
1937 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1938 {
1939 	char buf[PATH_MAX];
1940 	struct utsname uts;
1941 	int len, err = 0;
1942 	gzFile file;
1943 
1944 	uname(&uts);
1945 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1946 	if (len < 0)
1947 		return -EINVAL;
1948 	else if (len >= PATH_MAX)
1949 		return -ENAMETOOLONG;
1950 
1951 	/* gzopen also accepts uncompressed files. */
1952 	file = gzopen(buf, "r");
1953 	if (!file)
1954 		file = gzopen("/proc/config.gz", "r");
1955 
1956 	if (!file) {
1957 		pr_warn("failed to open system Kconfig\n");
1958 		return -ENOENT;
1959 	}
1960 
1961 	while (gzgets(file, buf, sizeof(buf))) {
1962 		err = bpf_object__process_kconfig_line(obj, buf, data);
1963 		if (err) {
1964 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1965 				buf, err);
1966 			goto out;
1967 		}
1968 	}
1969 
1970 out:
1971 	gzclose(file);
1972 	return err;
1973 }
1974 
1975 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1976 					const char *config, void *data)
1977 {
1978 	char buf[PATH_MAX];
1979 	int err = 0;
1980 	FILE *file;
1981 
1982 	file = fmemopen((void *)config, strlen(config), "r");
1983 	if (!file) {
1984 		err = -errno;
1985 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1986 		return err;
1987 	}
1988 
1989 	while (fgets(buf, sizeof(buf), file)) {
1990 		err = bpf_object__process_kconfig_line(obj, buf, data);
1991 		if (err) {
1992 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1993 				buf, err);
1994 			break;
1995 		}
1996 	}
1997 
1998 	fclose(file);
1999 	return err;
2000 }
2001 
2002 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2003 {
2004 	struct extern_desc *last_ext = NULL, *ext;
2005 	size_t map_sz;
2006 	int i, err;
2007 
2008 	for (i = 0; i < obj->nr_extern; i++) {
2009 		ext = &obj->externs[i];
2010 		if (ext->type == EXT_KCFG)
2011 			last_ext = ext;
2012 	}
2013 
2014 	if (!last_ext)
2015 		return 0;
2016 
2017 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2018 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2019 					    ".kconfig", obj->efile.symbols_shndx,
2020 					    NULL, map_sz);
2021 	if (err)
2022 		return err;
2023 
2024 	obj->kconfig_map_idx = obj->nr_maps - 1;
2025 
2026 	return 0;
2027 }
2028 
2029 const struct btf_type *
2030 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2031 {
2032 	const struct btf_type *t = btf__type_by_id(btf, id);
2033 
2034 	if (res_id)
2035 		*res_id = id;
2036 
2037 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2038 		if (res_id)
2039 			*res_id = t->type;
2040 		t = btf__type_by_id(btf, t->type);
2041 	}
2042 
2043 	return t;
2044 }
2045 
2046 static const struct btf_type *
2047 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2048 {
2049 	const struct btf_type *t;
2050 
2051 	t = skip_mods_and_typedefs(btf, id, NULL);
2052 	if (!btf_is_ptr(t))
2053 		return NULL;
2054 
2055 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2056 
2057 	return btf_is_func_proto(t) ? t : NULL;
2058 }
2059 
2060 static const char *__btf_kind_str(__u16 kind)
2061 {
2062 	switch (kind) {
2063 	case BTF_KIND_UNKN: return "void";
2064 	case BTF_KIND_INT: return "int";
2065 	case BTF_KIND_PTR: return "ptr";
2066 	case BTF_KIND_ARRAY: return "array";
2067 	case BTF_KIND_STRUCT: return "struct";
2068 	case BTF_KIND_UNION: return "union";
2069 	case BTF_KIND_ENUM: return "enum";
2070 	case BTF_KIND_FWD: return "fwd";
2071 	case BTF_KIND_TYPEDEF: return "typedef";
2072 	case BTF_KIND_VOLATILE: return "volatile";
2073 	case BTF_KIND_CONST: return "const";
2074 	case BTF_KIND_RESTRICT: return "restrict";
2075 	case BTF_KIND_FUNC: return "func";
2076 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2077 	case BTF_KIND_VAR: return "var";
2078 	case BTF_KIND_DATASEC: return "datasec";
2079 	case BTF_KIND_FLOAT: return "float";
2080 	case BTF_KIND_DECL_TAG: return "decl_tag";
2081 	case BTF_KIND_TYPE_TAG: return "type_tag";
2082 	case BTF_KIND_ENUM64: return "enum64";
2083 	default: return "unknown";
2084 	}
2085 }
2086 
2087 const char *btf_kind_str(const struct btf_type *t)
2088 {
2089 	return __btf_kind_str(btf_kind(t));
2090 }
2091 
2092 /*
2093  * Fetch integer attribute of BTF map definition. Such attributes are
2094  * represented using a pointer to an array, in which dimensionality of array
2095  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2096  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2097  * type definition, while using only sizeof(void *) space in ELF data section.
2098  */
2099 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2100 			      const struct btf_member *m, __u32 *res)
2101 {
2102 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2103 	const char *name = btf__name_by_offset(btf, m->name_off);
2104 	const struct btf_array *arr_info;
2105 	const struct btf_type *arr_t;
2106 
2107 	if (!btf_is_ptr(t)) {
2108 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2109 			map_name, name, btf_kind_str(t));
2110 		return false;
2111 	}
2112 
2113 	arr_t = btf__type_by_id(btf, t->type);
2114 	if (!arr_t) {
2115 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2116 			map_name, name, t->type);
2117 		return false;
2118 	}
2119 	if (!btf_is_array(arr_t)) {
2120 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2121 			map_name, name, btf_kind_str(arr_t));
2122 		return false;
2123 	}
2124 	arr_info = btf_array(arr_t);
2125 	*res = arr_info->nelems;
2126 	return true;
2127 }
2128 
2129 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2130 {
2131 	int len;
2132 
2133 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2134 	if (len < 0)
2135 		return -EINVAL;
2136 	if (len >= buf_sz)
2137 		return -ENAMETOOLONG;
2138 
2139 	return 0;
2140 }
2141 
2142 static int build_map_pin_path(struct bpf_map *map, const char *path)
2143 {
2144 	char buf[PATH_MAX];
2145 	int err;
2146 
2147 	if (!path)
2148 		path = "/sys/fs/bpf";
2149 
2150 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2151 	if (err)
2152 		return err;
2153 
2154 	return bpf_map__set_pin_path(map, buf);
2155 }
2156 
2157 /* should match definition in bpf_helpers.h */
2158 enum libbpf_pin_type {
2159 	LIBBPF_PIN_NONE,
2160 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2161 	LIBBPF_PIN_BY_NAME,
2162 };
2163 
2164 int parse_btf_map_def(const char *map_name, struct btf *btf,
2165 		      const struct btf_type *def_t, bool strict,
2166 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2167 {
2168 	const struct btf_type *t;
2169 	const struct btf_member *m;
2170 	bool is_inner = inner_def == NULL;
2171 	int vlen, i;
2172 
2173 	vlen = btf_vlen(def_t);
2174 	m = btf_members(def_t);
2175 	for (i = 0; i < vlen; i++, m++) {
2176 		const char *name = btf__name_by_offset(btf, m->name_off);
2177 
2178 		if (!name) {
2179 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2180 			return -EINVAL;
2181 		}
2182 		if (strcmp(name, "type") == 0) {
2183 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2184 				return -EINVAL;
2185 			map_def->parts |= MAP_DEF_MAP_TYPE;
2186 		} else if (strcmp(name, "max_entries") == 0) {
2187 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2188 				return -EINVAL;
2189 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2190 		} else if (strcmp(name, "map_flags") == 0) {
2191 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2192 				return -EINVAL;
2193 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2194 		} else if (strcmp(name, "numa_node") == 0) {
2195 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2196 				return -EINVAL;
2197 			map_def->parts |= MAP_DEF_NUMA_NODE;
2198 		} else if (strcmp(name, "key_size") == 0) {
2199 			__u32 sz;
2200 
2201 			if (!get_map_field_int(map_name, btf, m, &sz))
2202 				return -EINVAL;
2203 			if (map_def->key_size && map_def->key_size != sz) {
2204 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2205 					map_name, map_def->key_size, sz);
2206 				return -EINVAL;
2207 			}
2208 			map_def->key_size = sz;
2209 			map_def->parts |= MAP_DEF_KEY_SIZE;
2210 		} else if (strcmp(name, "key") == 0) {
2211 			__s64 sz;
2212 
2213 			t = btf__type_by_id(btf, m->type);
2214 			if (!t) {
2215 				pr_warn("map '%s': key type [%d] not found.\n",
2216 					map_name, m->type);
2217 				return -EINVAL;
2218 			}
2219 			if (!btf_is_ptr(t)) {
2220 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2221 					map_name, btf_kind_str(t));
2222 				return -EINVAL;
2223 			}
2224 			sz = btf__resolve_size(btf, t->type);
2225 			if (sz < 0) {
2226 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2227 					map_name, t->type, (ssize_t)sz);
2228 				return sz;
2229 			}
2230 			if (map_def->key_size && map_def->key_size != sz) {
2231 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2232 					map_name, map_def->key_size, (ssize_t)sz);
2233 				return -EINVAL;
2234 			}
2235 			map_def->key_size = sz;
2236 			map_def->key_type_id = t->type;
2237 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2238 		} else if (strcmp(name, "value_size") == 0) {
2239 			__u32 sz;
2240 
2241 			if (!get_map_field_int(map_name, btf, m, &sz))
2242 				return -EINVAL;
2243 			if (map_def->value_size && map_def->value_size != sz) {
2244 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2245 					map_name, map_def->value_size, sz);
2246 				return -EINVAL;
2247 			}
2248 			map_def->value_size = sz;
2249 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2250 		} else if (strcmp(name, "value") == 0) {
2251 			__s64 sz;
2252 
2253 			t = btf__type_by_id(btf, m->type);
2254 			if (!t) {
2255 				pr_warn("map '%s': value type [%d] not found.\n",
2256 					map_name, m->type);
2257 				return -EINVAL;
2258 			}
2259 			if (!btf_is_ptr(t)) {
2260 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2261 					map_name, btf_kind_str(t));
2262 				return -EINVAL;
2263 			}
2264 			sz = btf__resolve_size(btf, t->type);
2265 			if (sz < 0) {
2266 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2267 					map_name, t->type, (ssize_t)sz);
2268 				return sz;
2269 			}
2270 			if (map_def->value_size && map_def->value_size != sz) {
2271 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2272 					map_name, map_def->value_size, (ssize_t)sz);
2273 				return -EINVAL;
2274 			}
2275 			map_def->value_size = sz;
2276 			map_def->value_type_id = t->type;
2277 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2278 		}
2279 		else if (strcmp(name, "values") == 0) {
2280 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2281 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2282 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2283 			char inner_map_name[128];
2284 			int err;
2285 
2286 			if (is_inner) {
2287 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2288 					map_name);
2289 				return -ENOTSUP;
2290 			}
2291 			if (i != vlen - 1) {
2292 				pr_warn("map '%s': '%s' member should be last.\n",
2293 					map_name, name);
2294 				return -EINVAL;
2295 			}
2296 			if (!is_map_in_map && !is_prog_array) {
2297 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2298 					map_name);
2299 				return -ENOTSUP;
2300 			}
2301 			if (map_def->value_size && map_def->value_size != 4) {
2302 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2303 					map_name, map_def->value_size);
2304 				return -EINVAL;
2305 			}
2306 			map_def->value_size = 4;
2307 			t = btf__type_by_id(btf, m->type);
2308 			if (!t) {
2309 				pr_warn("map '%s': %s type [%d] not found.\n",
2310 					map_name, desc, m->type);
2311 				return -EINVAL;
2312 			}
2313 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2314 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2315 					map_name, desc);
2316 				return -EINVAL;
2317 			}
2318 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2319 			if (!btf_is_ptr(t)) {
2320 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2321 					map_name, desc, btf_kind_str(t));
2322 				return -EINVAL;
2323 			}
2324 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2325 			if (is_prog_array) {
2326 				if (!btf_is_func_proto(t)) {
2327 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2328 						map_name, btf_kind_str(t));
2329 					return -EINVAL;
2330 				}
2331 				continue;
2332 			}
2333 			if (!btf_is_struct(t)) {
2334 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2335 					map_name, btf_kind_str(t));
2336 				return -EINVAL;
2337 			}
2338 
2339 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2340 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2341 			if (err)
2342 				return err;
2343 
2344 			map_def->parts |= MAP_DEF_INNER_MAP;
2345 		} else if (strcmp(name, "pinning") == 0) {
2346 			__u32 val;
2347 
2348 			if (is_inner) {
2349 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2350 				return -EINVAL;
2351 			}
2352 			if (!get_map_field_int(map_name, btf, m, &val))
2353 				return -EINVAL;
2354 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2355 				pr_warn("map '%s': invalid pinning value %u.\n",
2356 					map_name, val);
2357 				return -EINVAL;
2358 			}
2359 			map_def->pinning = val;
2360 			map_def->parts |= MAP_DEF_PINNING;
2361 		} else if (strcmp(name, "map_extra") == 0) {
2362 			__u32 map_extra;
2363 
2364 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2365 				return -EINVAL;
2366 			map_def->map_extra = map_extra;
2367 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2368 		} else {
2369 			if (strict) {
2370 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2371 				return -ENOTSUP;
2372 			}
2373 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2374 		}
2375 	}
2376 
2377 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2378 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2379 		return -EINVAL;
2380 	}
2381 
2382 	return 0;
2383 }
2384 
2385 static size_t adjust_ringbuf_sz(size_t sz)
2386 {
2387 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2388 	__u32 mul;
2389 
2390 	/* if user forgot to set any size, make sure they see error */
2391 	if (sz == 0)
2392 		return 0;
2393 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2394 	 * a power-of-2 multiple of kernel's page size. If user diligently
2395 	 * satisified these conditions, pass the size through.
2396 	 */
2397 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2398 		return sz;
2399 
2400 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2401 	 * user-set size to satisfy both user size request and kernel
2402 	 * requirements and substitute correct max_entries for map creation.
2403 	 */
2404 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2405 		if (mul * page_sz > sz)
2406 			return mul * page_sz;
2407 	}
2408 
2409 	/* if it's impossible to satisfy the conditions (i.e., user size is
2410 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2411 	 * page_size) then just return original size and let kernel reject it
2412 	 */
2413 	return sz;
2414 }
2415 
2416 static bool map_is_ringbuf(const struct bpf_map *map)
2417 {
2418 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2419 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2420 }
2421 
2422 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2423 {
2424 	map->def.type = def->map_type;
2425 	map->def.key_size = def->key_size;
2426 	map->def.value_size = def->value_size;
2427 	map->def.max_entries = def->max_entries;
2428 	map->def.map_flags = def->map_flags;
2429 	map->map_extra = def->map_extra;
2430 
2431 	map->numa_node = def->numa_node;
2432 	map->btf_key_type_id = def->key_type_id;
2433 	map->btf_value_type_id = def->value_type_id;
2434 
2435 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2436 	if (map_is_ringbuf(map))
2437 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2438 
2439 	if (def->parts & MAP_DEF_MAP_TYPE)
2440 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2441 
2442 	if (def->parts & MAP_DEF_KEY_TYPE)
2443 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2444 			 map->name, def->key_type_id, def->key_size);
2445 	else if (def->parts & MAP_DEF_KEY_SIZE)
2446 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2447 
2448 	if (def->parts & MAP_DEF_VALUE_TYPE)
2449 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2450 			 map->name, def->value_type_id, def->value_size);
2451 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2452 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2453 
2454 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2455 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2456 	if (def->parts & MAP_DEF_MAP_FLAGS)
2457 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2458 	if (def->parts & MAP_DEF_MAP_EXTRA)
2459 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2460 			 (unsigned long long)def->map_extra);
2461 	if (def->parts & MAP_DEF_PINNING)
2462 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2463 	if (def->parts & MAP_DEF_NUMA_NODE)
2464 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2465 
2466 	if (def->parts & MAP_DEF_INNER_MAP)
2467 		pr_debug("map '%s': found inner map definition.\n", map->name);
2468 }
2469 
2470 static const char *btf_var_linkage_str(__u32 linkage)
2471 {
2472 	switch (linkage) {
2473 	case BTF_VAR_STATIC: return "static";
2474 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2475 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2476 	default: return "unknown";
2477 	}
2478 }
2479 
2480 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2481 					 const struct btf_type *sec,
2482 					 int var_idx, int sec_idx,
2483 					 const Elf_Data *data, bool strict,
2484 					 const char *pin_root_path)
2485 {
2486 	struct btf_map_def map_def = {}, inner_def = {};
2487 	const struct btf_type *var, *def;
2488 	const struct btf_var_secinfo *vi;
2489 	const struct btf_var *var_extra;
2490 	const char *map_name;
2491 	struct bpf_map *map;
2492 	int err;
2493 
2494 	vi = btf_var_secinfos(sec) + var_idx;
2495 	var = btf__type_by_id(obj->btf, vi->type);
2496 	var_extra = btf_var(var);
2497 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2498 
2499 	if (map_name == NULL || map_name[0] == '\0') {
2500 		pr_warn("map #%d: empty name.\n", var_idx);
2501 		return -EINVAL;
2502 	}
2503 	if ((__u64)vi->offset + vi->size > data->d_size) {
2504 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2505 		return -EINVAL;
2506 	}
2507 	if (!btf_is_var(var)) {
2508 		pr_warn("map '%s': unexpected var kind %s.\n",
2509 			map_name, btf_kind_str(var));
2510 		return -EINVAL;
2511 	}
2512 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2513 		pr_warn("map '%s': unsupported map linkage %s.\n",
2514 			map_name, btf_var_linkage_str(var_extra->linkage));
2515 		return -EOPNOTSUPP;
2516 	}
2517 
2518 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2519 	if (!btf_is_struct(def)) {
2520 		pr_warn("map '%s': unexpected def kind %s.\n",
2521 			map_name, btf_kind_str(var));
2522 		return -EINVAL;
2523 	}
2524 	if (def->size > vi->size) {
2525 		pr_warn("map '%s': invalid def size.\n", map_name);
2526 		return -EINVAL;
2527 	}
2528 
2529 	map = bpf_object__add_map(obj);
2530 	if (IS_ERR(map))
2531 		return PTR_ERR(map);
2532 	map->name = strdup(map_name);
2533 	if (!map->name) {
2534 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2535 		return -ENOMEM;
2536 	}
2537 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2538 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2539 	map->sec_idx = sec_idx;
2540 	map->sec_offset = vi->offset;
2541 	map->btf_var_idx = var_idx;
2542 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2543 		 map_name, map->sec_idx, map->sec_offset);
2544 
2545 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2546 	if (err)
2547 		return err;
2548 
2549 	fill_map_from_def(map, &map_def);
2550 
2551 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2552 		err = build_map_pin_path(map, pin_root_path);
2553 		if (err) {
2554 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2555 			return err;
2556 		}
2557 	}
2558 
2559 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2560 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2561 		if (!map->inner_map)
2562 			return -ENOMEM;
2563 		map->inner_map->fd = -1;
2564 		map->inner_map->sec_idx = sec_idx;
2565 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2566 		if (!map->inner_map->name)
2567 			return -ENOMEM;
2568 		sprintf(map->inner_map->name, "%s.inner", map_name);
2569 
2570 		fill_map_from_def(map->inner_map, &inner_def);
2571 	}
2572 
2573 	err = map_fill_btf_type_info(obj, map);
2574 	if (err)
2575 		return err;
2576 
2577 	return 0;
2578 }
2579 
2580 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2581 					  const char *pin_root_path)
2582 {
2583 	const struct btf_type *sec = NULL;
2584 	int nr_types, i, vlen, err;
2585 	const struct btf_type *t;
2586 	const char *name;
2587 	Elf_Data *data;
2588 	Elf_Scn *scn;
2589 
2590 	if (obj->efile.btf_maps_shndx < 0)
2591 		return 0;
2592 
2593 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2594 	data = elf_sec_data(obj, scn);
2595 	if (!scn || !data) {
2596 		pr_warn("elf: failed to get %s map definitions for %s\n",
2597 			MAPS_ELF_SEC, obj->path);
2598 		return -EINVAL;
2599 	}
2600 
2601 	nr_types = btf__type_cnt(obj->btf);
2602 	for (i = 1; i < nr_types; i++) {
2603 		t = btf__type_by_id(obj->btf, i);
2604 		if (!btf_is_datasec(t))
2605 			continue;
2606 		name = btf__name_by_offset(obj->btf, t->name_off);
2607 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2608 			sec = t;
2609 			obj->efile.btf_maps_sec_btf_id = i;
2610 			break;
2611 		}
2612 	}
2613 
2614 	if (!sec) {
2615 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2616 		return -ENOENT;
2617 	}
2618 
2619 	vlen = btf_vlen(sec);
2620 	for (i = 0; i < vlen; i++) {
2621 		err = bpf_object__init_user_btf_map(obj, sec, i,
2622 						    obj->efile.btf_maps_shndx,
2623 						    data, strict,
2624 						    pin_root_path);
2625 		if (err)
2626 			return err;
2627 	}
2628 
2629 	return 0;
2630 }
2631 
2632 static int bpf_object__init_maps(struct bpf_object *obj,
2633 				 const struct bpf_object_open_opts *opts)
2634 {
2635 	const char *pin_root_path;
2636 	bool strict;
2637 	int err = 0;
2638 
2639 	strict = !OPTS_GET(opts, relaxed_maps, false);
2640 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2641 
2642 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2643 	err = err ?: bpf_object__init_global_data_maps(obj);
2644 	err = err ?: bpf_object__init_kconfig_map(obj);
2645 	err = err ?: bpf_object_init_struct_ops(obj);
2646 
2647 	return err;
2648 }
2649 
2650 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2651 {
2652 	Elf64_Shdr *sh;
2653 
2654 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2655 	if (!sh)
2656 		return false;
2657 
2658 	return sh->sh_flags & SHF_EXECINSTR;
2659 }
2660 
2661 static bool btf_needs_sanitization(struct bpf_object *obj)
2662 {
2663 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2664 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2665 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2666 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2667 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2668 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2669 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2670 
2671 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2672 	       !has_decl_tag || !has_type_tag || !has_enum64;
2673 }
2674 
2675 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2676 {
2677 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2678 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2679 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2680 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2681 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2682 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2683 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2684 	int enum64_placeholder_id = 0;
2685 	struct btf_type *t;
2686 	int i, j, vlen;
2687 
2688 	for (i = 1; i < btf__type_cnt(btf); i++) {
2689 		t = (struct btf_type *)btf__type_by_id(btf, i);
2690 
2691 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2692 			/* replace VAR/DECL_TAG with INT */
2693 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2694 			/*
2695 			 * using size = 1 is the safest choice, 4 will be too
2696 			 * big and cause kernel BTF validation failure if
2697 			 * original variable took less than 4 bytes
2698 			 */
2699 			t->size = 1;
2700 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2701 		} else if (!has_datasec && btf_is_datasec(t)) {
2702 			/* replace DATASEC with STRUCT */
2703 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2704 			struct btf_member *m = btf_members(t);
2705 			struct btf_type *vt;
2706 			char *name;
2707 
2708 			name = (char *)btf__name_by_offset(btf, t->name_off);
2709 			while (*name) {
2710 				if (*name == '.')
2711 					*name = '_';
2712 				name++;
2713 			}
2714 
2715 			vlen = btf_vlen(t);
2716 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2717 			for (j = 0; j < vlen; j++, v++, m++) {
2718 				/* order of field assignments is important */
2719 				m->offset = v->offset * 8;
2720 				m->type = v->type;
2721 				/* preserve variable name as member name */
2722 				vt = (void *)btf__type_by_id(btf, v->type);
2723 				m->name_off = vt->name_off;
2724 			}
2725 		} else if (!has_func && btf_is_func_proto(t)) {
2726 			/* replace FUNC_PROTO with ENUM */
2727 			vlen = btf_vlen(t);
2728 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2729 			t->size = sizeof(__u32); /* kernel enforced */
2730 		} else if (!has_func && btf_is_func(t)) {
2731 			/* replace FUNC with TYPEDEF */
2732 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2733 		} else if (!has_func_global && btf_is_func(t)) {
2734 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2735 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2736 		} else if (!has_float && btf_is_float(t)) {
2737 			/* replace FLOAT with an equally-sized empty STRUCT;
2738 			 * since C compilers do not accept e.g. "float" as a
2739 			 * valid struct name, make it anonymous
2740 			 */
2741 			t->name_off = 0;
2742 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2743 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2744 			/* replace TYPE_TAG with a CONST */
2745 			t->name_off = 0;
2746 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2747 		} else if (!has_enum64 && btf_is_enum(t)) {
2748 			/* clear the kflag */
2749 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2750 		} else if (!has_enum64 && btf_is_enum64(t)) {
2751 			/* replace ENUM64 with a union */
2752 			struct btf_member *m;
2753 
2754 			if (enum64_placeholder_id == 0) {
2755 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2756 				if (enum64_placeholder_id < 0)
2757 					return enum64_placeholder_id;
2758 
2759 				t = (struct btf_type *)btf__type_by_id(btf, i);
2760 			}
2761 
2762 			m = btf_members(t);
2763 			vlen = btf_vlen(t);
2764 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2765 			for (j = 0; j < vlen; j++, m++) {
2766 				m->type = enum64_placeholder_id;
2767 				m->offset = 0;
2768 			}
2769 		}
2770 	}
2771 
2772 	return 0;
2773 }
2774 
2775 static bool libbpf_needs_btf(const struct bpf_object *obj)
2776 {
2777 	return obj->efile.btf_maps_shndx >= 0 ||
2778 	       obj->efile.st_ops_shndx >= 0 ||
2779 	       obj->efile.st_ops_link_shndx >= 0 ||
2780 	       obj->nr_extern > 0;
2781 }
2782 
2783 static bool kernel_needs_btf(const struct bpf_object *obj)
2784 {
2785 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2786 }
2787 
2788 static int bpf_object__init_btf(struct bpf_object *obj,
2789 				Elf_Data *btf_data,
2790 				Elf_Data *btf_ext_data)
2791 {
2792 	int err = -ENOENT;
2793 
2794 	if (btf_data) {
2795 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2796 		err = libbpf_get_error(obj->btf);
2797 		if (err) {
2798 			obj->btf = NULL;
2799 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2800 			goto out;
2801 		}
2802 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2803 		btf__set_pointer_size(obj->btf, 8);
2804 	}
2805 	if (btf_ext_data) {
2806 		struct btf_ext_info *ext_segs[3];
2807 		int seg_num, sec_num;
2808 
2809 		if (!obj->btf) {
2810 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2811 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2812 			goto out;
2813 		}
2814 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2815 		err = libbpf_get_error(obj->btf_ext);
2816 		if (err) {
2817 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2818 				BTF_EXT_ELF_SEC, err);
2819 			obj->btf_ext = NULL;
2820 			goto out;
2821 		}
2822 
2823 		/* setup .BTF.ext to ELF section mapping */
2824 		ext_segs[0] = &obj->btf_ext->func_info;
2825 		ext_segs[1] = &obj->btf_ext->line_info;
2826 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2827 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2828 			struct btf_ext_info *seg = ext_segs[seg_num];
2829 			const struct btf_ext_info_sec *sec;
2830 			const char *sec_name;
2831 			Elf_Scn *scn;
2832 
2833 			if (seg->sec_cnt == 0)
2834 				continue;
2835 
2836 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2837 			if (!seg->sec_idxs) {
2838 				err = -ENOMEM;
2839 				goto out;
2840 			}
2841 
2842 			sec_num = 0;
2843 			for_each_btf_ext_sec(seg, sec) {
2844 				/* preventively increment index to avoid doing
2845 				 * this before every continue below
2846 				 */
2847 				sec_num++;
2848 
2849 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2850 				if (str_is_empty(sec_name))
2851 					continue;
2852 				scn = elf_sec_by_name(obj, sec_name);
2853 				if (!scn)
2854 					continue;
2855 
2856 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2857 			}
2858 		}
2859 	}
2860 out:
2861 	if (err && libbpf_needs_btf(obj)) {
2862 		pr_warn("BTF is required, but is missing or corrupted.\n");
2863 		return err;
2864 	}
2865 	return 0;
2866 }
2867 
2868 static int compare_vsi_off(const void *_a, const void *_b)
2869 {
2870 	const struct btf_var_secinfo *a = _a;
2871 	const struct btf_var_secinfo *b = _b;
2872 
2873 	return a->offset - b->offset;
2874 }
2875 
2876 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2877 			     struct btf_type *t)
2878 {
2879 	__u32 size = 0, i, vars = btf_vlen(t);
2880 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2881 	struct btf_var_secinfo *vsi;
2882 	bool fixup_offsets = false;
2883 	int err;
2884 
2885 	if (!sec_name) {
2886 		pr_debug("No name found in string section for DATASEC kind.\n");
2887 		return -ENOENT;
2888 	}
2889 
2890 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2891 	 * variable offsets set at the previous step. Further, not every
2892 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2893 	 * all fixups altogether for such sections and go straight to sorting
2894 	 * VARs within their DATASEC.
2895 	 */
2896 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2897 		goto sort_vars;
2898 
2899 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2900 	 * fix this up. But BPF static linker already fixes this up and fills
2901 	 * all the sizes and offsets during static linking. So this step has
2902 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2903 	 * non-extern DATASEC, so the variable fixup loop below handles both
2904 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2905 	 * symbol matching just once.
2906 	 */
2907 	if (t->size == 0) {
2908 		err = find_elf_sec_sz(obj, sec_name, &size);
2909 		if (err || !size) {
2910 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2911 				 sec_name, size, err);
2912 			return -ENOENT;
2913 		}
2914 
2915 		t->size = size;
2916 		fixup_offsets = true;
2917 	}
2918 
2919 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2920 		const struct btf_type *t_var;
2921 		struct btf_var *var;
2922 		const char *var_name;
2923 		Elf64_Sym *sym;
2924 
2925 		t_var = btf__type_by_id(btf, vsi->type);
2926 		if (!t_var || !btf_is_var(t_var)) {
2927 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2928 			return -EINVAL;
2929 		}
2930 
2931 		var = btf_var(t_var);
2932 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2933 			continue;
2934 
2935 		var_name = btf__name_by_offset(btf, t_var->name_off);
2936 		if (!var_name) {
2937 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2938 				 sec_name, i);
2939 			return -ENOENT;
2940 		}
2941 
2942 		sym = find_elf_var_sym(obj, var_name);
2943 		if (IS_ERR(sym)) {
2944 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2945 				 sec_name, var_name);
2946 			return -ENOENT;
2947 		}
2948 
2949 		if (fixup_offsets)
2950 			vsi->offset = sym->st_value;
2951 
2952 		/* if variable is a global/weak symbol, but has restricted
2953 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2954 		 * as static. This follows similar logic for functions (BPF
2955 		 * subprogs) and influences libbpf's further decisions about
2956 		 * whether to make global data BPF array maps as
2957 		 * BPF_F_MMAPABLE.
2958 		 */
2959 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2960 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2961 			var->linkage = BTF_VAR_STATIC;
2962 	}
2963 
2964 sort_vars:
2965 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2966 	return 0;
2967 }
2968 
2969 static int bpf_object_fixup_btf(struct bpf_object *obj)
2970 {
2971 	int i, n, err = 0;
2972 
2973 	if (!obj->btf)
2974 		return 0;
2975 
2976 	n = btf__type_cnt(obj->btf);
2977 	for (i = 1; i < n; i++) {
2978 		struct btf_type *t = btf_type_by_id(obj->btf, i);
2979 
2980 		/* Loader needs to fix up some of the things compiler
2981 		 * couldn't get its hands on while emitting BTF. This
2982 		 * is section size and global variable offset. We use
2983 		 * the info from the ELF itself for this purpose.
2984 		 */
2985 		if (btf_is_datasec(t)) {
2986 			err = btf_fixup_datasec(obj, obj->btf, t);
2987 			if (err)
2988 				return err;
2989 		}
2990 	}
2991 
2992 	return 0;
2993 }
2994 
2995 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2996 {
2997 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2998 	    prog->type == BPF_PROG_TYPE_LSM)
2999 		return true;
3000 
3001 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3002 	 * also need vmlinux BTF
3003 	 */
3004 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3005 		return true;
3006 
3007 	return false;
3008 }
3009 
3010 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3011 {
3012 	struct bpf_program *prog;
3013 	int i;
3014 
3015 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3016 	 * is not specified
3017 	 */
3018 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3019 		return true;
3020 
3021 	/* Support for typed ksyms needs kernel BTF */
3022 	for (i = 0; i < obj->nr_extern; i++) {
3023 		const struct extern_desc *ext;
3024 
3025 		ext = &obj->externs[i];
3026 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3027 			return true;
3028 	}
3029 
3030 	bpf_object__for_each_program(prog, obj) {
3031 		if (!prog->autoload)
3032 			continue;
3033 		if (prog_needs_vmlinux_btf(prog))
3034 			return true;
3035 	}
3036 
3037 	return false;
3038 }
3039 
3040 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3041 {
3042 	int err;
3043 
3044 	/* btf_vmlinux could be loaded earlier */
3045 	if (obj->btf_vmlinux || obj->gen_loader)
3046 		return 0;
3047 
3048 	if (!force && !obj_needs_vmlinux_btf(obj))
3049 		return 0;
3050 
3051 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3052 	err = libbpf_get_error(obj->btf_vmlinux);
3053 	if (err) {
3054 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3055 		obj->btf_vmlinux = NULL;
3056 		return err;
3057 	}
3058 	return 0;
3059 }
3060 
3061 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3062 {
3063 	struct btf *kern_btf = obj->btf;
3064 	bool btf_mandatory, sanitize;
3065 	int i, err = 0;
3066 
3067 	if (!obj->btf)
3068 		return 0;
3069 
3070 	if (!kernel_supports(obj, FEAT_BTF)) {
3071 		if (kernel_needs_btf(obj)) {
3072 			err = -EOPNOTSUPP;
3073 			goto report;
3074 		}
3075 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3076 		return 0;
3077 	}
3078 
3079 	/* Even though some subprogs are global/weak, user might prefer more
3080 	 * permissive BPF verification process that BPF verifier performs for
3081 	 * static functions, taking into account more context from the caller
3082 	 * functions. In such case, they need to mark such subprogs with
3083 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3084 	 * corresponding FUNC BTF type to be marked as static and trigger more
3085 	 * involved BPF verification process.
3086 	 */
3087 	for (i = 0; i < obj->nr_programs; i++) {
3088 		struct bpf_program *prog = &obj->programs[i];
3089 		struct btf_type *t;
3090 		const char *name;
3091 		int j, n;
3092 
3093 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3094 			continue;
3095 
3096 		n = btf__type_cnt(obj->btf);
3097 		for (j = 1; j < n; j++) {
3098 			t = btf_type_by_id(obj->btf, j);
3099 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3100 				continue;
3101 
3102 			name = btf__str_by_offset(obj->btf, t->name_off);
3103 			if (strcmp(name, prog->name) != 0)
3104 				continue;
3105 
3106 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3107 			break;
3108 		}
3109 	}
3110 
3111 	sanitize = btf_needs_sanitization(obj);
3112 	if (sanitize) {
3113 		const void *raw_data;
3114 		__u32 sz;
3115 
3116 		/* clone BTF to sanitize a copy and leave the original intact */
3117 		raw_data = btf__raw_data(obj->btf, &sz);
3118 		kern_btf = btf__new(raw_data, sz);
3119 		err = libbpf_get_error(kern_btf);
3120 		if (err)
3121 			return err;
3122 
3123 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3124 		btf__set_pointer_size(obj->btf, 8);
3125 		err = bpf_object__sanitize_btf(obj, kern_btf);
3126 		if (err)
3127 			return err;
3128 	}
3129 
3130 	if (obj->gen_loader) {
3131 		__u32 raw_size = 0;
3132 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3133 
3134 		if (!raw_data)
3135 			return -ENOMEM;
3136 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3137 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3138 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3139 		 */
3140 		btf__set_fd(kern_btf, 0);
3141 	} else {
3142 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3143 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3144 					   obj->log_level ? 1 : 0);
3145 	}
3146 	if (sanitize) {
3147 		if (!err) {
3148 			/* move fd to libbpf's BTF */
3149 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3150 			btf__set_fd(kern_btf, -1);
3151 		}
3152 		btf__free(kern_btf);
3153 	}
3154 report:
3155 	if (err) {
3156 		btf_mandatory = kernel_needs_btf(obj);
3157 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3158 			btf_mandatory ? "BTF is mandatory, can't proceed."
3159 				      : "BTF is optional, ignoring.");
3160 		if (!btf_mandatory)
3161 			err = 0;
3162 	}
3163 	return err;
3164 }
3165 
3166 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3167 {
3168 	const char *name;
3169 
3170 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3171 	if (!name) {
3172 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3173 			off, obj->path, elf_errmsg(-1));
3174 		return NULL;
3175 	}
3176 
3177 	return name;
3178 }
3179 
3180 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3181 {
3182 	const char *name;
3183 
3184 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3185 	if (!name) {
3186 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3187 			off, obj->path, elf_errmsg(-1));
3188 		return NULL;
3189 	}
3190 
3191 	return name;
3192 }
3193 
3194 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3195 {
3196 	Elf_Scn *scn;
3197 
3198 	scn = elf_getscn(obj->efile.elf, idx);
3199 	if (!scn) {
3200 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3201 			idx, obj->path, elf_errmsg(-1));
3202 		return NULL;
3203 	}
3204 	return scn;
3205 }
3206 
3207 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3208 {
3209 	Elf_Scn *scn = NULL;
3210 	Elf *elf = obj->efile.elf;
3211 	const char *sec_name;
3212 
3213 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3214 		sec_name = elf_sec_name(obj, scn);
3215 		if (!sec_name)
3216 			return NULL;
3217 
3218 		if (strcmp(sec_name, name) != 0)
3219 			continue;
3220 
3221 		return scn;
3222 	}
3223 	return NULL;
3224 }
3225 
3226 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3227 {
3228 	Elf64_Shdr *shdr;
3229 
3230 	if (!scn)
3231 		return NULL;
3232 
3233 	shdr = elf64_getshdr(scn);
3234 	if (!shdr) {
3235 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3236 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3237 		return NULL;
3238 	}
3239 
3240 	return shdr;
3241 }
3242 
3243 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3244 {
3245 	const char *name;
3246 	Elf64_Shdr *sh;
3247 
3248 	if (!scn)
3249 		return NULL;
3250 
3251 	sh = elf_sec_hdr(obj, scn);
3252 	if (!sh)
3253 		return NULL;
3254 
3255 	name = elf_sec_str(obj, sh->sh_name);
3256 	if (!name) {
3257 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3258 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3259 		return NULL;
3260 	}
3261 
3262 	return name;
3263 }
3264 
3265 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3266 {
3267 	Elf_Data *data;
3268 
3269 	if (!scn)
3270 		return NULL;
3271 
3272 	data = elf_getdata(scn, 0);
3273 	if (!data) {
3274 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3275 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3276 			obj->path, elf_errmsg(-1));
3277 		return NULL;
3278 	}
3279 
3280 	return data;
3281 }
3282 
3283 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3284 {
3285 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3286 		return NULL;
3287 
3288 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3289 }
3290 
3291 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3292 {
3293 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3294 		return NULL;
3295 
3296 	return (Elf64_Rel *)data->d_buf + idx;
3297 }
3298 
3299 static bool is_sec_name_dwarf(const char *name)
3300 {
3301 	/* approximation, but the actual list is too long */
3302 	return str_has_pfx(name, ".debug_");
3303 }
3304 
3305 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3306 {
3307 	/* no special handling of .strtab */
3308 	if (hdr->sh_type == SHT_STRTAB)
3309 		return true;
3310 
3311 	/* ignore .llvm_addrsig section as well */
3312 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3313 		return true;
3314 
3315 	/* no subprograms will lead to an empty .text section, ignore it */
3316 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3317 	    strcmp(name, ".text") == 0)
3318 		return true;
3319 
3320 	/* DWARF sections */
3321 	if (is_sec_name_dwarf(name))
3322 		return true;
3323 
3324 	if (str_has_pfx(name, ".rel")) {
3325 		name += sizeof(".rel") - 1;
3326 		/* DWARF section relocations */
3327 		if (is_sec_name_dwarf(name))
3328 			return true;
3329 
3330 		/* .BTF and .BTF.ext don't need relocations */
3331 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3332 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3333 			return true;
3334 	}
3335 
3336 	return false;
3337 }
3338 
3339 static int cmp_progs(const void *_a, const void *_b)
3340 {
3341 	const struct bpf_program *a = _a;
3342 	const struct bpf_program *b = _b;
3343 
3344 	if (a->sec_idx != b->sec_idx)
3345 		return a->sec_idx < b->sec_idx ? -1 : 1;
3346 
3347 	/* sec_insn_off can't be the same within the section */
3348 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3349 }
3350 
3351 static int bpf_object__elf_collect(struct bpf_object *obj)
3352 {
3353 	struct elf_sec_desc *sec_desc;
3354 	Elf *elf = obj->efile.elf;
3355 	Elf_Data *btf_ext_data = NULL;
3356 	Elf_Data *btf_data = NULL;
3357 	int idx = 0, err = 0;
3358 	const char *name;
3359 	Elf_Data *data;
3360 	Elf_Scn *scn;
3361 	Elf64_Shdr *sh;
3362 
3363 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3364 	 * section. Since section count retrieved by elf_getshdrnum() does
3365 	 * include sec #0, it is already the necessary size of an array to keep
3366 	 * all the sections.
3367 	 */
3368 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3369 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3370 			obj->path, elf_errmsg(-1));
3371 		return -LIBBPF_ERRNO__FORMAT;
3372 	}
3373 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3374 	if (!obj->efile.secs)
3375 		return -ENOMEM;
3376 
3377 	/* a bunch of ELF parsing functionality depends on processing symbols,
3378 	 * so do the first pass and find the symbol table
3379 	 */
3380 	scn = NULL;
3381 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3382 		sh = elf_sec_hdr(obj, scn);
3383 		if (!sh)
3384 			return -LIBBPF_ERRNO__FORMAT;
3385 
3386 		if (sh->sh_type == SHT_SYMTAB) {
3387 			if (obj->efile.symbols) {
3388 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3389 				return -LIBBPF_ERRNO__FORMAT;
3390 			}
3391 
3392 			data = elf_sec_data(obj, scn);
3393 			if (!data)
3394 				return -LIBBPF_ERRNO__FORMAT;
3395 
3396 			idx = elf_ndxscn(scn);
3397 
3398 			obj->efile.symbols = data;
3399 			obj->efile.symbols_shndx = idx;
3400 			obj->efile.strtabidx = sh->sh_link;
3401 		}
3402 	}
3403 
3404 	if (!obj->efile.symbols) {
3405 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3406 			obj->path);
3407 		return -ENOENT;
3408 	}
3409 
3410 	scn = NULL;
3411 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3412 		idx = elf_ndxscn(scn);
3413 		sec_desc = &obj->efile.secs[idx];
3414 
3415 		sh = elf_sec_hdr(obj, scn);
3416 		if (!sh)
3417 			return -LIBBPF_ERRNO__FORMAT;
3418 
3419 		name = elf_sec_str(obj, sh->sh_name);
3420 		if (!name)
3421 			return -LIBBPF_ERRNO__FORMAT;
3422 
3423 		if (ignore_elf_section(sh, name))
3424 			continue;
3425 
3426 		data = elf_sec_data(obj, scn);
3427 		if (!data)
3428 			return -LIBBPF_ERRNO__FORMAT;
3429 
3430 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3431 			 idx, name, (unsigned long)data->d_size,
3432 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3433 			 (int)sh->sh_type);
3434 
3435 		if (strcmp(name, "license") == 0) {
3436 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3437 			if (err)
3438 				return err;
3439 		} else if (strcmp(name, "version") == 0) {
3440 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3441 			if (err)
3442 				return err;
3443 		} else if (strcmp(name, "maps") == 0) {
3444 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3445 			return -ENOTSUP;
3446 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3447 			obj->efile.btf_maps_shndx = idx;
3448 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3449 			if (sh->sh_type != SHT_PROGBITS)
3450 				return -LIBBPF_ERRNO__FORMAT;
3451 			btf_data = data;
3452 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3453 			if (sh->sh_type != SHT_PROGBITS)
3454 				return -LIBBPF_ERRNO__FORMAT;
3455 			btf_ext_data = data;
3456 		} else if (sh->sh_type == SHT_SYMTAB) {
3457 			/* already processed during the first pass above */
3458 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3459 			if (sh->sh_flags & SHF_EXECINSTR) {
3460 				if (strcmp(name, ".text") == 0)
3461 					obj->efile.text_shndx = idx;
3462 				err = bpf_object__add_programs(obj, data, name, idx);
3463 				if (err)
3464 					return err;
3465 			} else if (strcmp(name, DATA_SEC) == 0 ||
3466 				   str_has_pfx(name, DATA_SEC ".")) {
3467 				sec_desc->sec_type = SEC_DATA;
3468 				sec_desc->shdr = sh;
3469 				sec_desc->data = data;
3470 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3471 				   str_has_pfx(name, RODATA_SEC ".")) {
3472 				sec_desc->sec_type = SEC_RODATA;
3473 				sec_desc->shdr = sh;
3474 				sec_desc->data = data;
3475 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3476 				obj->efile.st_ops_data = data;
3477 				obj->efile.st_ops_shndx = idx;
3478 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3479 				obj->efile.st_ops_link_data = data;
3480 				obj->efile.st_ops_link_shndx = idx;
3481 			} else {
3482 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3483 					idx, name);
3484 			}
3485 		} else if (sh->sh_type == SHT_REL) {
3486 			int targ_sec_idx = sh->sh_info; /* points to other section */
3487 
3488 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3489 			    targ_sec_idx >= obj->efile.sec_cnt)
3490 				return -LIBBPF_ERRNO__FORMAT;
3491 
3492 			/* Only do relo for section with exec instructions */
3493 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3494 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3495 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3496 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3497 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3498 					idx, name, targ_sec_idx,
3499 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3500 				continue;
3501 			}
3502 
3503 			sec_desc->sec_type = SEC_RELO;
3504 			sec_desc->shdr = sh;
3505 			sec_desc->data = data;
3506 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3507 							 str_has_pfx(name, BSS_SEC "."))) {
3508 			sec_desc->sec_type = SEC_BSS;
3509 			sec_desc->shdr = sh;
3510 			sec_desc->data = data;
3511 		} else {
3512 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3513 				(size_t)sh->sh_size);
3514 		}
3515 	}
3516 
3517 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3518 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3519 		return -LIBBPF_ERRNO__FORMAT;
3520 	}
3521 
3522 	/* sort BPF programs by section name and in-section instruction offset
3523 	 * for faster search
3524 	 */
3525 	if (obj->nr_programs)
3526 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3527 
3528 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3529 }
3530 
3531 static bool sym_is_extern(const Elf64_Sym *sym)
3532 {
3533 	int bind = ELF64_ST_BIND(sym->st_info);
3534 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3535 	return sym->st_shndx == SHN_UNDEF &&
3536 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3537 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3538 }
3539 
3540 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3541 {
3542 	int bind = ELF64_ST_BIND(sym->st_info);
3543 	int type = ELF64_ST_TYPE(sym->st_info);
3544 
3545 	/* in .text section */
3546 	if (sym->st_shndx != text_shndx)
3547 		return false;
3548 
3549 	/* local function */
3550 	if (bind == STB_LOCAL && type == STT_SECTION)
3551 		return true;
3552 
3553 	/* global function */
3554 	return bind == STB_GLOBAL && type == STT_FUNC;
3555 }
3556 
3557 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3558 {
3559 	const struct btf_type *t;
3560 	const char *tname;
3561 	int i, n;
3562 
3563 	if (!btf)
3564 		return -ESRCH;
3565 
3566 	n = btf__type_cnt(btf);
3567 	for (i = 1; i < n; i++) {
3568 		t = btf__type_by_id(btf, i);
3569 
3570 		if (!btf_is_var(t) && !btf_is_func(t))
3571 			continue;
3572 
3573 		tname = btf__name_by_offset(btf, t->name_off);
3574 		if (strcmp(tname, ext_name))
3575 			continue;
3576 
3577 		if (btf_is_var(t) &&
3578 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3579 			return -EINVAL;
3580 
3581 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3582 			return -EINVAL;
3583 
3584 		return i;
3585 	}
3586 
3587 	return -ENOENT;
3588 }
3589 
3590 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3591 	const struct btf_var_secinfo *vs;
3592 	const struct btf_type *t;
3593 	int i, j, n;
3594 
3595 	if (!btf)
3596 		return -ESRCH;
3597 
3598 	n = btf__type_cnt(btf);
3599 	for (i = 1; i < n; i++) {
3600 		t = btf__type_by_id(btf, i);
3601 
3602 		if (!btf_is_datasec(t))
3603 			continue;
3604 
3605 		vs = btf_var_secinfos(t);
3606 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3607 			if (vs->type == ext_btf_id)
3608 				return i;
3609 		}
3610 	}
3611 
3612 	return -ENOENT;
3613 }
3614 
3615 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3616 				     bool *is_signed)
3617 {
3618 	const struct btf_type *t;
3619 	const char *name;
3620 
3621 	t = skip_mods_and_typedefs(btf, id, NULL);
3622 	name = btf__name_by_offset(btf, t->name_off);
3623 
3624 	if (is_signed)
3625 		*is_signed = false;
3626 	switch (btf_kind(t)) {
3627 	case BTF_KIND_INT: {
3628 		int enc = btf_int_encoding(t);
3629 
3630 		if (enc & BTF_INT_BOOL)
3631 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3632 		if (is_signed)
3633 			*is_signed = enc & BTF_INT_SIGNED;
3634 		if (t->size == 1)
3635 			return KCFG_CHAR;
3636 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3637 			return KCFG_UNKNOWN;
3638 		return KCFG_INT;
3639 	}
3640 	case BTF_KIND_ENUM:
3641 		if (t->size != 4)
3642 			return KCFG_UNKNOWN;
3643 		if (strcmp(name, "libbpf_tristate"))
3644 			return KCFG_UNKNOWN;
3645 		return KCFG_TRISTATE;
3646 	case BTF_KIND_ENUM64:
3647 		if (strcmp(name, "libbpf_tristate"))
3648 			return KCFG_UNKNOWN;
3649 		return KCFG_TRISTATE;
3650 	case BTF_KIND_ARRAY:
3651 		if (btf_array(t)->nelems == 0)
3652 			return KCFG_UNKNOWN;
3653 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3654 			return KCFG_UNKNOWN;
3655 		return KCFG_CHAR_ARR;
3656 	default:
3657 		return KCFG_UNKNOWN;
3658 	}
3659 }
3660 
3661 static int cmp_externs(const void *_a, const void *_b)
3662 {
3663 	const struct extern_desc *a = _a;
3664 	const struct extern_desc *b = _b;
3665 
3666 	if (a->type != b->type)
3667 		return a->type < b->type ? -1 : 1;
3668 
3669 	if (a->type == EXT_KCFG) {
3670 		/* descending order by alignment requirements */
3671 		if (a->kcfg.align != b->kcfg.align)
3672 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3673 		/* ascending order by size, within same alignment class */
3674 		if (a->kcfg.sz != b->kcfg.sz)
3675 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3676 	}
3677 
3678 	/* resolve ties by name */
3679 	return strcmp(a->name, b->name);
3680 }
3681 
3682 static int find_int_btf_id(const struct btf *btf)
3683 {
3684 	const struct btf_type *t;
3685 	int i, n;
3686 
3687 	n = btf__type_cnt(btf);
3688 	for (i = 1; i < n; i++) {
3689 		t = btf__type_by_id(btf, i);
3690 
3691 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3692 			return i;
3693 	}
3694 
3695 	return 0;
3696 }
3697 
3698 static int add_dummy_ksym_var(struct btf *btf)
3699 {
3700 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3701 	const struct btf_var_secinfo *vs;
3702 	const struct btf_type *sec;
3703 
3704 	if (!btf)
3705 		return 0;
3706 
3707 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3708 					    BTF_KIND_DATASEC);
3709 	if (sec_btf_id < 0)
3710 		return 0;
3711 
3712 	sec = btf__type_by_id(btf, sec_btf_id);
3713 	vs = btf_var_secinfos(sec);
3714 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3715 		const struct btf_type *vt;
3716 
3717 		vt = btf__type_by_id(btf, vs->type);
3718 		if (btf_is_func(vt))
3719 			break;
3720 	}
3721 
3722 	/* No func in ksyms sec.  No need to add dummy var. */
3723 	if (i == btf_vlen(sec))
3724 		return 0;
3725 
3726 	int_btf_id = find_int_btf_id(btf);
3727 	dummy_var_btf_id = btf__add_var(btf,
3728 					"dummy_ksym",
3729 					BTF_VAR_GLOBAL_ALLOCATED,
3730 					int_btf_id);
3731 	if (dummy_var_btf_id < 0)
3732 		pr_warn("cannot create a dummy_ksym var\n");
3733 
3734 	return dummy_var_btf_id;
3735 }
3736 
3737 static int bpf_object__collect_externs(struct bpf_object *obj)
3738 {
3739 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3740 	const struct btf_type *t;
3741 	struct extern_desc *ext;
3742 	int i, n, off, dummy_var_btf_id;
3743 	const char *ext_name, *sec_name;
3744 	Elf_Scn *scn;
3745 	Elf64_Shdr *sh;
3746 
3747 	if (!obj->efile.symbols)
3748 		return 0;
3749 
3750 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3751 	sh = elf_sec_hdr(obj, scn);
3752 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3753 		return -LIBBPF_ERRNO__FORMAT;
3754 
3755 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3756 	if (dummy_var_btf_id < 0)
3757 		return dummy_var_btf_id;
3758 
3759 	n = sh->sh_size / sh->sh_entsize;
3760 	pr_debug("looking for externs among %d symbols...\n", n);
3761 
3762 	for (i = 0; i < n; i++) {
3763 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3764 
3765 		if (!sym)
3766 			return -LIBBPF_ERRNO__FORMAT;
3767 		if (!sym_is_extern(sym))
3768 			continue;
3769 		ext_name = elf_sym_str(obj, sym->st_name);
3770 		if (!ext_name || !ext_name[0])
3771 			continue;
3772 
3773 		ext = obj->externs;
3774 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3775 		if (!ext)
3776 			return -ENOMEM;
3777 		obj->externs = ext;
3778 		ext = &ext[obj->nr_extern];
3779 		memset(ext, 0, sizeof(*ext));
3780 		obj->nr_extern++;
3781 
3782 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3783 		if (ext->btf_id <= 0) {
3784 			pr_warn("failed to find BTF for extern '%s': %d\n",
3785 				ext_name, ext->btf_id);
3786 			return ext->btf_id;
3787 		}
3788 		t = btf__type_by_id(obj->btf, ext->btf_id);
3789 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3790 		ext->sym_idx = i;
3791 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3792 
3793 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3794 		if (ext->sec_btf_id <= 0) {
3795 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3796 				ext_name, ext->btf_id, ext->sec_btf_id);
3797 			return ext->sec_btf_id;
3798 		}
3799 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3800 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3801 
3802 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3803 			if (btf_is_func(t)) {
3804 				pr_warn("extern function %s is unsupported under %s section\n",
3805 					ext->name, KCONFIG_SEC);
3806 				return -ENOTSUP;
3807 			}
3808 			kcfg_sec = sec;
3809 			ext->type = EXT_KCFG;
3810 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3811 			if (ext->kcfg.sz <= 0) {
3812 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3813 					ext_name, ext->kcfg.sz);
3814 				return ext->kcfg.sz;
3815 			}
3816 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3817 			if (ext->kcfg.align <= 0) {
3818 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3819 					ext_name, ext->kcfg.align);
3820 				return -EINVAL;
3821 			}
3822 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3823 							&ext->kcfg.is_signed);
3824 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3825 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3826 				return -ENOTSUP;
3827 			}
3828 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3829 			ksym_sec = sec;
3830 			ext->type = EXT_KSYM;
3831 			skip_mods_and_typedefs(obj->btf, t->type,
3832 					       &ext->ksym.type_id);
3833 		} else {
3834 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3835 			return -ENOTSUP;
3836 		}
3837 	}
3838 	pr_debug("collected %d externs total\n", obj->nr_extern);
3839 
3840 	if (!obj->nr_extern)
3841 		return 0;
3842 
3843 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3844 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3845 
3846 	/* for .ksyms section, we need to turn all externs into allocated
3847 	 * variables in BTF to pass kernel verification; we do this by
3848 	 * pretending that each extern is a 8-byte variable
3849 	 */
3850 	if (ksym_sec) {
3851 		/* find existing 4-byte integer type in BTF to use for fake
3852 		 * extern variables in DATASEC
3853 		 */
3854 		int int_btf_id = find_int_btf_id(obj->btf);
3855 		/* For extern function, a dummy_var added earlier
3856 		 * will be used to replace the vs->type and
3857 		 * its name string will be used to refill
3858 		 * the missing param's name.
3859 		 */
3860 		const struct btf_type *dummy_var;
3861 
3862 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3863 		for (i = 0; i < obj->nr_extern; i++) {
3864 			ext = &obj->externs[i];
3865 			if (ext->type != EXT_KSYM)
3866 				continue;
3867 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3868 				 i, ext->sym_idx, ext->name);
3869 		}
3870 
3871 		sec = ksym_sec;
3872 		n = btf_vlen(sec);
3873 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3874 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3875 			struct btf_type *vt;
3876 
3877 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3878 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3879 			ext = find_extern_by_name(obj, ext_name);
3880 			if (!ext) {
3881 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3882 					btf_kind_str(vt), ext_name);
3883 				return -ESRCH;
3884 			}
3885 			if (btf_is_func(vt)) {
3886 				const struct btf_type *func_proto;
3887 				struct btf_param *param;
3888 				int j;
3889 
3890 				func_proto = btf__type_by_id(obj->btf,
3891 							     vt->type);
3892 				param = btf_params(func_proto);
3893 				/* Reuse the dummy_var string if the
3894 				 * func proto does not have param name.
3895 				 */
3896 				for (j = 0; j < btf_vlen(func_proto); j++)
3897 					if (param[j].type && !param[j].name_off)
3898 						param[j].name_off =
3899 							dummy_var->name_off;
3900 				vs->type = dummy_var_btf_id;
3901 				vt->info &= ~0xffff;
3902 				vt->info |= BTF_FUNC_GLOBAL;
3903 			} else {
3904 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3905 				vt->type = int_btf_id;
3906 			}
3907 			vs->offset = off;
3908 			vs->size = sizeof(int);
3909 		}
3910 		sec->size = off;
3911 	}
3912 
3913 	if (kcfg_sec) {
3914 		sec = kcfg_sec;
3915 		/* for kcfg externs calculate their offsets within a .kconfig map */
3916 		off = 0;
3917 		for (i = 0; i < obj->nr_extern; i++) {
3918 			ext = &obj->externs[i];
3919 			if (ext->type != EXT_KCFG)
3920 				continue;
3921 
3922 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3923 			off = ext->kcfg.data_off + ext->kcfg.sz;
3924 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3925 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3926 		}
3927 		sec->size = off;
3928 		n = btf_vlen(sec);
3929 		for (i = 0; i < n; i++) {
3930 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3931 
3932 			t = btf__type_by_id(obj->btf, vs->type);
3933 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3934 			ext = find_extern_by_name(obj, ext_name);
3935 			if (!ext) {
3936 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3937 					ext_name);
3938 				return -ESRCH;
3939 			}
3940 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3941 			vs->offset = ext->kcfg.data_off;
3942 		}
3943 	}
3944 	return 0;
3945 }
3946 
3947 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3948 {
3949 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3950 }
3951 
3952 struct bpf_program *
3953 bpf_object__find_program_by_name(const struct bpf_object *obj,
3954 				 const char *name)
3955 {
3956 	struct bpf_program *prog;
3957 
3958 	bpf_object__for_each_program(prog, obj) {
3959 		if (prog_is_subprog(obj, prog))
3960 			continue;
3961 		if (!strcmp(prog->name, name))
3962 			return prog;
3963 	}
3964 	return errno = ENOENT, NULL;
3965 }
3966 
3967 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3968 				      int shndx)
3969 {
3970 	switch (obj->efile.secs[shndx].sec_type) {
3971 	case SEC_BSS:
3972 	case SEC_DATA:
3973 	case SEC_RODATA:
3974 		return true;
3975 	default:
3976 		return false;
3977 	}
3978 }
3979 
3980 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3981 				      int shndx)
3982 {
3983 	return shndx == obj->efile.btf_maps_shndx;
3984 }
3985 
3986 static enum libbpf_map_type
3987 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3988 {
3989 	if (shndx == obj->efile.symbols_shndx)
3990 		return LIBBPF_MAP_KCONFIG;
3991 
3992 	switch (obj->efile.secs[shndx].sec_type) {
3993 	case SEC_BSS:
3994 		return LIBBPF_MAP_BSS;
3995 	case SEC_DATA:
3996 		return LIBBPF_MAP_DATA;
3997 	case SEC_RODATA:
3998 		return LIBBPF_MAP_RODATA;
3999 	default:
4000 		return LIBBPF_MAP_UNSPEC;
4001 	}
4002 }
4003 
4004 static int bpf_program__record_reloc(struct bpf_program *prog,
4005 				     struct reloc_desc *reloc_desc,
4006 				     __u32 insn_idx, const char *sym_name,
4007 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4008 {
4009 	struct bpf_insn *insn = &prog->insns[insn_idx];
4010 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4011 	struct bpf_object *obj = prog->obj;
4012 	__u32 shdr_idx = sym->st_shndx;
4013 	enum libbpf_map_type type;
4014 	const char *sym_sec_name;
4015 	struct bpf_map *map;
4016 
4017 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4018 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4019 			prog->name, sym_name, insn_idx, insn->code);
4020 		return -LIBBPF_ERRNO__RELOC;
4021 	}
4022 
4023 	if (sym_is_extern(sym)) {
4024 		int sym_idx = ELF64_R_SYM(rel->r_info);
4025 		int i, n = obj->nr_extern;
4026 		struct extern_desc *ext;
4027 
4028 		for (i = 0; i < n; i++) {
4029 			ext = &obj->externs[i];
4030 			if (ext->sym_idx == sym_idx)
4031 				break;
4032 		}
4033 		if (i >= n) {
4034 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4035 				prog->name, sym_name, sym_idx);
4036 			return -LIBBPF_ERRNO__RELOC;
4037 		}
4038 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4039 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4040 		if (insn->code == (BPF_JMP | BPF_CALL))
4041 			reloc_desc->type = RELO_EXTERN_CALL;
4042 		else
4043 			reloc_desc->type = RELO_EXTERN_LD64;
4044 		reloc_desc->insn_idx = insn_idx;
4045 		reloc_desc->sym_off = i; /* sym_off stores extern index */
4046 		return 0;
4047 	}
4048 
4049 	/* sub-program call relocation */
4050 	if (is_call_insn(insn)) {
4051 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4052 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4053 			return -LIBBPF_ERRNO__RELOC;
4054 		}
4055 		/* text_shndx can be 0, if no default "main" program exists */
4056 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4057 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4058 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4059 				prog->name, sym_name, sym_sec_name);
4060 			return -LIBBPF_ERRNO__RELOC;
4061 		}
4062 		if (sym->st_value % BPF_INSN_SZ) {
4063 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4064 				prog->name, sym_name, (size_t)sym->st_value);
4065 			return -LIBBPF_ERRNO__RELOC;
4066 		}
4067 		reloc_desc->type = RELO_CALL;
4068 		reloc_desc->insn_idx = insn_idx;
4069 		reloc_desc->sym_off = sym->st_value;
4070 		return 0;
4071 	}
4072 
4073 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4074 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4075 			prog->name, sym_name, shdr_idx);
4076 		return -LIBBPF_ERRNO__RELOC;
4077 	}
4078 
4079 	/* loading subprog addresses */
4080 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4081 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4082 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4083 		 */
4084 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4085 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4086 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4087 			return -LIBBPF_ERRNO__RELOC;
4088 		}
4089 
4090 		reloc_desc->type = RELO_SUBPROG_ADDR;
4091 		reloc_desc->insn_idx = insn_idx;
4092 		reloc_desc->sym_off = sym->st_value;
4093 		return 0;
4094 	}
4095 
4096 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4097 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4098 
4099 	/* generic map reference relocation */
4100 	if (type == LIBBPF_MAP_UNSPEC) {
4101 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4102 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4103 				prog->name, sym_name, sym_sec_name);
4104 			return -LIBBPF_ERRNO__RELOC;
4105 		}
4106 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4107 			map = &obj->maps[map_idx];
4108 			if (map->libbpf_type != type ||
4109 			    map->sec_idx != sym->st_shndx ||
4110 			    map->sec_offset != sym->st_value)
4111 				continue;
4112 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4113 				 prog->name, map_idx, map->name, map->sec_idx,
4114 				 map->sec_offset, insn_idx);
4115 			break;
4116 		}
4117 		if (map_idx >= nr_maps) {
4118 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4119 				prog->name, sym_sec_name, (size_t)sym->st_value);
4120 			return -LIBBPF_ERRNO__RELOC;
4121 		}
4122 		reloc_desc->type = RELO_LD64;
4123 		reloc_desc->insn_idx = insn_idx;
4124 		reloc_desc->map_idx = map_idx;
4125 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4126 		return 0;
4127 	}
4128 
4129 	/* global data map relocation */
4130 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4131 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4132 			prog->name, sym_sec_name);
4133 		return -LIBBPF_ERRNO__RELOC;
4134 	}
4135 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4136 		map = &obj->maps[map_idx];
4137 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4138 			continue;
4139 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4140 			 prog->name, map_idx, map->name, map->sec_idx,
4141 			 map->sec_offset, insn_idx);
4142 		break;
4143 	}
4144 	if (map_idx >= nr_maps) {
4145 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4146 			prog->name, sym_sec_name);
4147 		return -LIBBPF_ERRNO__RELOC;
4148 	}
4149 
4150 	reloc_desc->type = RELO_DATA;
4151 	reloc_desc->insn_idx = insn_idx;
4152 	reloc_desc->map_idx = map_idx;
4153 	reloc_desc->sym_off = sym->st_value;
4154 	return 0;
4155 }
4156 
4157 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4158 {
4159 	return insn_idx >= prog->sec_insn_off &&
4160 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4161 }
4162 
4163 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4164 						 size_t sec_idx, size_t insn_idx)
4165 {
4166 	int l = 0, r = obj->nr_programs - 1, m;
4167 	struct bpf_program *prog;
4168 
4169 	if (!obj->nr_programs)
4170 		return NULL;
4171 
4172 	while (l < r) {
4173 		m = l + (r - l + 1) / 2;
4174 		prog = &obj->programs[m];
4175 
4176 		if (prog->sec_idx < sec_idx ||
4177 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4178 			l = m;
4179 		else
4180 			r = m - 1;
4181 	}
4182 	/* matching program could be at index l, but it still might be the
4183 	 * wrong one, so we need to double check conditions for the last time
4184 	 */
4185 	prog = &obj->programs[l];
4186 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4187 		return prog;
4188 	return NULL;
4189 }
4190 
4191 static int
4192 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4193 {
4194 	const char *relo_sec_name, *sec_name;
4195 	size_t sec_idx = shdr->sh_info, sym_idx;
4196 	struct bpf_program *prog;
4197 	struct reloc_desc *relos;
4198 	int err, i, nrels;
4199 	const char *sym_name;
4200 	__u32 insn_idx;
4201 	Elf_Scn *scn;
4202 	Elf_Data *scn_data;
4203 	Elf64_Sym *sym;
4204 	Elf64_Rel *rel;
4205 
4206 	if (sec_idx >= obj->efile.sec_cnt)
4207 		return -EINVAL;
4208 
4209 	scn = elf_sec_by_idx(obj, sec_idx);
4210 	scn_data = elf_sec_data(obj, scn);
4211 
4212 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4213 	sec_name = elf_sec_name(obj, scn);
4214 	if (!relo_sec_name || !sec_name)
4215 		return -EINVAL;
4216 
4217 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4218 		 relo_sec_name, sec_idx, sec_name);
4219 	nrels = shdr->sh_size / shdr->sh_entsize;
4220 
4221 	for (i = 0; i < nrels; i++) {
4222 		rel = elf_rel_by_idx(data, i);
4223 		if (!rel) {
4224 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4225 			return -LIBBPF_ERRNO__FORMAT;
4226 		}
4227 
4228 		sym_idx = ELF64_R_SYM(rel->r_info);
4229 		sym = elf_sym_by_idx(obj, sym_idx);
4230 		if (!sym) {
4231 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4232 				relo_sec_name, sym_idx, i);
4233 			return -LIBBPF_ERRNO__FORMAT;
4234 		}
4235 
4236 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4237 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4238 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4239 			return -LIBBPF_ERRNO__FORMAT;
4240 		}
4241 
4242 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4243 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4244 				relo_sec_name, (size_t)rel->r_offset, i);
4245 			return -LIBBPF_ERRNO__FORMAT;
4246 		}
4247 
4248 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4249 		/* relocations against static functions are recorded as
4250 		 * relocations against the section that contains a function;
4251 		 * in such case, symbol will be STT_SECTION and sym.st_name
4252 		 * will point to empty string (0), so fetch section name
4253 		 * instead
4254 		 */
4255 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4256 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4257 		else
4258 			sym_name = elf_sym_str(obj, sym->st_name);
4259 		sym_name = sym_name ?: "<?";
4260 
4261 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4262 			 relo_sec_name, i, insn_idx, sym_name);
4263 
4264 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4265 		if (!prog) {
4266 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4267 				relo_sec_name, i, sec_name, insn_idx);
4268 			continue;
4269 		}
4270 
4271 		relos = libbpf_reallocarray(prog->reloc_desc,
4272 					    prog->nr_reloc + 1, sizeof(*relos));
4273 		if (!relos)
4274 			return -ENOMEM;
4275 		prog->reloc_desc = relos;
4276 
4277 		/* adjust insn_idx to local BPF program frame of reference */
4278 		insn_idx -= prog->sec_insn_off;
4279 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4280 						insn_idx, sym_name, sym, rel);
4281 		if (err)
4282 			return err;
4283 
4284 		prog->nr_reloc++;
4285 	}
4286 	return 0;
4287 }
4288 
4289 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4290 {
4291 	int id;
4292 
4293 	if (!obj->btf)
4294 		return -ENOENT;
4295 
4296 	/* if it's BTF-defined map, we don't need to search for type IDs.
4297 	 * For struct_ops map, it does not need btf_key_type_id and
4298 	 * btf_value_type_id.
4299 	 */
4300 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4301 		return 0;
4302 
4303 	/*
4304 	 * LLVM annotates global data differently in BTF, that is,
4305 	 * only as '.data', '.bss' or '.rodata'.
4306 	 */
4307 	if (!bpf_map__is_internal(map))
4308 		return -ENOENT;
4309 
4310 	id = btf__find_by_name(obj->btf, map->real_name);
4311 	if (id < 0)
4312 		return id;
4313 
4314 	map->btf_key_type_id = 0;
4315 	map->btf_value_type_id = id;
4316 	return 0;
4317 }
4318 
4319 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4320 {
4321 	char file[PATH_MAX], buff[4096];
4322 	FILE *fp;
4323 	__u32 val;
4324 	int err;
4325 
4326 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4327 	memset(info, 0, sizeof(*info));
4328 
4329 	fp = fopen(file, "r");
4330 	if (!fp) {
4331 		err = -errno;
4332 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4333 			err);
4334 		return err;
4335 	}
4336 
4337 	while (fgets(buff, sizeof(buff), fp)) {
4338 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4339 			info->type = val;
4340 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4341 			info->key_size = val;
4342 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4343 			info->value_size = val;
4344 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4345 			info->max_entries = val;
4346 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4347 			info->map_flags = val;
4348 	}
4349 
4350 	fclose(fp);
4351 
4352 	return 0;
4353 }
4354 
4355 bool bpf_map__autocreate(const struct bpf_map *map)
4356 {
4357 	return map->autocreate;
4358 }
4359 
4360 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4361 {
4362 	if (map->obj->loaded)
4363 		return libbpf_err(-EBUSY);
4364 
4365 	map->autocreate = autocreate;
4366 	return 0;
4367 }
4368 
4369 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4370 {
4371 	struct bpf_map_info info;
4372 	__u32 len = sizeof(info), name_len;
4373 	int new_fd, err;
4374 	char *new_name;
4375 
4376 	memset(&info, 0, len);
4377 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4378 	if (err && errno == EINVAL)
4379 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4380 	if (err)
4381 		return libbpf_err(err);
4382 
4383 	name_len = strlen(info.name);
4384 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4385 		new_name = strdup(map->name);
4386 	else
4387 		new_name = strdup(info.name);
4388 
4389 	if (!new_name)
4390 		return libbpf_err(-errno);
4391 
4392 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4393 	if (new_fd < 0) {
4394 		err = -errno;
4395 		goto err_free_new_name;
4396 	}
4397 
4398 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4399 	if (new_fd < 0) {
4400 		err = -errno;
4401 		goto err_close_new_fd;
4402 	}
4403 
4404 	err = zclose(map->fd);
4405 	if (err) {
4406 		err = -errno;
4407 		goto err_close_new_fd;
4408 	}
4409 	free(map->name);
4410 
4411 	map->fd = new_fd;
4412 	map->name = new_name;
4413 	map->def.type = info.type;
4414 	map->def.key_size = info.key_size;
4415 	map->def.value_size = info.value_size;
4416 	map->def.max_entries = info.max_entries;
4417 	map->def.map_flags = info.map_flags;
4418 	map->btf_key_type_id = info.btf_key_type_id;
4419 	map->btf_value_type_id = info.btf_value_type_id;
4420 	map->reused = true;
4421 	map->map_extra = info.map_extra;
4422 
4423 	return 0;
4424 
4425 err_close_new_fd:
4426 	close(new_fd);
4427 err_free_new_name:
4428 	free(new_name);
4429 	return libbpf_err(err);
4430 }
4431 
4432 __u32 bpf_map__max_entries(const struct bpf_map *map)
4433 {
4434 	return map->def.max_entries;
4435 }
4436 
4437 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4438 {
4439 	if (!bpf_map_type__is_map_in_map(map->def.type))
4440 		return errno = EINVAL, NULL;
4441 
4442 	return map->inner_map;
4443 }
4444 
4445 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4446 {
4447 	if (map->obj->loaded)
4448 		return libbpf_err(-EBUSY);
4449 
4450 	map->def.max_entries = max_entries;
4451 
4452 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4453 	if (map_is_ringbuf(map))
4454 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4455 
4456 	return 0;
4457 }
4458 
4459 static int
4460 bpf_object__probe_loading(struct bpf_object *obj)
4461 {
4462 	char *cp, errmsg[STRERR_BUFSIZE];
4463 	struct bpf_insn insns[] = {
4464 		BPF_MOV64_IMM(BPF_REG_0, 0),
4465 		BPF_EXIT_INSN(),
4466 	};
4467 	int ret, insn_cnt = ARRAY_SIZE(insns);
4468 
4469 	if (obj->gen_loader)
4470 		return 0;
4471 
4472 	ret = bump_rlimit_memlock();
4473 	if (ret)
4474 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4475 
4476 	/* make sure basic loading works */
4477 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4478 	if (ret < 0)
4479 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4480 	if (ret < 0) {
4481 		ret = errno;
4482 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4483 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4484 			"program. Make sure your kernel supports BPF "
4485 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4486 			"set to big enough value.\n", __func__, cp, ret);
4487 		return -ret;
4488 	}
4489 	close(ret);
4490 
4491 	return 0;
4492 }
4493 
4494 static int probe_fd(int fd)
4495 {
4496 	if (fd >= 0)
4497 		close(fd);
4498 	return fd >= 0;
4499 }
4500 
4501 static int probe_kern_prog_name(void)
4502 {
4503 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4504 	struct bpf_insn insns[] = {
4505 		BPF_MOV64_IMM(BPF_REG_0, 0),
4506 		BPF_EXIT_INSN(),
4507 	};
4508 	union bpf_attr attr;
4509 	int ret;
4510 
4511 	memset(&attr, 0, attr_sz);
4512 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4513 	attr.license = ptr_to_u64("GPL");
4514 	attr.insns = ptr_to_u64(insns);
4515 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4516 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4517 
4518 	/* make sure loading with name works */
4519 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4520 	return probe_fd(ret);
4521 }
4522 
4523 static int probe_kern_global_data(void)
4524 {
4525 	char *cp, errmsg[STRERR_BUFSIZE];
4526 	struct bpf_insn insns[] = {
4527 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4528 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4529 		BPF_MOV64_IMM(BPF_REG_0, 0),
4530 		BPF_EXIT_INSN(),
4531 	};
4532 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4533 
4534 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4535 	if (map < 0) {
4536 		ret = -errno;
4537 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4538 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4539 			__func__, cp, -ret);
4540 		return ret;
4541 	}
4542 
4543 	insns[0].imm = map;
4544 
4545 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4546 	close(map);
4547 	return probe_fd(ret);
4548 }
4549 
4550 static int probe_kern_btf(void)
4551 {
4552 	static const char strs[] = "\0int";
4553 	__u32 types[] = {
4554 		/* int */
4555 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4556 	};
4557 
4558 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4559 					     strs, sizeof(strs)));
4560 }
4561 
4562 static int probe_kern_btf_func(void)
4563 {
4564 	static const char strs[] = "\0int\0x\0a";
4565 	/* void x(int a) {} */
4566 	__u32 types[] = {
4567 		/* int */
4568 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4569 		/* FUNC_PROTO */                                /* [2] */
4570 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4571 		BTF_PARAM_ENC(7, 1),
4572 		/* FUNC x */                                    /* [3] */
4573 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4574 	};
4575 
4576 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4577 					     strs, sizeof(strs)));
4578 }
4579 
4580 static int probe_kern_btf_func_global(void)
4581 {
4582 	static const char strs[] = "\0int\0x\0a";
4583 	/* static void x(int a) {} */
4584 	__u32 types[] = {
4585 		/* int */
4586 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4587 		/* FUNC_PROTO */                                /* [2] */
4588 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4589 		BTF_PARAM_ENC(7, 1),
4590 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4591 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4592 	};
4593 
4594 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4595 					     strs, sizeof(strs)));
4596 }
4597 
4598 static int probe_kern_btf_datasec(void)
4599 {
4600 	static const char strs[] = "\0x\0.data";
4601 	/* static int a; */
4602 	__u32 types[] = {
4603 		/* int */
4604 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4605 		/* VAR x */                                     /* [2] */
4606 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4607 		BTF_VAR_STATIC,
4608 		/* DATASEC val */                               /* [3] */
4609 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4610 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4611 	};
4612 
4613 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4614 					     strs, sizeof(strs)));
4615 }
4616 
4617 static int probe_kern_btf_float(void)
4618 {
4619 	static const char strs[] = "\0float";
4620 	__u32 types[] = {
4621 		/* float */
4622 		BTF_TYPE_FLOAT_ENC(1, 4),
4623 	};
4624 
4625 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4626 					     strs, sizeof(strs)));
4627 }
4628 
4629 static int probe_kern_btf_decl_tag(void)
4630 {
4631 	static const char strs[] = "\0tag";
4632 	__u32 types[] = {
4633 		/* int */
4634 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4635 		/* VAR x */                                     /* [2] */
4636 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4637 		BTF_VAR_STATIC,
4638 		/* attr */
4639 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4640 	};
4641 
4642 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4643 					     strs, sizeof(strs)));
4644 }
4645 
4646 static int probe_kern_btf_type_tag(void)
4647 {
4648 	static const char strs[] = "\0tag";
4649 	__u32 types[] = {
4650 		/* int */
4651 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4652 		/* attr */
4653 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4654 		/* ptr */
4655 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4656 	};
4657 
4658 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4659 					     strs, sizeof(strs)));
4660 }
4661 
4662 static int probe_kern_array_mmap(void)
4663 {
4664 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4665 	int fd;
4666 
4667 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4668 	return probe_fd(fd);
4669 }
4670 
4671 static int probe_kern_exp_attach_type(void)
4672 {
4673 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4674 	struct bpf_insn insns[] = {
4675 		BPF_MOV64_IMM(BPF_REG_0, 0),
4676 		BPF_EXIT_INSN(),
4677 	};
4678 	int fd, insn_cnt = ARRAY_SIZE(insns);
4679 
4680 	/* use any valid combination of program type and (optional)
4681 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4682 	 * to see if kernel supports expected_attach_type field for
4683 	 * BPF_PROG_LOAD command
4684 	 */
4685 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4686 	return probe_fd(fd);
4687 }
4688 
4689 static int probe_kern_probe_read_kernel(void)
4690 {
4691 	struct bpf_insn insns[] = {
4692 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4693 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4694 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4695 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4696 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4697 		BPF_EXIT_INSN(),
4698 	};
4699 	int fd, insn_cnt = ARRAY_SIZE(insns);
4700 
4701 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4702 	return probe_fd(fd);
4703 }
4704 
4705 static int probe_prog_bind_map(void)
4706 {
4707 	char *cp, errmsg[STRERR_BUFSIZE];
4708 	struct bpf_insn insns[] = {
4709 		BPF_MOV64_IMM(BPF_REG_0, 0),
4710 		BPF_EXIT_INSN(),
4711 	};
4712 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4713 
4714 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4715 	if (map < 0) {
4716 		ret = -errno;
4717 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4718 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4719 			__func__, cp, -ret);
4720 		return ret;
4721 	}
4722 
4723 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4724 	if (prog < 0) {
4725 		close(map);
4726 		return 0;
4727 	}
4728 
4729 	ret = bpf_prog_bind_map(prog, map, NULL);
4730 
4731 	close(map);
4732 	close(prog);
4733 
4734 	return ret >= 0;
4735 }
4736 
4737 static int probe_module_btf(void)
4738 {
4739 	static const char strs[] = "\0int";
4740 	__u32 types[] = {
4741 		/* int */
4742 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4743 	};
4744 	struct bpf_btf_info info;
4745 	__u32 len = sizeof(info);
4746 	char name[16];
4747 	int fd, err;
4748 
4749 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4750 	if (fd < 0)
4751 		return 0; /* BTF not supported at all */
4752 
4753 	memset(&info, 0, sizeof(info));
4754 	info.name = ptr_to_u64(name);
4755 	info.name_len = sizeof(name);
4756 
4757 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4758 	 * kernel's module BTF support coincides with support for
4759 	 * name/name_len fields in struct bpf_btf_info.
4760 	 */
4761 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4762 	close(fd);
4763 	return !err;
4764 }
4765 
4766 static int probe_perf_link(void)
4767 {
4768 	struct bpf_insn insns[] = {
4769 		BPF_MOV64_IMM(BPF_REG_0, 0),
4770 		BPF_EXIT_INSN(),
4771 	};
4772 	int prog_fd, link_fd, err;
4773 
4774 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4775 				insns, ARRAY_SIZE(insns), NULL);
4776 	if (prog_fd < 0)
4777 		return -errno;
4778 
4779 	/* use invalid perf_event FD to get EBADF, if link is supported;
4780 	 * otherwise EINVAL should be returned
4781 	 */
4782 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4783 	err = -errno; /* close() can clobber errno */
4784 
4785 	if (link_fd >= 0)
4786 		close(link_fd);
4787 	close(prog_fd);
4788 
4789 	return link_fd < 0 && err == -EBADF;
4790 }
4791 
4792 static int probe_kern_bpf_cookie(void)
4793 {
4794 	struct bpf_insn insns[] = {
4795 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4796 		BPF_EXIT_INSN(),
4797 	};
4798 	int ret, insn_cnt = ARRAY_SIZE(insns);
4799 
4800 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4801 	return probe_fd(ret);
4802 }
4803 
4804 static int probe_kern_btf_enum64(void)
4805 {
4806 	static const char strs[] = "\0enum64";
4807 	__u32 types[] = {
4808 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4809 	};
4810 
4811 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4812 					     strs, sizeof(strs)));
4813 }
4814 
4815 static int probe_kern_syscall_wrapper(void);
4816 
4817 enum kern_feature_result {
4818 	FEAT_UNKNOWN = 0,
4819 	FEAT_SUPPORTED = 1,
4820 	FEAT_MISSING = 2,
4821 };
4822 
4823 typedef int (*feature_probe_fn)(void);
4824 
4825 static struct kern_feature_desc {
4826 	const char *desc;
4827 	feature_probe_fn probe;
4828 	enum kern_feature_result res;
4829 } feature_probes[__FEAT_CNT] = {
4830 	[FEAT_PROG_NAME] = {
4831 		"BPF program name", probe_kern_prog_name,
4832 	},
4833 	[FEAT_GLOBAL_DATA] = {
4834 		"global variables", probe_kern_global_data,
4835 	},
4836 	[FEAT_BTF] = {
4837 		"minimal BTF", probe_kern_btf,
4838 	},
4839 	[FEAT_BTF_FUNC] = {
4840 		"BTF functions", probe_kern_btf_func,
4841 	},
4842 	[FEAT_BTF_GLOBAL_FUNC] = {
4843 		"BTF global function", probe_kern_btf_func_global,
4844 	},
4845 	[FEAT_BTF_DATASEC] = {
4846 		"BTF data section and variable", probe_kern_btf_datasec,
4847 	},
4848 	[FEAT_ARRAY_MMAP] = {
4849 		"ARRAY map mmap()", probe_kern_array_mmap,
4850 	},
4851 	[FEAT_EXP_ATTACH_TYPE] = {
4852 		"BPF_PROG_LOAD expected_attach_type attribute",
4853 		probe_kern_exp_attach_type,
4854 	},
4855 	[FEAT_PROBE_READ_KERN] = {
4856 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4857 	},
4858 	[FEAT_PROG_BIND_MAP] = {
4859 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4860 	},
4861 	[FEAT_MODULE_BTF] = {
4862 		"module BTF support", probe_module_btf,
4863 	},
4864 	[FEAT_BTF_FLOAT] = {
4865 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4866 	},
4867 	[FEAT_PERF_LINK] = {
4868 		"BPF perf link support", probe_perf_link,
4869 	},
4870 	[FEAT_BTF_DECL_TAG] = {
4871 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4872 	},
4873 	[FEAT_BTF_TYPE_TAG] = {
4874 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4875 	},
4876 	[FEAT_MEMCG_ACCOUNT] = {
4877 		"memcg-based memory accounting", probe_memcg_account,
4878 	},
4879 	[FEAT_BPF_COOKIE] = {
4880 		"BPF cookie support", probe_kern_bpf_cookie,
4881 	},
4882 	[FEAT_BTF_ENUM64] = {
4883 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4884 	},
4885 	[FEAT_SYSCALL_WRAPPER] = {
4886 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4887 	},
4888 };
4889 
4890 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4891 {
4892 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4893 	int ret;
4894 
4895 	if (obj && obj->gen_loader)
4896 		/* To generate loader program assume the latest kernel
4897 		 * to avoid doing extra prog_load, map_create syscalls.
4898 		 */
4899 		return true;
4900 
4901 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4902 		ret = feat->probe();
4903 		if (ret > 0) {
4904 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4905 		} else if (ret == 0) {
4906 			WRITE_ONCE(feat->res, FEAT_MISSING);
4907 		} else {
4908 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4909 			WRITE_ONCE(feat->res, FEAT_MISSING);
4910 		}
4911 	}
4912 
4913 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4914 }
4915 
4916 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4917 {
4918 	struct bpf_map_info map_info;
4919 	char msg[STRERR_BUFSIZE];
4920 	__u32 map_info_len = sizeof(map_info);
4921 	int err;
4922 
4923 	memset(&map_info, 0, map_info_len);
4924 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4925 	if (err && errno == EINVAL)
4926 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4927 	if (err) {
4928 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4929 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4930 		return false;
4931 	}
4932 
4933 	return (map_info.type == map->def.type &&
4934 		map_info.key_size == map->def.key_size &&
4935 		map_info.value_size == map->def.value_size &&
4936 		map_info.max_entries == map->def.max_entries &&
4937 		map_info.map_flags == map->def.map_flags &&
4938 		map_info.map_extra == map->map_extra);
4939 }
4940 
4941 static int
4942 bpf_object__reuse_map(struct bpf_map *map)
4943 {
4944 	char *cp, errmsg[STRERR_BUFSIZE];
4945 	int err, pin_fd;
4946 
4947 	pin_fd = bpf_obj_get(map->pin_path);
4948 	if (pin_fd < 0) {
4949 		err = -errno;
4950 		if (err == -ENOENT) {
4951 			pr_debug("found no pinned map to reuse at '%s'\n",
4952 				 map->pin_path);
4953 			return 0;
4954 		}
4955 
4956 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4957 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4958 			map->pin_path, cp);
4959 		return err;
4960 	}
4961 
4962 	if (!map_is_reuse_compat(map, pin_fd)) {
4963 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4964 			map->pin_path);
4965 		close(pin_fd);
4966 		return -EINVAL;
4967 	}
4968 
4969 	err = bpf_map__reuse_fd(map, pin_fd);
4970 	close(pin_fd);
4971 	if (err)
4972 		return err;
4973 
4974 	map->pinned = true;
4975 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4976 
4977 	return 0;
4978 }
4979 
4980 static int
4981 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4982 {
4983 	enum libbpf_map_type map_type = map->libbpf_type;
4984 	char *cp, errmsg[STRERR_BUFSIZE];
4985 	int err, zero = 0;
4986 
4987 	if (obj->gen_loader) {
4988 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4989 					 map->mmaped, map->def.value_size);
4990 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4991 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4992 		return 0;
4993 	}
4994 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4995 	if (err) {
4996 		err = -errno;
4997 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4998 		pr_warn("Error setting initial map(%s) contents: %s\n",
4999 			map->name, cp);
5000 		return err;
5001 	}
5002 
5003 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5004 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5005 		err = bpf_map_freeze(map->fd);
5006 		if (err) {
5007 			err = -errno;
5008 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5009 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5010 				map->name, cp);
5011 			return err;
5012 		}
5013 	}
5014 	return 0;
5015 }
5016 
5017 static void bpf_map__destroy(struct bpf_map *map);
5018 
5019 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5020 {
5021 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5022 	struct bpf_map_def *def = &map->def;
5023 	const char *map_name = NULL;
5024 	int err = 0;
5025 
5026 	if (kernel_supports(obj, FEAT_PROG_NAME))
5027 		map_name = map->name;
5028 	create_attr.map_ifindex = map->map_ifindex;
5029 	create_attr.map_flags = def->map_flags;
5030 	create_attr.numa_node = map->numa_node;
5031 	create_attr.map_extra = map->map_extra;
5032 
5033 	if (bpf_map__is_struct_ops(map))
5034 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5035 
5036 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5037 		create_attr.btf_fd = btf__fd(obj->btf);
5038 		create_attr.btf_key_type_id = map->btf_key_type_id;
5039 		create_attr.btf_value_type_id = map->btf_value_type_id;
5040 	}
5041 
5042 	if (bpf_map_type__is_map_in_map(def->type)) {
5043 		if (map->inner_map) {
5044 			err = bpf_object__create_map(obj, map->inner_map, true);
5045 			if (err) {
5046 				pr_warn("map '%s': failed to create inner map: %d\n",
5047 					map->name, err);
5048 				return err;
5049 			}
5050 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5051 		}
5052 		if (map->inner_map_fd >= 0)
5053 			create_attr.inner_map_fd = map->inner_map_fd;
5054 	}
5055 
5056 	switch (def->type) {
5057 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5058 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5059 	case BPF_MAP_TYPE_STACK_TRACE:
5060 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5061 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5062 	case BPF_MAP_TYPE_DEVMAP:
5063 	case BPF_MAP_TYPE_DEVMAP_HASH:
5064 	case BPF_MAP_TYPE_CPUMAP:
5065 	case BPF_MAP_TYPE_XSKMAP:
5066 	case BPF_MAP_TYPE_SOCKMAP:
5067 	case BPF_MAP_TYPE_SOCKHASH:
5068 	case BPF_MAP_TYPE_QUEUE:
5069 	case BPF_MAP_TYPE_STACK:
5070 		create_attr.btf_fd = 0;
5071 		create_attr.btf_key_type_id = 0;
5072 		create_attr.btf_value_type_id = 0;
5073 		map->btf_key_type_id = 0;
5074 		map->btf_value_type_id = 0;
5075 	default:
5076 		break;
5077 	}
5078 
5079 	if (obj->gen_loader) {
5080 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5081 				    def->key_size, def->value_size, def->max_entries,
5082 				    &create_attr, is_inner ? -1 : map - obj->maps);
5083 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5084 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5085 		 */
5086 		map->fd = 0;
5087 	} else {
5088 		map->fd = bpf_map_create(def->type, map_name,
5089 					 def->key_size, def->value_size,
5090 					 def->max_entries, &create_attr);
5091 	}
5092 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5093 			    create_attr.btf_value_type_id)) {
5094 		char *cp, errmsg[STRERR_BUFSIZE];
5095 
5096 		err = -errno;
5097 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5098 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5099 			map->name, cp, err);
5100 		create_attr.btf_fd = 0;
5101 		create_attr.btf_key_type_id = 0;
5102 		create_attr.btf_value_type_id = 0;
5103 		map->btf_key_type_id = 0;
5104 		map->btf_value_type_id = 0;
5105 		map->fd = bpf_map_create(def->type, map_name,
5106 					 def->key_size, def->value_size,
5107 					 def->max_entries, &create_attr);
5108 	}
5109 
5110 	err = map->fd < 0 ? -errno : 0;
5111 
5112 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5113 		if (obj->gen_loader)
5114 			map->inner_map->fd = -1;
5115 		bpf_map__destroy(map->inner_map);
5116 		zfree(&map->inner_map);
5117 	}
5118 
5119 	return err;
5120 }
5121 
5122 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5123 {
5124 	const struct bpf_map *targ_map;
5125 	unsigned int i;
5126 	int fd, err = 0;
5127 
5128 	for (i = 0; i < map->init_slots_sz; i++) {
5129 		if (!map->init_slots[i])
5130 			continue;
5131 
5132 		targ_map = map->init_slots[i];
5133 		fd = bpf_map__fd(targ_map);
5134 
5135 		if (obj->gen_loader) {
5136 			bpf_gen__populate_outer_map(obj->gen_loader,
5137 						    map - obj->maps, i,
5138 						    targ_map - obj->maps);
5139 		} else {
5140 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5141 		}
5142 		if (err) {
5143 			err = -errno;
5144 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5145 				map->name, i, targ_map->name, fd, err);
5146 			return err;
5147 		}
5148 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5149 			 map->name, i, targ_map->name, fd);
5150 	}
5151 
5152 	zfree(&map->init_slots);
5153 	map->init_slots_sz = 0;
5154 
5155 	return 0;
5156 }
5157 
5158 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5159 {
5160 	const struct bpf_program *targ_prog;
5161 	unsigned int i;
5162 	int fd, err;
5163 
5164 	if (obj->gen_loader)
5165 		return -ENOTSUP;
5166 
5167 	for (i = 0; i < map->init_slots_sz; i++) {
5168 		if (!map->init_slots[i])
5169 			continue;
5170 
5171 		targ_prog = map->init_slots[i];
5172 		fd = bpf_program__fd(targ_prog);
5173 
5174 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5175 		if (err) {
5176 			err = -errno;
5177 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5178 				map->name, i, targ_prog->name, fd, err);
5179 			return err;
5180 		}
5181 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5182 			 map->name, i, targ_prog->name, fd);
5183 	}
5184 
5185 	zfree(&map->init_slots);
5186 	map->init_slots_sz = 0;
5187 
5188 	return 0;
5189 }
5190 
5191 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5192 {
5193 	struct bpf_map *map;
5194 	int i, err;
5195 
5196 	for (i = 0; i < obj->nr_maps; i++) {
5197 		map = &obj->maps[i];
5198 
5199 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5200 			continue;
5201 
5202 		err = init_prog_array_slots(obj, map);
5203 		if (err < 0) {
5204 			zclose(map->fd);
5205 			return err;
5206 		}
5207 	}
5208 	return 0;
5209 }
5210 
5211 static int map_set_def_max_entries(struct bpf_map *map)
5212 {
5213 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5214 		int nr_cpus;
5215 
5216 		nr_cpus = libbpf_num_possible_cpus();
5217 		if (nr_cpus < 0) {
5218 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5219 				map->name, nr_cpus);
5220 			return nr_cpus;
5221 		}
5222 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5223 		map->def.max_entries = nr_cpus;
5224 	}
5225 
5226 	return 0;
5227 }
5228 
5229 static int
5230 bpf_object__create_maps(struct bpf_object *obj)
5231 {
5232 	struct bpf_map *map;
5233 	char *cp, errmsg[STRERR_BUFSIZE];
5234 	unsigned int i, j;
5235 	int err;
5236 	bool retried;
5237 
5238 	for (i = 0; i < obj->nr_maps; i++) {
5239 		map = &obj->maps[i];
5240 
5241 		/* To support old kernels, we skip creating global data maps
5242 		 * (.rodata, .data, .kconfig, etc); later on, during program
5243 		 * loading, if we detect that at least one of the to-be-loaded
5244 		 * programs is referencing any global data map, we'll error
5245 		 * out with program name and relocation index logged.
5246 		 * This approach allows to accommodate Clang emitting
5247 		 * unnecessary .rodata.str1.1 sections for string literals,
5248 		 * but also it allows to have CO-RE applications that use
5249 		 * global variables in some of BPF programs, but not others.
5250 		 * If those global variable-using programs are not loaded at
5251 		 * runtime due to bpf_program__set_autoload(prog, false),
5252 		 * bpf_object loading will succeed just fine even on old
5253 		 * kernels.
5254 		 */
5255 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5256 			map->autocreate = false;
5257 
5258 		if (!map->autocreate) {
5259 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5260 			continue;
5261 		}
5262 
5263 		err = map_set_def_max_entries(map);
5264 		if (err)
5265 			goto err_out;
5266 
5267 		retried = false;
5268 retry:
5269 		if (map->pin_path) {
5270 			err = bpf_object__reuse_map(map);
5271 			if (err) {
5272 				pr_warn("map '%s': error reusing pinned map\n",
5273 					map->name);
5274 				goto err_out;
5275 			}
5276 			if (retried && map->fd < 0) {
5277 				pr_warn("map '%s': cannot find pinned map\n",
5278 					map->name);
5279 				err = -ENOENT;
5280 				goto err_out;
5281 			}
5282 		}
5283 
5284 		if (map->fd >= 0) {
5285 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5286 				 map->name, map->fd);
5287 		} else {
5288 			err = bpf_object__create_map(obj, map, false);
5289 			if (err)
5290 				goto err_out;
5291 
5292 			pr_debug("map '%s': created successfully, fd=%d\n",
5293 				 map->name, map->fd);
5294 
5295 			if (bpf_map__is_internal(map)) {
5296 				err = bpf_object__populate_internal_map(obj, map);
5297 				if (err < 0) {
5298 					zclose(map->fd);
5299 					goto err_out;
5300 				}
5301 			}
5302 
5303 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5304 				err = init_map_in_map_slots(obj, map);
5305 				if (err < 0) {
5306 					zclose(map->fd);
5307 					goto err_out;
5308 				}
5309 			}
5310 		}
5311 
5312 		if (map->pin_path && !map->pinned) {
5313 			err = bpf_map__pin(map, NULL);
5314 			if (err) {
5315 				zclose(map->fd);
5316 				if (!retried && err == -EEXIST) {
5317 					retried = true;
5318 					goto retry;
5319 				}
5320 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5321 					map->name, map->pin_path, err);
5322 				goto err_out;
5323 			}
5324 		}
5325 	}
5326 
5327 	return 0;
5328 
5329 err_out:
5330 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5331 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5332 	pr_perm_msg(err);
5333 	for (j = 0; j < i; j++)
5334 		zclose(obj->maps[j].fd);
5335 	return err;
5336 }
5337 
5338 static bool bpf_core_is_flavor_sep(const char *s)
5339 {
5340 	/* check X___Y name pattern, where X and Y are not underscores */
5341 	return s[0] != '_' &&				      /* X */
5342 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5343 	       s[4] != '_';				      /* Y */
5344 }
5345 
5346 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5347  * before last triple underscore. Struct name part after last triple
5348  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5349  */
5350 size_t bpf_core_essential_name_len(const char *name)
5351 {
5352 	size_t n = strlen(name);
5353 	int i;
5354 
5355 	for (i = n - 5; i >= 0; i--) {
5356 		if (bpf_core_is_flavor_sep(name + i))
5357 			return i + 1;
5358 	}
5359 	return n;
5360 }
5361 
5362 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5363 {
5364 	if (!cands)
5365 		return;
5366 
5367 	free(cands->cands);
5368 	free(cands);
5369 }
5370 
5371 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5372 		       size_t local_essent_len,
5373 		       const struct btf *targ_btf,
5374 		       const char *targ_btf_name,
5375 		       int targ_start_id,
5376 		       struct bpf_core_cand_list *cands)
5377 {
5378 	struct bpf_core_cand *new_cands, *cand;
5379 	const struct btf_type *t, *local_t;
5380 	const char *targ_name, *local_name;
5381 	size_t targ_essent_len;
5382 	int n, i;
5383 
5384 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5385 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5386 
5387 	n = btf__type_cnt(targ_btf);
5388 	for (i = targ_start_id; i < n; i++) {
5389 		t = btf__type_by_id(targ_btf, i);
5390 		if (!btf_kind_core_compat(t, local_t))
5391 			continue;
5392 
5393 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5394 		if (str_is_empty(targ_name))
5395 			continue;
5396 
5397 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5398 		if (targ_essent_len != local_essent_len)
5399 			continue;
5400 
5401 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5402 			continue;
5403 
5404 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5405 			 local_cand->id, btf_kind_str(local_t),
5406 			 local_name, i, btf_kind_str(t), targ_name,
5407 			 targ_btf_name);
5408 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5409 					      sizeof(*cands->cands));
5410 		if (!new_cands)
5411 			return -ENOMEM;
5412 
5413 		cand = &new_cands[cands->len];
5414 		cand->btf = targ_btf;
5415 		cand->id = i;
5416 
5417 		cands->cands = new_cands;
5418 		cands->len++;
5419 	}
5420 	return 0;
5421 }
5422 
5423 static int load_module_btfs(struct bpf_object *obj)
5424 {
5425 	struct bpf_btf_info info;
5426 	struct module_btf *mod_btf;
5427 	struct btf *btf;
5428 	char name[64];
5429 	__u32 id = 0, len;
5430 	int err, fd;
5431 
5432 	if (obj->btf_modules_loaded)
5433 		return 0;
5434 
5435 	if (obj->gen_loader)
5436 		return 0;
5437 
5438 	/* don't do this again, even if we find no module BTFs */
5439 	obj->btf_modules_loaded = true;
5440 
5441 	/* kernel too old to support module BTFs */
5442 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5443 		return 0;
5444 
5445 	while (true) {
5446 		err = bpf_btf_get_next_id(id, &id);
5447 		if (err && errno == ENOENT)
5448 			return 0;
5449 		if (err) {
5450 			err = -errno;
5451 			pr_warn("failed to iterate BTF objects: %d\n", err);
5452 			return err;
5453 		}
5454 
5455 		fd = bpf_btf_get_fd_by_id(id);
5456 		if (fd < 0) {
5457 			if (errno == ENOENT)
5458 				continue; /* expected race: BTF was unloaded */
5459 			err = -errno;
5460 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5461 			return err;
5462 		}
5463 
5464 		len = sizeof(info);
5465 		memset(&info, 0, sizeof(info));
5466 		info.name = ptr_to_u64(name);
5467 		info.name_len = sizeof(name);
5468 
5469 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5470 		if (err) {
5471 			err = -errno;
5472 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5473 			goto err_out;
5474 		}
5475 
5476 		/* ignore non-module BTFs */
5477 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5478 			close(fd);
5479 			continue;
5480 		}
5481 
5482 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5483 		err = libbpf_get_error(btf);
5484 		if (err) {
5485 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5486 				name, id, err);
5487 			goto err_out;
5488 		}
5489 
5490 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5491 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5492 		if (err)
5493 			goto err_out;
5494 
5495 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5496 
5497 		mod_btf->btf = btf;
5498 		mod_btf->id = id;
5499 		mod_btf->fd = fd;
5500 		mod_btf->name = strdup(name);
5501 		if (!mod_btf->name) {
5502 			err = -ENOMEM;
5503 			goto err_out;
5504 		}
5505 		continue;
5506 
5507 err_out:
5508 		close(fd);
5509 		return err;
5510 	}
5511 
5512 	return 0;
5513 }
5514 
5515 static struct bpf_core_cand_list *
5516 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5517 {
5518 	struct bpf_core_cand local_cand = {};
5519 	struct bpf_core_cand_list *cands;
5520 	const struct btf *main_btf;
5521 	const struct btf_type *local_t;
5522 	const char *local_name;
5523 	size_t local_essent_len;
5524 	int err, i;
5525 
5526 	local_cand.btf = local_btf;
5527 	local_cand.id = local_type_id;
5528 	local_t = btf__type_by_id(local_btf, local_type_id);
5529 	if (!local_t)
5530 		return ERR_PTR(-EINVAL);
5531 
5532 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5533 	if (str_is_empty(local_name))
5534 		return ERR_PTR(-EINVAL);
5535 	local_essent_len = bpf_core_essential_name_len(local_name);
5536 
5537 	cands = calloc(1, sizeof(*cands));
5538 	if (!cands)
5539 		return ERR_PTR(-ENOMEM);
5540 
5541 	/* Attempt to find target candidates in vmlinux BTF first */
5542 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5543 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5544 	if (err)
5545 		goto err_out;
5546 
5547 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5548 	if (cands->len)
5549 		return cands;
5550 
5551 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5552 	if (obj->btf_vmlinux_override)
5553 		return cands;
5554 
5555 	/* now look through module BTFs, trying to still find candidates */
5556 	err = load_module_btfs(obj);
5557 	if (err)
5558 		goto err_out;
5559 
5560 	for (i = 0; i < obj->btf_module_cnt; i++) {
5561 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5562 					 obj->btf_modules[i].btf,
5563 					 obj->btf_modules[i].name,
5564 					 btf__type_cnt(obj->btf_vmlinux),
5565 					 cands);
5566 		if (err)
5567 			goto err_out;
5568 	}
5569 
5570 	return cands;
5571 err_out:
5572 	bpf_core_free_cands(cands);
5573 	return ERR_PTR(err);
5574 }
5575 
5576 /* Check local and target types for compatibility. This check is used for
5577  * type-based CO-RE relocations and follow slightly different rules than
5578  * field-based relocations. This function assumes that root types were already
5579  * checked for name match. Beyond that initial root-level name check, names
5580  * are completely ignored. Compatibility rules are as follows:
5581  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5582  *     kind should match for local and target types (i.e., STRUCT is not
5583  *     compatible with UNION);
5584  *   - for ENUMs, the size is ignored;
5585  *   - for INT, size and signedness are ignored;
5586  *   - for ARRAY, dimensionality is ignored, element types are checked for
5587  *     compatibility recursively;
5588  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5589  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5590  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5591  *     number of input args and compatible return and argument types.
5592  * These rules are not set in stone and probably will be adjusted as we get
5593  * more experience with using BPF CO-RE relocations.
5594  */
5595 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5596 			      const struct btf *targ_btf, __u32 targ_id)
5597 {
5598 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5599 }
5600 
5601 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5602 			 const struct btf *targ_btf, __u32 targ_id)
5603 {
5604 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5605 }
5606 
5607 static size_t bpf_core_hash_fn(const long key, void *ctx)
5608 {
5609 	return key;
5610 }
5611 
5612 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5613 {
5614 	return k1 == k2;
5615 }
5616 
5617 static int record_relo_core(struct bpf_program *prog,
5618 			    const struct bpf_core_relo *core_relo, int insn_idx)
5619 {
5620 	struct reloc_desc *relos, *relo;
5621 
5622 	relos = libbpf_reallocarray(prog->reloc_desc,
5623 				    prog->nr_reloc + 1, sizeof(*relos));
5624 	if (!relos)
5625 		return -ENOMEM;
5626 	relo = &relos[prog->nr_reloc];
5627 	relo->type = RELO_CORE;
5628 	relo->insn_idx = insn_idx;
5629 	relo->core_relo = core_relo;
5630 	prog->reloc_desc = relos;
5631 	prog->nr_reloc++;
5632 	return 0;
5633 }
5634 
5635 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5636 {
5637 	struct reloc_desc *relo;
5638 	int i;
5639 
5640 	for (i = 0; i < prog->nr_reloc; i++) {
5641 		relo = &prog->reloc_desc[i];
5642 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5643 			continue;
5644 
5645 		return relo->core_relo;
5646 	}
5647 
5648 	return NULL;
5649 }
5650 
5651 static int bpf_core_resolve_relo(struct bpf_program *prog,
5652 				 const struct bpf_core_relo *relo,
5653 				 int relo_idx,
5654 				 const struct btf *local_btf,
5655 				 struct hashmap *cand_cache,
5656 				 struct bpf_core_relo_res *targ_res)
5657 {
5658 	struct bpf_core_spec specs_scratch[3] = {};
5659 	struct bpf_core_cand_list *cands = NULL;
5660 	const char *prog_name = prog->name;
5661 	const struct btf_type *local_type;
5662 	const char *local_name;
5663 	__u32 local_id = relo->type_id;
5664 	int err;
5665 
5666 	local_type = btf__type_by_id(local_btf, local_id);
5667 	if (!local_type)
5668 		return -EINVAL;
5669 
5670 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5671 	if (!local_name)
5672 		return -EINVAL;
5673 
5674 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5675 	    !hashmap__find(cand_cache, local_id, &cands)) {
5676 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5677 		if (IS_ERR(cands)) {
5678 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5679 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5680 				local_name, PTR_ERR(cands));
5681 			return PTR_ERR(cands);
5682 		}
5683 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5684 		if (err) {
5685 			bpf_core_free_cands(cands);
5686 			return err;
5687 		}
5688 	}
5689 
5690 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5691 				       targ_res);
5692 }
5693 
5694 static int
5695 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5696 {
5697 	const struct btf_ext_info_sec *sec;
5698 	struct bpf_core_relo_res targ_res;
5699 	const struct bpf_core_relo *rec;
5700 	const struct btf_ext_info *seg;
5701 	struct hashmap_entry *entry;
5702 	struct hashmap *cand_cache = NULL;
5703 	struct bpf_program *prog;
5704 	struct bpf_insn *insn;
5705 	const char *sec_name;
5706 	int i, err = 0, insn_idx, sec_idx, sec_num;
5707 
5708 	if (obj->btf_ext->core_relo_info.len == 0)
5709 		return 0;
5710 
5711 	if (targ_btf_path) {
5712 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5713 		err = libbpf_get_error(obj->btf_vmlinux_override);
5714 		if (err) {
5715 			pr_warn("failed to parse target BTF: %d\n", err);
5716 			return err;
5717 		}
5718 	}
5719 
5720 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5721 	if (IS_ERR(cand_cache)) {
5722 		err = PTR_ERR(cand_cache);
5723 		goto out;
5724 	}
5725 
5726 	seg = &obj->btf_ext->core_relo_info;
5727 	sec_num = 0;
5728 	for_each_btf_ext_sec(seg, sec) {
5729 		sec_idx = seg->sec_idxs[sec_num];
5730 		sec_num++;
5731 
5732 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5733 		if (str_is_empty(sec_name)) {
5734 			err = -EINVAL;
5735 			goto out;
5736 		}
5737 
5738 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5739 
5740 		for_each_btf_ext_rec(seg, sec, i, rec) {
5741 			if (rec->insn_off % BPF_INSN_SZ)
5742 				return -EINVAL;
5743 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5744 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5745 			if (!prog) {
5746 				/* When __weak subprog is "overridden" by another instance
5747 				 * of the subprog from a different object file, linker still
5748 				 * appends all the .BTF.ext info that used to belong to that
5749 				 * eliminated subprogram.
5750 				 * This is similar to what x86-64 linker does for relocations.
5751 				 * So just ignore such relocations just like we ignore
5752 				 * subprog instructions when discovering subprograms.
5753 				 */
5754 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5755 					 sec_name, i, insn_idx);
5756 				continue;
5757 			}
5758 			/* no need to apply CO-RE relocation if the program is
5759 			 * not going to be loaded
5760 			 */
5761 			if (!prog->autoload)
5762 				continue;
5763 
5764 			/* adjust insn_idx from section frame of reference to the local
5765 			 * program's frame of reference; (sub-)program code is not yet
5766 			 * relocated, so it's enough to just subtract in-section offset
5767 			 */
5768 			insn_idx = insn_idx - prog->sec_insn_off;
5769 			if (insn_idx >= prog->insns_cnt)
5770 				return -EINVAL;
5771 			insn = &prog->insns[insn_idx];
5772 
5773 			err = record_relo_core(prog, rec, insn_idx);
5774 			if (err) {
5775 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5776 					prog->name, i, err);
5777 				goto out;
5778 			}
5779 
5780 			if (prog->obj->gen_loader)
5781 				continue;
5782 
5783 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5784 			if (err) {
5785 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5786 					prog->name, i, err);
5787 				goto out;
5788 			}
5789 
5790 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5791 			if (err) {
5792 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5793 					prog->name, i, insn_idx, err);
5794 				goto out;
5795 			}
5796 		}
5797 	}
5798 
5799 out:
5800 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5801 	btf__free(obj->btf_vmlinux_override);
5802 	obj->btf_vmlinux_override = NULL;
5803 
5804 	if (!IS_ERR_OR_NULL(cand_cache)) {
5805 		hashmap__for_each_entry(cand_cache, entry, i) {
5806 			bpf_core_free_cands(entry->pvalue);
5807 		}
5808 		hashmap__free(cand_cache);
5809 	}
5810 	return err;
5811 }
5812 
5813 /* base map load ldimm64 special constant, used also for log fixup logic */
5814 #define MAP_LDIMM64_POISON_BASE 2001000000
5815 #define MAP_LDIMM64_POISON_PFX "200100"
5816 
5817 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5818 			       int insn_idx, struct bpf_insn *insn,
5819 			       int map_idx, const struct bpf_map *map)
5820 {
5821 	int i;
5822 
5823 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5824 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5825 
5826 	/* we turn single ldimm64 into two identical invalid calls */
5827 	for (i = 0; i < 2; i++) {
5828 		insn->code = BPF_JMP | BPF_CALL;
5829 		insn->dst_reg = 0;
5830 		insn->src_reg = 0;
5831 		insn->off = 0;
5832 		/* if this instruction is reachable (not a dead code),
5833 		 * verifier will complain with something like:
5834 		 * invalid func unknown#2001000123
5835 		 * where lower 123 is map index into obj->maps[] array
5836 		 */
5837 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5838 
5839 		insn++;
5840 	}
5841 }
5842 
5843 /* Relocate data references within program code:
5844  *  - map references;
5845  *  - global variable references;
5846  *  - extern references.
5847  */
5848 static int
5849 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5850 {
5851 	int i;
5852 
5853 	for (i = 0; i < prog->nr_reloc; i++) {
5854 		struct reloc_desc *relo = &prog->reloc_desc[i];
5855 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5856 		const struct bpf_map *map;
5857 		struct extern_desc *ext;
5858 
5859 		switch (relo->type) {
5860 		case RELO_LD64:
5861 			map = &obj->maps[relo->map_idx];
5862 			if (obj->gen_loader) {
5863 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5864 				insn[0].imm = relo->map_idx;
5865 			} else if (map->autocreate) {
5866 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5867 				insn[0].imm = map->fd;
5868 			} else {
5869 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5870 						   relo->map_idx, map);
5871 			}
5872 			break;
5873 		case RELO_DATA:
5874 			map = &obj->maps[relo->map_idx];
5875 			insn[1].imm = insn[0].imm + relo->sym_off;
5876 			if (obj->gen_loader) {
5877 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5878 				insn[0].imm = relo->map_idx;
5879 			} else if (map->autocreate) {
5880 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5881 				insn[0].imm = map->fd;
5882 			} else {
5883 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5884 						   relo->map_idx, map);
5885 			}
5886 			break;
5887 		case RELO_EXTERN_LD64:
5888 			ext = &obj->externs[relo->sym_off];
5889 			if (ext->type == EXT_KCFG) {
5890 				if (obj->gen_loader) {
5891 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5892 					insn[0].imm = obj->kconfig_map_idx;
5893 				} else {
5894 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5895 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5896 				}
5897 				insn[1].imm = ext->kcfg.data_off;
5898 			} else /* EXT_KSYM */ {
5899 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5900 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5901 					insn[0].imm = ext->ksym.kernel_btf_id;
5902 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5903 				} else { /* typeless ksyms or unresolved typed ksyms */
5904 					insn[0].imm = (__u32)ext->ksym.addr;
5905 					insn[1].imm = ext->ksym.addr >> 32;
5906 				}
5907 			}
5908 			break;
5909 		case RELO_EXTERN_CALL:
5910 			ext = &obj->externs[relo->sym_off];
5911 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5912 			if (ext->is_set) {
5913 				insn[0].imm = ext->ksym.kernel_btf_id;
5914 				insn[0].off = ext->ksym.btf_fd_idx;
5915 			} else { /* unresolved weak kfunc */
5916 				insn[0].imm = 0;
5917 				insn[0].off = 0;
5918 			}
5919 			break;
5920 		case RELO_SUBPROG_ADDR:
5921 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5922 				pr_warn("prog '%s': relo #%d: bad insn\n",
5923 					prog->name, i);
5924 				return -EINVAL;
5925 			}
5926 			/* handled already */
5927 			break;
5928 		case RELO_CALL:
5929 			/* handled already */
5930 			break;
5931 		case RELO_CORE:
5932 			/* will be handled by bpf_program_record_relos() */
5933 			break;
5934 		default:
5935 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5936 				prog->name, i, relo->type);
5937 			return -EINVAL;
5938 		}
5939 	}
5940 
5941 	return 0;
5942 }
5943 
5944 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5945 				    const struct bpf_program *prog,
5946 				    const struct btf_ext_info *ext_info,
5947 				    void **prog_info, __u32 *prog_rec_cnt,
5948 				    __u32 *prog_rec_sz)
5949 {
5950 	void *copy_start = NULL, *copy_end = NULL;
5951 	void *rec, *rec_end, *new_prog_info;
5952 	const struct btf_ext_info_sec *sec;
5953 	size_t old_sz, new_sz;
5954 	int i, sec_num, sec_idx, off_adj;
5955 
5956 	sec_num = 0;
5957 	for_each_btf_ext_sec(ext_info, sec) {
5958 		sec_idx = ext_info->sec_idxs[sec_num];
5959 		sec_num++;
5960 		if (prog->sec_idx != sec_idx)
5961 			continue;
5962 
5963 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
5964 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5965 
5966 			if (insn_off < prog->sec_insn_off)
5967 				continue;
5968 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5969 				break;
5970 
5971 			if (!copy_start)
5972 				copy_start = rec;
5973 			copy_end = rec + ext_info->rec_size;
5974 		}
5975 
5976 		if (!copy_start)
5977 			return -ENOENT;
5978 
5979 		/* append func/line info of a given (sub-)program to the main
5980 		 * program func/line info
5981 		 */
5982 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5983 		new_sz = old_sz + (copy_end - copy_start);
5984 		new_prog_info = realloc(*prog_info, new_sz);
5985 		if (!new_prog_info)
5986 			return -ENOMEM;
5987 		*prog_info = new_prog_info;
5988 		*prog_rec_cnt = new_sz / ext_info->rec_size;
5989 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5990 
5991 		/* Kernel instruction offsets are in units of 8-byte
5992 		 * instructions, while .BTF.ext instruction offsets generated
5993 		 * by Clang are in units of bytes. So convert Clang offsets
5994 		 * into kernel offsets and adjust offset according to program
5995 		 * relocated position.
5996 		 */
5997 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
5998 		rec = new_prog_info + old_sz;
5999 		rec_end = new_prog_info + new_sz;
6000 		for (; rec < rec_end; rec += ext_info->rec_size) {
6001 			__u32 *insn_off = rec;
6002 
6003 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6004 		}
6005 		*prog_rec_sz = ext_info->rec_size;
6006 		return 0;
6007 	}
6008 
6009 	return -ENOENT;
6010 }
6011 
6012 static int
6013 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6014 			      struct bpf_program *main_prog,
6015 			      const struct bpf_program *prog)
6016 {
6017 	int err;
6018 
6019 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6020 	 * supprot func/line info
6021 	 */
6022 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6023 		return 0;
6024 
6025 	/* only attempt func info relocation if main program's func_info
6026 	 * relocation was successful
6027 	 */
6028 	if (main_prog != prog && !main_prog->func_info)
6029 		goto line_info;
6030 
6031 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6032 				       &main_prog->func_info,
6033 				       &main_prog->func_info_cnt,
6034 				       &main_prog->func_info_rec_size);
6035 	if (err) {
6036 		if (err != -ENOENT) {
6037 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6038 				prog->name, err);
6039 			return err;
6040 		}
6041 		if (main_prog->func_info) {
6042 			/*
6043 			 * Some info has already been found but has problem
6044 			 * in the last btf_ext reloc. Must have to error out.
6045 			 */
6046 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6047 			return err;
6048 		}
6049 		/* Have problem loading the very first info. Ignore the rest. */
6050 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6051 			prog->name);
6052 	}
6053 
6054 line_info:
6055 	/* don't relocate line info if main program's relocation failed */
6056 	if (main_prog != prog && !main_prog->line_info)
6057 		return 0;
6058 
6059 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6060 				       &main_prog->line_info,
6061 				       &main_prog->line_info_cnt,
6062 				       &main_prog->line_info_rec_size);
6063 	if (err) {
6064 		if (err != -ENOENT) {
6065 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6066 				prog->name, err);
6067 			return err;
6068 		}
6069 		if (main_prog->line_info) {
6070 			/*
6071 			 * Some info has already been found but has problem
6072 			 * in the last btf_ext reloc. Must have to error out.
6073 			 */
6074 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6075 			return err;
6076 		}
6077 		/* Have problem loading the very first info. Ignore the rest. */
6078 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6079 			prog->name);
6080 	}
6081 	return 0;
6082 }
6083 
6084 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6085 {
6086 	size_t insn_idx = *(const size_t *)key;
6087 	const struct reloc_desc *relo = elem;
6088 
6089 	if (insn_idx == relo->insn_idx)
6090 		return 0;
6091 	return insn_idx < relo->insn_idx ? -1 : 1;
6092 }
6093 
6094 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6095 {
6096 	if (!prog->nr_reloc)
6097 		return NULL;
6098 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6099 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6100 }
6101 
6102 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6103 {
6104 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6105 	struct reloc_desc *relos;
6106 	int i;
6107 
6108 	if (main_prog == subprog)
6109 		return 0;
6110 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6111 	if (!relos)
6112 		return -ENOMEM;
6113 	if (subprog->nr_reloc)
6114 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6115 		       sizeof(*relos) * subprog->nr_reloc);
6116 
6117 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6118 		relos[i].insn_idx += subprog->sub_insn_off;
6119 	/* After insn_idx adjustment the 'relos' array is still sorted
6120 	 * by insn_idx and doesn't break bsearch.
6121 	 */
6122 	main_prog->reloc_desc = relos;
6123 	main_prog->nr_reloc = new_cnt;
6124 	return 0;
6125 }
6126 
6127 static int
6128 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6129 		       struct bpf_program *prog)
6130 {
6131 	size_t sub_insn_idx, insn_idx, new_cnt;
6132 	struct bpf_program *subprog;
6133 	struct bpf_insn *insns, *insn;
6134 	struct reloc_desc *relo;
6135 	int err;
6136 
6137 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6138 	if (err)
6139 		return err;
6140 
6141 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6142 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6143 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6144 			continue;
6145 
6146 		relo = find_prog_insn_relo(prog, insn_idx);
6147 		if (relo && relo->type == RELO_EXTERN_CALL)
6148 			/* kfunc relocations will be handled later
6149 			 * in bpf_object__relocate_data()
6150 			 */
6151 			continue;
6152 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6153 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6154 				prog->name, insn_idx, relo->type);
6155 			return -LIBBPF_ERRNO__RELOC;
6156 		}
6157 		if (relo) {
6158 			/* sub-program instruction index is a combination of
6159 			 * an offset of a symbol pointed to by relocation and
6160 			 * call instruction's imm field; for global functions,
6161 			 * call always has imm = -1, but for static functions
6162 			 * relocation is against STT_SECTION and insn->imm
6163 			 * points to a start of a static function
6164 			 *
6165 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6166 			 * the byte offset in the corresponding section.
6167 			 */
6168 			if (relo->type == RELO_CALL)
6169 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6170 			else
6171 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6172 		} else if (insn_is_pseudo_func(insn)) {
6173 			/*
6174 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6175 			 * functions are in the same section, so it shouldn't reach here.
6176 			 */
6177 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6178 				prog->name, insn_idx);
6179 			return -LIBBPF_ERRNO__RELOC;
6180 		} else {
6181 			/* if subprogram call is to a static function within
6182 			 * the same ELF section, there won't be any relocation
6183 			 * emitted, but it also means there is no additional
6184 			 * offset necessary, insns->imm is relative to
6185 			 * instruction's original position within the section
6186 			 */
6187 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6188 		}
6189 
6190 		/* we enforce that sub-programs should be in .text section */
6191 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6192 		if (!subprog) {
6193 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6194 				prog->name);
6195 			return -LIBBPF_ERRNO__RELOC;
6196 		}
6197 
6198 		/* if it's the first call instruction calling into this
6199 		 * subprogram (meaning this subprog hasn't been processed
6200 		 * yet) within the context of current main program:
6201 		 *   - append it at the end of main program's instructions blog;
6202 		 *   - process is recursively, while current program is put on hold;
6203 		 *   - if that subprogram calls some other not yet processes
6204 		 *   subprogram, same thing will happen recursively until
6205 		 *   there are no more unprocesses subprograms left to append
6206 		 *   and relocate.
6207 		 */
6208 		if (subprog->sub_insn_off == 0) {
6209 			subprog->sub_insn_off = main_prog->insns_cnt;
6210 
6211 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6212 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6213 			if (!insns) {
6214 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6215 				return -ENOMEM;
6216 			}
6217 			main_prog->insns = insns;
6218 			main_prog->insns_cnt = new_cnt;
6219 
6220 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6221 			       subprog->insns_cnt * sizeof(*insns));
6222 
6223 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6224 				 main_prog->name, subprog->insns_cnt, subprog->name);
6225 
6226 			/* The subprog insns are now appended. Append its relos too. */
6227 			err = append_subprog_relos(main_prog, subprog);
6228 			if (err)
6229 				return err;
6230 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6231 			if (err)
6232 				return err;
6233 		}
6234 
6235 		/* main_prog->insns memory could have been re-allocated, so
6236 		 * calculate pointer again
6237 		 */
6238 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6239 		/* calculate correct instruction position within current main
6240 		 * prog; each main prog can have a different set of
6241 		 * subprograms appended (potentially in different order as
6242 		 * well), so position of any subprog can be different for
6243 		 * different main programs
6244 		 */
6245 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6246 
6247 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6248 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6249 	}
6250 
6251 	return 0;
6252 }
6253 
6254 /*
6255  * Relocate sub-program calls.
6256  *
6257  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6258  * main prog) is processed separately. For each subprog (non-entry functions,
6259  * that can be called from either entry progs or other subprogs) gets their
6260  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6261  * hasn't been yet appended and relocated within current main prog. Once its
6262  * relocated, sub_insn_off will point at the position within current main prog
6263  * where given subprog was appended. This will further be used to relocate all
6264  * the call instructions jumping into this subprog.
6265  *
6266  * We start with main program and process all call instructions. If the call
6267  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6268  * is zero), subprog instructions are appended at the end of main program's
6269  * instruction array. Then main program is "put on hold" while we recursively
6270  * process newly appended subprogram. If that subprogram calls into another
6271  * subprogram that hasn't been appended, new subprogram is appended again to
6272  * the *main* prog's instructions (subprog's instructions are always left
6273  * untouched, as they need to be in unmodified state for subsequent main progs
6274  * and subprog instructions are always sent only as part of a main prog) and
6275  * the process continues recursively. Once all the subprogs called from a main
6276  * prog or any of its subprogs are appended (and relocated), all their
6277  * positions within finalized instructions array are known, so it's easy to
6278  * rewrite call instructions with correct relative offsets, corresponding to
6279  * desired target subprog.
6280  *
6281  * Its important to realize that some subprogs might not be called from some
6282  * main prog and any of its called/used subprogs. Those will keep their
6283  * subprog->sub_insn_off as zero at all times and won't be appended to current
6284  * main prog and won't be relocated within the context of current main prog.
6285  * They might still be used from other main progs later.
6286  *
6287  * Visually this process can be shown as below. Suppose we have two main
6288  * programs mainA and mainB and BPF object contains three subprogs: subA,
6289  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6290  * subC both call subB:
6291  *
6292  *        +--------+ +-------+
6293  *        |        v v       |
6294  *     +--+---+ +--+-+-+ +---+--+
6295  *     | subA | | subB | | subC |
6296  *     +--+---+ +------+ +---+--+
6297  *        ^                  ^
6298  *        |                  |
6299  *    +---+-------+   +------+----+
6300  *    |   mainA   |   |   mainB   |
6301  *    +-----------+   +-----------+
6302  *
6303  * We'll start relocating mainA, will find subA, append it and start
6304  * processing sub A recursively:
6305  *
6306  *    +-----------+------+
6307  *    |   mainA   | subA |
6308  *    +-----------+------+
6309  *
6310  * At this point we notice that subB is used from subA, so we append it and
6311  * relocate (there are no further subcalls from subB):
6312  *
6313  *    +-----------+------+------+
6314  *    |   mainA   | subA | subB |
6315  *    +-----------+------+------+
6316  *
6317  * At this point, we relocate subA calls, then go one level up and finish with
6318  * relocatin mainA calls. mainA is done.
6319  *
6320  * For mainB process is similar but results in different order. We start with
6321  * mainB and skip subA and subB, as mainB never calls them (at least
6322  * directly), but we see subC is needed, so we append and start processing it:
6323  *
6324  *    +-----------+------+
6325  *    |   mainB   | subC |
6326  *    +-----------+------+
6327  * Now we see subC needs subB, so we go back to it, append and relocate it:
6328  *
6329  *    +-----------+------+------+
6330  *    |   mainB   | subC | subB |
6331  *    +-----------+------+------+
6332  *
6333  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6334  */
6335 static int
6336 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6337 {
6338 	struct bpf_program *subprog;
6339 	int i, err;
6340 
6341 	/* mark all subprogs as not relocated (yet) within the context of
6342 	 * current main program
6343 	 */
6344 	for (i = 0; i < obj->nr_programs; i++) {
6345 		subprog = &obj->programs[i];
6346 		if (!prog_is_subprog(obj, subprog))
6347 			continue;
6348 
6349 		subprog->sub_insn_off = 0;
6350 	}
6351 
6352 	err = bpf_object__reloc_code(obj, prog, prog);
6353 	if (err)
6354 		return err;
6355 
6356 	return 0;
6357 }
6358 
6359 static void
6360 bpf_object__free_relocs(struct bpf_object *obj)
6361 {
6362 	struct bpf_program *prog;
6363 	int i;
6364 
6365 	/* free up relocation descriptors */
6366 	for (i = 0; i < obj->nr_programs; i++) {
6367 		prog = &obj->programs[i];
6368 		zfree(&prog->reloc_desc);
6369 		prog->nr_reloc = 0;
6370 	}
6371 }
6372 
6373 static int cmp_relocs(const void *_a, const void *_b)
6374 {
6375 	const struct reloc_desc *a = _a;
6376 	const struct reloc_desc *b = _b;
6377 
6378 	if (a->insn_idx != b->insn_idx)
6379 		return a->insn_idx < b->insn_idx ? -1 : 1;
6380 
6381 	/* no two relocations should have the same insn_idx, but ... */
6382 	if (a->type != b->type)
6383 		return a->type < b->type ? -1 : 1;
6384 
6385 	return 0;
6386 }
6387 
6388 static void bpf_object__sort_relos(struct bpf_object *obj)
6389 {
6390 	int i;
6391 
6392 	for (i = 0; i < obj->nr_programs; i++) {
6393 		struct bpf_program *p = &obj->programs[i];
6394 
6395 		if (!p->nr_reloc)
6396 			continue;
6397 
6398 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6399 	}
6400 }
6401 
6402 static int
6403 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6404 {
6405 	struct bpf_program *prog;
6406 	size_t i, j;
6407 	int err;
6408 
6409 	if (obj->btf_ext) {
6410 		err = bpf_object__relocate_core(obj, targ_btf_path);
6411 		if (err) {
6412 			pr_warn("failed to perform CO-RE relocations: %d\n",
6413 				err);
6414 			return err;
6415 		}
6416 		bpf_object__sort_relos(obj);
6417 	}
6418 
6419 	/* Before relocating calls pre-process relocations and mark
6420 	 * few ld_imm64 instructions that points to subprogs.
6421 	 * Otherwise bpf_object__reloc_code() later would have to consider
6422 	 * all ld_imm64 insns as relocation candidates. That would
6423 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6424 	 * would increase and most of them will fail to find a relo.
6425 	 */
6426 	for (i = 0; i < obj->nr_programs; i++) {
6427 		prog = &obj->programs[i];
6428 		for (j = 0; j < prog->nr_reloc; j++) {
6429 			struct reloc_desc *relo = &prog->reloc_desc[j];
6430 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6431 
6432 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6433 			if (relo->type == RELO_SUBPROG_ADDR)
6434 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6435 		}
6436 	}
6437 
6438 	/* relocate subprogram calls and append used subprograms to main
6439 	 * programs; each copy of subprogram code needs to be relocated
6440 	 * differently for each main program, because its code location might
6441 	 * have changed.
6442 	 * Append subprog relos to main programs to allow data relos to be
6443 	 * processed after text is completely relocated.
6444 	 */
6445 	for (i = 0; i < obj->nr_programs; i++) {
6446 		prog = &obj->programs[i];
6447 		/* sub-program's sub-calls are relocated within the context of
6448 		 * its main program only
6449 		 */
6450 		if (prog_is_subprog(obj, prog))
6451 			continue;
6452 		if (!prog->autoload)
6453 			continue;
6454 
6455 		err = bpf_object__relocate_calls(obj, prog);
6456 		if (err) {
6457 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6458 				prog->name, err);
6459 			return err;
6460 		}
6461 	}
6462 	/* Process data relos for main programs */
6463 	for (i = 0; i < obj->nr_programs; i++) {
6464 		prog = &obj->programs[i];
6465 		if (prog_is_subprog(obj, prog))
6466 			continue;
6467 		if (!prog->autoload)
6468 			continue;
6469 		err = bpf_object__relocate_data(obj, prog);
6470 		if (err) {
6471 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6472 				prog->name, err);
6473 			return err;
6474 		}
6475 	}
6476 
6477 	return 0;
6478 }
6479 
6480 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6481 					    Elf64_Shdr *shdr, Elf_Data *data);
6482 
6483 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6484 					 Elf64_Shdr *shdr, Elf_Data *data)
6485 {
6486 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6487 	int i, j, nrels, new_sz;
6488 	const struct btf_var_secinfo *vi = NULL;
6489 	const struct btf_type *sec, *var, *def;
6490 	struct bpf_map *map = NULL, *targ_map = NULL;
6491 	struct bpf_program *targ_prog = NULL;
6492 	bool is_prog_array, is_map_in_map;
6493 	const struct btf_member *member;
6494 	const char *name, *mname, *type;
6495 	unsigned int moff;
6496 	Elf64_Sym *sym;
6497 	Elf64_Rel *rel;
6498 	void *tmp;
6499 
6500 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6501 		return -EINVAL;
6502 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6503 	if (!sec)
6504 		return -EINVAL;
6505 
6506 	nrels = shdr->sh_size / shdr->sh_entsize;
6507 	for (i = 0; i < nrels; i++) {
6508 		rel = elf_rel_by_idx(data, i);
6509 		if (!rel) {
6510 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6511 			return -LIBBPF_ERRNO__FORMAT;
6512 		}
6513 
6514 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6515 		if (!sym) {
6516 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6517 				i, (size_t)ELF64_R_SYM(rel->r_info));
6518 			return -LIBBPF_ERRNO__FORMAT;
6519 		}
6520 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6521 
6522 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6523 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6524 			 (size_t)rel->r_offset, sym->st_name, name);
6525 
6526 		for (j = 0; j < obj->nr_maps; j++) {
6527 			map = &obj->maps[j];
6528 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6529 				continue;
6530 
6531 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6532 			if (vi->offset <= rel->r_offset &&
6533 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6534 				break;
6535 		}
6536 		if (j == obj->nr_maps) {
6537 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6538 				i, name, (size_t)rel->r_offset);
6539 			return -EINVAL;
6540 		}
6541 
6542 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6543 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6544 		type = is_map_in_map ? "map" : "prog";
6545 		if (is_map_in_map) {
6546 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6547 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6548 					i, name);
6549 				return -LIBBPF_ERRNO__RELOC;
6550 			}
6551 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6552 			    map->def.key_size != sizeof(int)) {
6553 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6554 					i, map->name, sizeof(int));
6555 				return -EINVAL;
6556 			}
6557 			targ_map = bpf_object__find_map_by_name(obj, name);
6558 			if (!targ_map) {
6559 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6560 					i, name);
6561 				return -ESRCH;
6562 			}
6563 		} else if (is_prog_array) {
6564 			targ_prog = bpf_object__find_program_by_name(obj, name);
6565 			if (!targ_prog) {
6566 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6567 					i, name);
6568 				return -ESRCH;
6569 			}
6570 			if (targ_prog->sec_idx != sym->st_shndx ||
6571 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6572 			    prog_is_subprog(obj, targ_prog)) {
6573 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6574 					i, name);
6575 				return -LIBBPF_ERRNO__RELOC;
6576 			}
6577 		} else {
6578 			return -EINVAL;
6579 		}
6580 
6581 		var = btf__type_by_id(obj->btf, vi->type);
6582 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6583 		if (btf_vlen(def) == 0)
6584 			return -EINVAL;
6585 		member = btf_members(def) + btf_vlen(def) - 1;
6586 		mname = btf__name_by_offset(obj->btf, member->name_off);
6587 		if (strcmp(mname, "values"))
6588 			return -EINVAL;
6589 
6590 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6591 		if (rel->r_offset - vi->offset < moff)
6592 			return -EINVAL;
6593 
6594 		moff = rel->r_offset - vi->offset - moff;
6595 		/* here we use BPF pointer size, which is always 64 bit, as we
6596 		 * are parsing ELF that was built for BPF target
6597 		 */
6598 		if (moff % bpf_ptr_sz)
6599 			return -EINVAL;
6600 		moff /= bpf_ptr_sz;
6601 		if (moff >= map->init_slots_sz) {
6602 			new_sz = moff + 1;
6603 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6604 			if (!tmp)
6605 				return -ENOMEM;
6606 			map->init_slots = tmp;
6607 			memset(map->init_slots + map->init_slots_sz, 0,
6608 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6609 			map->init_slots_sz = new_sz;
6610 		}
6611 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6612 
6613 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6614 			 i, map->name, moff, type, name);
6615 	}
6616 
6617 	return 0;
6618 }
6619 
6620 static int bpf_object__collect_relos(struct bpf_object *obj)
6621 {
6622 	int i, err;
6623 
6624 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6625 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6626 		Elf64_Shdr *shdr;
6627 		Elf_Data *data;
6628 		int idx;
6629 
6630 		if (sec_desc->sec_type != SEC_RELO)
6631 			continue;
6632 
6633 		shdr = sec_desc->shdr;
6634 		data = sec_desc->data;
6635 		idx = shdr->sh_info;
6636 
6637 		if (shdr->sh_type != SHT_REL) {
6638 			pr_warn("internal error at %d\n", __LINE__);
6639 			return -LIBBPF_ERRNO__INTERNAL;
6640 		}
6641 
6642 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6643 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6644 		else if (idx == obj->efile.btf_maps_shndx)
6645 			err = bpf_object__collect_map_relos(obj, shdr, data);
6646 		else
6647 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6648 		if (err)
6649 			return err;
6650 	}
6651 
6652 	bpf_object__sort_relos(obj);
6653 	return 0;
6654 }
6655 
6656 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6657 {
6658 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6659 	    BPF_OP(insn->code) == BPF_CALL &&
6660 	    BPF_SRC(insn->code) == BPF_K &&
6661 	    insn->src_reg == 0 &&
6662 	    insn->dst_reg == 0) {
6663 		    *func_id = insn->imm;
6664 		    return true;
6665 	}
6666 	return false;
6667 }
6668 
6669 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6670 {
6671 	struct bpf_insn *insn = prog->insns;
6672 	enum bpf_func_id func_id;
6673 	int i;
6674 
6675 	if (obj->gen_loader)
6676 		return 0;
6677 
6678 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6679 		if (!insn_is_helper_call(insn, &func_id))
6680 			continue;
6681 
6682 		/* on kernels that don't yet support
6683 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6684 		 * to bpf_probe_read() which works well for old kernels
6685 		 */
6686 		switch (func_id) {
6687 		case BPF_FUNC_probe_read_kernel:
6688 		case BPF_FUNC_probe_read_user:
6689 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6690 				insn->imm = BPF_FUNC_probe_read;
6691 			break;
6692 		case BPF_FUNC_probe_read_kernel_str:
6693 		case BPF_FUNC_probe_read_user_str:
6694 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6695 				insn->imm = BPF_FUNC_probe_read_str;
6696 			break;
6697 		default:
6698 			break;
6699 		}
6700 	}
6701 	return 0;
6702 }
6703 
6704 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6705 				     int *btf_obj_fd, int *btf_type_id);
6706 
6707 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6708 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6709 				    struct bpf_prog_load_opts *opts, long cookie)
6710 {
6711 	enum sec_def_flags def = cookie;
6712 
6713 	/* old kernels might not support specifying expected_attach_type */
6714 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6715 		opts->expected_attach_type = 0;
6716 
6717 	if (def & SEC_SLEEPABLE)
6718 		opts->prog_flags |= BPF_F_SLEEPABLE;
6719 
6720 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6721 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6722 
6723 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6724 		int btf_obj_fd = 0, btf_type_id = 0, err;
6725 		const char *attach_name;
6726 
6727 		attach_name = strchr(prog->sec_name, '/');
6728 		if (!attach_name) {
6729 			/* if BPF program is annotated with just SEC("fentry")
6730 			 * (or similar) without declaratively specifying
6731 			 * target, then it is expected that target will be
6732 			 * specified with bpf_program__set_attach_target() at
6733 			 * runtime before BPF object load step. If not, then
6734 			 * there is nothing to load into the kernel as BPF
6735 			 * verifier won't be able to validate BPF program
6736 			 * correctness anyways.
6737 			 */
6738 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6739 				prog->name);
6740 			return -EINVAL;
6741 		}
6742 		attach_name++; /* skip over / */
6743 
6744 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6745 		if (err)
6746 			return err;
6747 
6748 		/* cache resolved BTF FD and BTF type ID in the prog */
6749 		prog->attach_btf_obj_fd = btf_obj_fd;
6750 		prog->attach_btf_id = btf_type_id;
6751 
6752 		/* but by now libbpf common logic is not utilizing
6753 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6754 		 * this callback is called after opts were populated by
6755 		 * libbpf, so this callback has to update opts explicitly here
6756 		 */
6757 		opts->attach_btf_obj_fd = btf_obj_fd;
6758 		opts->attach_btf_id = btf_type_id;
6759 	}
6760 	return 0;
6761 }
6762 
6763 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6764 
6765 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6766 				struct bpf_insn *insns, int insns_cnt,
6767 				const char *license, __u32 kern_version, int *prog_fd)
6768 {
6769 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6770 	const char *prog_name = NULL;
6771 	char *cp, errmsg[STRERR_BUFSIZE];
6772 	size_t log_buf_size = 0;
6773 	char *log_buf = NULL, *tmp;
6774 	int btf_fd, ret, err;
6775 	bool own_log_buf = true;
6776 	__u32 log_level = prog->log_level;
6777 
6778 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6779 		/*
6780 		 * The program type must be set.  Most likely we couldn't find a proper
6781 		 * section definition at load time, and thus we didn't infer the type.
6782 		 */
6783 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6784 			prog->name, prog->sec_name);
6785 		return -EINVAL;
6786 	}
6787 
6788 	if (!insns || !insns_cnt)
6789 		return -EINVAL;
6790 
6791 	load_attr.expected_attach_type = prog->expected_attach_type;
6792 	if (kernel_supports(obj, FEAT_PROG_NAME))
6793 		prog_name = prog->name;
6794 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6795 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6796 	load_attr.attach_btf_id = prog->attach_btf_id;
6797 	load_attr.kern_version = kern_version;
6798 	load_attr.prog_ifindex = prog->prog_ifindex;
6799 
6800 	/* specify func_info/line_info only if kernel supports them */
6801 	btf_fd = bpf_object__btf_fd(obj);
6802 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6803 		load_attr.prog_btf_fd = btf_fd;
6804 		load_attr.func_info = prog->func_info;
6805 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6806 		load_attr.func_info_cnt = prog->func_info_cnt;
6807 		load_attr.line_info = prog->line_info;
6808 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6809 		load_attr.line_info_cnt = prog->line_info_cnt;
6810 	}
6811 	load_attr.log_level = log_level;
6812 	load_attr.prog_flags = prog->prog_flags;
6813 	load_attr.fd_array = obj->fd_array;
6814 
6815 	/* adjust load_attr if sec_def provides custom preload callback */
6816 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6817 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6818 		if (err < 0) {
6819 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6820 				prog->name, err);
6821 			return err;
6822 		}
6823 		insns = prog->insns;
6824 		insns_cnt = prog->insns_cnt;
6825 	}
6826 
6827 	if (obj->gen_loader) {
6828 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6829 				   license, insns, insns_cnt, &load_attr,
6830 				   prog - obj->programs);
6831 		*prog_fd = -1;
6832 		return 0;
6833 	}
6834 
6835 retry_load:
6836 	/* if log_level is zero, we don't request logs initially even if
6837 	 * custom log_buf is specified; if the program load fails, then we'll
6838 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6839 	 * our own and retry the load to get details on what failed
6840 	 */
6841 	if (log_level) {
6842 		if (prog->log_buf) {
6843 			log_buf = prog->log_buf;
6844 			log_buf_size = prog->log_size;
6845 			own_log_buf = false;
6846 		} else if (obj->log_buf) {
6847 			log_buf = obj->log_buf;
6848 			log_buf_size = obj->log_size;
6849 			own_log_buf = false;
6850 		} else {
6851 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6852 			tmp = realloc(log_buf, log_buf_size);
6853 			if (!tmp) {
6854 				ret = -ENOMEM;
6855 				goto out;
6856 			}
6857 			log_buf = tmp;
6858 			log_buf[0] = '\0';
6859 			own_log_buf = true;
6860 		}
6861 	}
6862 
6863 	load_attr.log_buf = log_buf;
6864 	load_attr.log_size = log_buf_size;
6865 	load_attr.log_level = log_level;
6866 
6867 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6868 	if (ret >= 0) {
6869 		if (log_level && own_log_buf) {
6870 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6871 				 prog->name, log_buf);
6872 		}
6873 
6874 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6875 			struct bpf_map *map;
6876 			int i;
6877 
6878 			for (i = 0; i < obj->nr_maps; i++) {
6879 				map = &prog->obj->maps[i];
6880 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6881 					continue;
6882 
6883 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6884 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6885 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6886 						prog->name, map->real_name, cp);
6887 					/* Don't fail hard if can't bind rodata. */
6888 				}
6889 			}
6890 		}
6891 
6892 		*prog_fd = ret;
6893 		ret = 0;
6894 		goto out;
6895 	}
6896 
6897 	if (log_level == 0) {
6898 		log_level = 1;
6899 		goto retry_load;
6900 	}
6901 	/* On ENOSPC, increase log buffer size and retry, unless custom
6902 	 * log_buf is specified.
6903 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6904 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6905 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6906 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6907 	 */
6908 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6909 		goto retry_load;
6910 
6911 	ret = -errno;
6912 
6913 	/* post-process verifier log to improve error descriptions */
6914 	fixup_verifier_log(prog, log_buf, log_buf_size);
6915 
6916 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6917 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6918 	pr_perm_msg(ret);
6919 
6920 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6921 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6922 			prog->name, log_buf);
6923 	}
6924 
6925 out:
6926 	if (own_log_buf)
6927 		free(log_buf);
6928 	return ret;
6929 }
6930 
6931 static char *find_prev_line(char *buf, char *cur)
6932 {
6933 	char *p;
6934 
6935 	if (cur == buf) /* end of a log buf */
6936 		return NULL;
6937 
6938 	p = cur - 1;
6939 	while (p - 1 >= buf && *(p - 1) != '\n')
6940 		p--;
6941 
6942 	return p;
6943 }
6944 
6945 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6946 		      char *orig, size_t orig_sz, const char *patch)
6947 {
6948 	/* size of the remaining log content to the right from the to-be-replaced part */
6949 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6950 	size_t patch_sz = strlen(patch);
6951 
6952 	if (patch_sz != orig_sz) {
6953 		/* If patch line(s) are longer than original piece of verifier log,
6954 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
6955 		 * starting from after to-be-replaced part of the log.
6956 		 *
6957 		 * If patch line(s) are shorter than original piece of verifier log,
6958 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
6959 		 * starting from after to-be-replaced part of the log
6960 		 *
6961 		 * We need to be careful about not overflowing available
6962 		 * buf_sz capacity. If that's the case, we'll truncate the end
6963 		 * of the original log, as necessary.
6964 		 */
6965 		if (patch_sz > orig_sz) {
6966 			if (orig + patch_sz >= buf + buf_sz) {
6967 				/* patch is big enough to cover remaining space completely */
6968 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6969 				rem_sz = 0;
6970 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
6971 				/* patch causes part of remaining log to be truncated */
6972 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6973 			}
6974 		}
6975 		/* shift remaining log to the right by calculated amount */
6976 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6977 	}
6978 
6979 	memcpy(orig, patch, patch_sz);
6980 }
6981 
6982 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6983 				       char *buf, size_t buf_sz, size_t log_sz,
6984 				       char *line1, char *line2, char *line3)
6985 {
6986 	/* Expected log for failed and not properly guarded CO-RE relocation:
6987 	 * line1 -> 123: (85) call unknown#195896080
6988 	 * line2 -> invalid func unknown#195896080
6989 	 * line3 -> <anything else or end of buffer>
6990 	 *
6991 	 * "123" is the index of the instruction that was poisoned. We extract
6992 	 * instruction index to find corresponding CO-RE relocation and
6993 	 * replace this part of the log with more relevant information about
6994 	 * failed CO-RE relocation.
6995 	 */
6996 	const struct bpf_core_relo *relo;
6997 	struct bpf_core_spec spec;
6998 	char patch[512], spec_buf[256];
6999 	int insn_idx, err, spec_len;
7000 
7001 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7002 		return;
7003 
7004 	relo = find_relo_core(prog, insn_idx);
7005 	if (!relo)
7006 		return;
7007 
7008 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7009 	if (err)
7010 		return;
7011 
7012 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7013 	snprintf(patch, sizeof(patch),
7014 		 "%d: <invalid CO-RE relocation>\n"
7015 		 "failed to resolve CO-RE relocation %s%s\n",
7016 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7017 
7018 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7019 }
7020 
7021 static void fixup_log_missing_map_load(struct bpf_program *prog,
7022 				       char *buf, size_t buf_sz, size_t log_sz,
7023 				       char *line1, char *line2, char *line3)
7024 {
7025 	/* Expected log for failed and not properly guarded CO-RE relocation:
7026 	 * line1 -> 123: (85) call unknown#2001000345
7027 	 * line2 -> invalid func unknown#2001000345
7028 	 * line3 -> <anything else or end of buffer>
7029 	 *
7030 	 * "123" is the index of the instruction that was poisoned.
7031 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7032 	 */
7033 	struct bpf_object *obj = prog->obj;
7034 	const struct bpf_map *map;
7035 	int insn_idx, map_idx;
7036 	char patch[128];
7037 
7038 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7039 		return;
7040 
7041 	map_idx -= MAP_LDIMM64_POISON_BASE;
7042 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7043 		return;
7044 	map = &obj->maps[map_idx];
7045 
7046 	snprintf(patch, sizeof(patch),
7047 		 "%d: <invalid BPF map reference>\n"
7048 		 "BPF map '%s' is referenced but wasn't created\n",
7049 		 insn_idx, map->name);
7050 
7051 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7052 }
7053 
7054 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7055 {
7056 	/* look for familiar error patterns in last N lines of the log */
7057 	const size_t max_last_line_cnt = 10;
7058 	char *prev_line, *cur_line, *next_line;
7059 	size_t log_sz;
7060 	int i;
7061 
7062 	if (!buf)
7063 		return;
7064 
7065 	log_sz = strlen(buf) + 1;
7066 	next_line = buf + log_sz - 1;
7067 
7068 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7069 		cur_line = find_prev_line(buf, next_line);
7070 		if (!cur_line)
7071 			return;
7072 
7073 		/* failed CO-RE relocation case */
7074 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7075 			prev_line = find_prev_line(buf, cur_line);
7076 			if (!prev_line)
7077 				continue;
7078 
7079 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7080 						   prev_line, cur_line, next_line);
7081 			return;
7082 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7083 			prev_line = find_prev_line(buf, cur_line);
7084 			if (!prev_line)
7085 				continue;
7086 
7087 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7088 						   prev_line, cur_line, next_line);
7089 			return;
7090 		}
7091 	}
7092 }
7093 
7094 static int bpf_program_record_relos(struct bpf_program *prog)
7095 {
7096 	struct bpf_object *obj = prog->obj;
7097 	int i;
7098 
7099 	for (i = 0; i < prog->nr_reloc; i++) {
7100 		struct reloc_desc *relo = &prog->reloc_desc[i];
7101 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7102 		int kind;
7103 
7104 		switch (relo->type) {
7105 		case RELO_EXTERN_LD64:
7106 			if (ext->type != EXT_KSYM)
7107 				continue;
7108 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7109 				BTF_KIND_VAR : BTF_KIND_FUNC;
7110 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7111 					       ext->is_weak, !ext->ksym.type_id,
7112 					       true, kind, relo->insn_idx);
7113 			break;
7114 		case RELO_EXTERN_CALL:
7115 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7116 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7117 					       relo->insn_idx);
7118 			break;
7119 		case RELO_CORE: {
7120 			struct bpf_core_relo cr = {
7121 				.insn_off = relo->insn_idx * 8,
7122 				.type_id = relo->core_relo->type_id,
7123 				.access_str_off = relo->core_relo->access_str_off,
7124 				.kind = relo->core_relo->kind,
7125 			};
7126 
7127 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7128 			break;
7129 		}
7130 		default:
7131 			continue;
7132 		}
7133 	}
7134 	return 0;
7135 }
7136 
7137 static int
7138 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7139 {
7140 	struct bpf_program *prog;
7141 	size_t i;
7142 	int err;
7143 
7144 	for (i = 0; i < obj->nr_programs; i++) {
7145 		prog = &obj->programs[i];
7146 		err = bpf_object__sanitize_prog(obj, prog);
7147 		if (err)
7148 			return err;
7149 	}
7150 
7151 	for (i = 0; i < obj->nr_programs; i++) {
7152 		prog = &obj->programs[i];
7153 		if (prog_is_subprog(obj, prog))
7154 			continue;
7155 		if (!prog->autoload) {
7156 			pr_debug("prog '%s': skipped loading\n", prog->name);
7157 			continue;
7158 		}
7159 		prog->log_level |= log_level;
7160 
7161 		if (obj->gen_loader)
7162 			bpf_program_record_relos(prog);
7163 
7164 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7165 					   obj->license, obj->kern_version, &prog->fd);
7166 		if (err) {
7167 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7168 			return err;
7169 		}
7170 	}
7171 
7172 	bpf_object__free_relocs(obj);
7173 	return 0;
7174 }
7175 
7176 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7177 
7178 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7179 {
7180 	struct bpf_program *prog;
7181 	int err;
7182 
7183 	bpf_object__for_each_program(prog, obj) {
7184 		prog->sec_def = find_sec_def(prog->sec_name);
7185 		if (!prog->sec_def) {
7186 			/* couldn't guess, but user might manually specify */
7187 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7188 				prog->name, prog->sec_name);
7189 			continue;
7190 		}
7191 
7192 		prog->type = prog->sec_def->prog_type;
7193 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7194 
7195 		/* sec_def can have custom callback which should be called
7196 		 * after bpf_program is initialized to adjust its properties
7197 		 */
7198 		if (prog->sec_def->prog_setup_fn) {
7199 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7200 			if (err < 0) {
7201 				pr_warn("prog '%s': failed to initialize: %d\n",
7202 					prog->name, err);
7203 				return err;
7204 			}
7205 		}
7206 	}
7207 
7208 	return 0;
7209 }
7210 
7211 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7212 					  const struct bpf_object_open_opts *opts)
7213 {
7214 	const char *obj_name, *kconfig, *btf_tmp_path;
7215 	struct bpf_object *obj;
7216 	char tmp_name[64];
7217 	int err;
7218 	char *log_buf;
7219 	size_t log_size;
7220 	__u32 log_level;
7221 
7222 	if (elf_version(EV_CURRENT) == EV_NONE) {
7223 		pr_warn("failed to init libelf for %s\n",
7224 			path ? : "(mem buf)");
7225 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7226 	}
7227 
7228 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7229 		return ERR_PTR(-EINVAL);
7230 
7231 	obj_name = OPTS_GET(opts, object_name, NULL);
7232 	if (obj_buf) {
7233 		if (!obj_name) {
7234 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7235 				 (unsigned long)obj_buf,
7236 				 (unsigned long)obj_buf_sz);
7237 			obj_name = tmp_name;
7238 		}
7239 		path = obj_name;
7240 		pr_debug("loading object '%s' from buffer\n", obj_name);
7241 	}
7242 
7243 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7244 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7245 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7246 	if (log_size > UINT_MAX)
7247 		return ERR_PTR(-EINVAL);
7248 	if (log_size && !log_buf)
7249 		return ERR_PTR(-EINVAL);
7250 
7251 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7252 	if (IS_ERR(obj))
7253 		return obj;
7254 
7255 	obj->log_buf = log_buf;
7256 	obj->log_size = log_size;
7257 	obj->log_level = log_level;
7258 
7259 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7260 	if (btf_tmp_path) {
7261 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7262 			err = -ENAMETOOLONG;
7263 			goto out;
7264 		}
7265 		obj->btf_custom_path = strdup(btf_tmp_path);
7266 		if (!obj->btf_custom_path) {
7267 			err = -ENOMEM;
7268 			goto out;
7269 		}
7270 	}
7271 
7272 	kconfig = OPTS_GET(opts, kconfig, NULL);
7273 	if (kconfig) {
7274 		obj->kconfig = strdup(kconfig);
7275 		if (!obj->kconfig) {
7276 			err = -ENOMEM;
7277 			goto out;
7278 		}
7279 	}
7280 
7281 	err = bpf_object__elf_init(obj);
7282 	err = err ? : bpf_object__check_endianness(obj);
7283 	err = err ? : bpf_object__elf_collect(obj);
7284 	err = err ? : bpf_object__collect_externs(obj);
7285 	err = err ? : bpf_object_fixup_btf(obj);
7286 	err = err ? : bpf_object__init_maps(obj, opts);
7287 	err = err ? : bpf_object_init_progs(obj, opts);
7288 	err = err ? : bpf_object__collect_relos(obj);
7289 	if (err)
7290 		goto out;
7291 
7292 	bpf_object__elf_finish(obj);
7293 
7294 	return obj;
7295 out:
7296 	bpf_object__close(obj);
7297 	return ERR_PTR(err);
7298 }
7299 
7300 struct bpf_object *
7301 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7302 {
7303 	if (!path)
7304 		return libbpf_err_ptr(-EINVAL);
7305 
7306 	pr_debug("loading %s\n", path);
7307 
7308 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7309 }
7310 
7311 struct bpf_object *bpf_object__open(const char *path)
7312 {
7313 	return bpf_object__open_file(path, NULL);
7314 }
7315 
7316 struct bpf_object *
7317 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7318 		     const struct bpf_object_open_opts *opts)
7319 {
7320 	if (!obj_buf || obj_buf_sz == 0)
7321 		return libbpf_err_ptr(-EINVAL);
7322 
7323 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7324 }
7325 
7326 static int bpf_object_unload(struct bpf_object *obj)
7327 {
7328 	size_t i;
7329 
7330 	if (!obj)
7331 		return libbpf_err(-EINVAL);
7332 
7333 	for (i = 0; i < obj->nr_maps; i++) {
7334 		zclose(obj->maps[i].fd);
7335 		if (obj->maps[i].st_ops)
7336 			zfree(&obj->maps[i].st_ops->kern_vdata);
7337 	}
7338 
7339 	for (i = 0; i < obj->nr_programs; i++)
7340 		bpf_program__unload(&obj->programs[i]);
7341 
7342 	return 0;
7343 }
7344 
7345 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7346 {
7347 	struct bpf_map *m;
7348 
7349 	bpf_object__for_each_map(m, obj) {
7350 		if (!bpf_map__is_internal(m))
7351 			continue;
7352 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7353 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7354 	}
7355 
7356 	return 0;
7357 }
7358 
7359 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7360 {
7361 	char sym_type, sym_name[500];
7362 	unsigned long long sym_addr;
7363 	int ret, err = 0;
7364 	FILE *f;
7365 
7366 	f = fopen("/proc/kallsyms", "r");
7367 	if (!f) {
7368 		err = -errno;
7369 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7370 		return err;
7371 	}
7372 
7373 	while (true) {
7374 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7375 			     &sym_addr, &sym_type, sym_name);
7376 		if (ret == EOF && feof(f))
7377 			break;
7378 		if (ret != 3) {
7379 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7380 			err = -EINVAL;
7381 			break;
7382 		}
7383 
7384 		err = cb(sym_addr, sym_type, sym_name, ctx);
7385 		if (err)
7386 			break;
7387 	}
7388 
7389 	fclose(f);
7390 	return err;
7391 }
7392 
7393 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7394 		       const char *sym_name, void *ctx)
7395 {
7396 	struct bpf_object *obj = ctx;
7397 	const struct btf_type *t;
7398 	struct extern_desc *ext;
7399 
7400 	ext = find_extern_by_name(obj, sym_name);
7401 	if (!ext || ext->type != EXT_KSYM)
7402 		return 0;
7403 
7404 	t = btf__type_by_id(obj->btf, ext->btf_id);
7405 	if (!btf_is_var(t))
7406 		return 0;
7407 
7408 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7409 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7410 			sym_name, ext->ksym.addr, sym_addr);
7411 		return -EINVAL;
7412 	}
7413 	if (!ext->is_set) {
7414 		ext->is_set = true;
7415 		ext->ksym.addr = sym_addr;
7416 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7417 	}
7418 	return 0;
7419 }
7420 
7421 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7422 {
7423 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7424 }
7425 
7426 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7427 			    __u16 kind, struct btf **res_btf,
7428 			    struct module_btf **res_mod_btf)
7429 {
7430 	struct module_btf *mod_btf;
7431 	struct btf *btf;
7432 	int i, id, err;
7433 
7434 	btf = obj->btf_vmlinux;
7435 	mod_btf = NULL;
7436 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7437 
7438 	if (id == -ENOENT) {
7439 		err = load_module_btfs(obj);
7440 		if (err)
7441 			return err;
7442 
7443 		for (i = 0; i < obj->btf_module_cnt; i++) {
7444 			/* we assume module_btf's BTF FD is always >0 */
7445 			mod_btf = &obj->btf_modules[i];
7446 			btf = mod_btf->btf;
7447 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7448 			if (id != -ENOENT)
7449 				break;
7450 		}
7451 	}
7452 	if (id <= 0)
7453 		return -ESRCH;
7454 
7455 	*res_btf = btf;
7456 	*res_mod_btf = mod_btf;
7457 	return id;
7458 }
7459 
7460 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7461 					       struct extern_desc *ext)
7462 {
7463 	const struct btf_type *targ_var, *targ_type;
7464 	__u32 targ_type_id, local_type_id;
7465 	struct module_btf *mod_btf = NULL;
7466 	const char *targ_var_name;
7467 	struct btf *btf = NULL;
7468 	int id, err;
7469 
7470 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7471 	if (id < 0) {
7472 		if (id == -ESRCH && ext->is_weak)
7473 			return 0;
7474 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7475 			ext->name);
7476 		return id;
7477 	}
7478 
7479 	/* find local type_id */
7480 	local_type_id = ext->ksym.type_id;
7481 
7482 	/* find target type_id */
7483 	targ_var = btf__type_by_id(btf, id);
7484 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7485 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7486 
7487 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7488 					btf, targ_type_id);
7489 	if (err <= 0) {
7490 		const struct btf_type *local_type;
7491 		const char *targ_name, *local_name;
7492 
7493 		local_type = btf__type_by_id(obj->btf, local_type_id);
7494 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7495 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7496 
7497 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7498 			ext->name, local_type_id,
7499 			btf_kind_str(local_type), local_name, targ_type_id,
7500 			btf_kind_str(targ_type), targ_name);
7501 		return -EINVAL;
7502 	}
7503 
7504 	ext->is_set = true;
7505 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7506 	ext->ksym.kernel_btf_id = id;
7507 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7508 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7509 
7510 	return 0;
7511 }
7512 
7513 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7514 						struct extern_desc *ext)
7515 {
7516 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7517 	struct module_btf *mod_btf = NULL;
7518 	const struct btf_type *kern_func;
7519 	struct btf *kern_btf = NULL;
7520 	int ret;
7521 
7522 	local_func_proto_id = ext->ksym.type_id;
7523 
7524 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7525 	if (kfunc_id < 0) {
7526 		if (kfunc_id == -ESRCH && ext->is_weak)
7527 			return 0;
7528 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7529 			ext->name);
7530 		return kfunc_id;
7531 	}
7532 
7533 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7534 	kfunc_proto_id = kern_func->type;
7535 
7536 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7537 					kern_btf, kfunc_proto_id);
7538 	if (ret <= 0) {
7539 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7540 			ext->name, local_func_proto_id, kfunc_proto_id);
7541 		return -EINVAL;
7542 	}
7543 
7544 	/* set index for module BTF fd in fd_array, if unset */
7545 	if (mod_btf && !mod_btf->fd_array_idx) {
7546 		/* insn->off is s16 */
7547 		if (obj->fd_array_cnt == INT16_MAX) {
7548 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7549 				ext->name, mod_btf->fd_array_idx);
7550 			return -E2BIG;
7551 		}
7552 		/* Cannot use index 0 for module BTF fd */
7553 		if (!obj->fd_array_cnt)
7554 			obj->fd_array_cnt = 1;
7555 
7556 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7557 					obj->fd_array_cnt + 1);
7558 		if (ret)
7559 			return ret;
7560 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7561 		/* we assume module BTF FD is always >0 */
7562 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7563 	}
7564 
7565 	ext->is_set = true;
7566 	ext->ksym.kernel_btf_id = kfunc_id;
7567 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7568 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7569 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7570 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7571 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7572 	 */
7573 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7574 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7575 		 ext->name, kfunc_id);
7576 
7577 	return 0;
7578 }
7579 
7580 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7581 {
7582 	const struct btf_type *t;
7583 	struct extern_desc *ext;
7584 	int i, err;
7585 
7586 	for (i = 0; i < obj->nr_extern; i++) {
7587 		ext = &obj->externs[i];
7588 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7589 			continue;
7590 
7591 		if (obj->gen_loader) {
7592 			ext->is_set = true;
7593 			ext->ksym.kernel_btf_obj_fd = 0;
7594 			ext->ksym.kernel_btf_id = 0;
7595 			continue;
7596 		}
7597 		t = btf__type_by_id(obj->btf, ext->btf_id);
7598 		if (btf_is_var(t))
7599 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7600 		else
7601 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7602 		if (err)
7603 			return err;
7604 	}
7605 	return 0;
7606 }
7607 
7608 static int bpf_object__resolve_externs(struct bpf_object *obj,
7609 				       const char *extra_kconfig)
7610 {
7611 	bool need_config = false, need_kallsyms = false;
7612 	bool need_vmlinux_btf = false;
7613 	struct extern_desc *ext;
7614 	void *kcfg_data = NULL;
7615 	int err, i;
7616 
7617 	if (obj->nr_extern == 0)
7618 		return 0;
7619 
7620 	if (obj->kconfig_map_idx >= 0)
7621 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7622 
7623 	for (i = 0; i < obj->nr_extern; i++) {
7624 		ext = &obj->externs[i];
7625 
7626 		if (ext->type == EXT_KSYM) {
7627 			if (ext->ksym.type_id)
7628 				need_vmlinux_btf = true;
7629 			else
7630 				need_kallsyms = true;
7631 			continue;
7632 		} else if (ext->type == EXT_KCFG) {
7633 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7634 			__u64 value = 0;
7635 
7636 			/* Kconfig externs need actual /proc/config.gz */
7637 			if (str_has_pfx(ext->name, "CONFIG_")) {
7638 				need_config = true;
7639 				continue;
7640 			}
7641 
7642 			/* Virtual kcfg externs are customly handled by libbpf */
7643 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7644 				value = get_kernel_version();
7645 				if (!value) {
7646 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7647 					return -EINVAL;
7648 				}
7649 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7650 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7651 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7652 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7653 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7654 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7655 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7656 				 * customly by libbpf (their values don't come from Kconfig).
7657 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7658 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7659 				 * externs.
7660 				 */
7661 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7662 				return -EINVAL;
7663 			}
7664 
7665 			err = set_kcfg_value_num(ext, ext_ptr, value);
7666 			if (err)
7667 				return err;
7668 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7669 				 ext->name, (long long)value);
7670 		} else {
7671 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7672 			return -EINVAL;
7673 		}
7674 	}
7675 	if (need_config && extra_kconfig) {
7676 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7677 		if (err)
7678 			return -EINVAL;
7679 		need_config = false;
7680 		for (i = 0; i < obj->nr_extern; i++) {
7681 			ext = &obj->externs[i];
7682 			if (ext->type == EXT_KCFG && !ext->is_set) {
7683 				need_config = true;
7684 				break;
7685 			}
7686 		}
7687 	}
7688 	if (need_config) {
7689 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7690 		if (err)
7691 			return -EINVAL;
7692 	}
7693 	if (need_kallsyms) {
7694 		err = bpf_object__read_kallsyms_file(obj);
7695 		if (err)
7696 			return -EINVAL;
7697 	}
7698 	if (need_vmlinux_btf) {
7699 		err = bpf_object__resolve_ksyms_btf_id(obj);
7700 		if (err)
7701 			return -EINVAL;
7702 	}
7703 	for (i = 0; i < obj->nr_extern; i++) {
7704 		ext = &obj->externs[i];
7705 
7706 		if (!ext->is_set && !ext->is_weak) {
7707 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7708 			return -ESRCH;
7709 		} else if (!ext->is_set) {
7710 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7711 				 ext->name);
7712 		}
7713 	}
7714 
7715 	return 0;
7716 }
7717 
7718 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7719 {
7720 	struct bpf_struct_ops *st_ops;
7721 	__u32 i;
7722 
7723 	st_ops = map->st_ops;
7724 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7725 		struct bpf_program *prog = st_ops->progs[i];
7726 		void *kern_data;
7727 		int prog_fd;
7728 
7729 		if (!prog)
7730 			continue;
7731 
7732 		prog_fd = bpf_program__fd(prog);
7733 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7734 		*(unsigned long *)kern_data = prog_fd;
7735 	}
7736 }
7737 
7738 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7739 {
7740 	int i;
7741 
7742 	for (i = 0; i < obj->nr_maps; i++)
7743 		if (bpf_map__is_struct_ops(&obj->maps[i]))
7744 			bpf_map_prepare_vdata(&obj->maps[i]);
7745 
7746 	return 0;
7747 }
7748 
7749 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7750 {
7751 	int err, i;
7752 
7753 	if (!obj)
7754 		return libbpf_err(-EINVAL);
7755 
7756 	if (obj->loaded) {
7757 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7758 		return libbpf_err(-EINVAL);
7759 	}
7760 
7761 	if (obj->gen_loader)
7762 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7763 
7764 	err = bpf_object__probe_loading(obj);
7765 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7766 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7767 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7768 	err = err ? : bpf_object__sanitize_maps(obj);
7769 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7770 	err = err ? : bpf_object__create_maps(obj);
7771 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7772 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7773 	err = err ? : bpf_object_init_prog_arrays(obj);
7774 	err = err ? : bpf_object_prepare_struct_ops(obj);
7775 
7776 	if (obj->gen_loader) {
7777 		/* reset FDs */
7778 		if (obj->btf)
7779 			btf__set_fd(obj->btf, -1);
7780 		for (i = 0; i < obj->nr_maps; i++)
7781 			obj->maps[i].fd = -1;
7782 		if (!err)
7783 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7784 	}
7785 
7786 	/* clean up fd_array */
7787 	zfree(&obj->fd_array);
7788 
7789 	/* clean up module BTFs */
7790 	for (i = 0; i < obj->btf_module_cnt; i++) {
7791 		close(obj->btf_modules[i].fd);
7792 		btf__free(obj->btf_modules[i].btf);
7793 		free(obj->btf_modules[i].name);
7794 	}
7795 	free(obj->btf_modules);
7796 
7797 	/* clean up vmlinux BTF */
7798 	btf__free(obj->btf_vmlinux);
7799 	obj->btf_vmlinux = NULL;
7800 
7801 	obj->loaded = true; /* doesn't matter if successfully or not */
7802 
7803 	if (err)
7804 		goto out;
7805 
7806 	return 0;
7807 out:
7808 	/* unpin any maps that were auto-pinned during load */
7809 	for (i = 0; i < obj->nr_maps; i++)
7810 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7811 			bpf_map__unpin(&obj->maps[i], NULL);
7812 
7813 	bpf_object_unload(obj);
7814 	pr_warn("failed to load object '%s'\n", obj->path);
7815 	return libbpf_err(err);
7816 }
7817 
7818 int bpf_object__load(struct bpf_object *obj)
7819 {
7820 	return bpf_object_load(obj, 0, NULL);
7821 }
7822 
7823 static int make_parent_dir(const char *path)
7824 {
7825 	char *cp, errmsg[STRERR_BUFSIZE];
7826 	char *dname, *dir;
7827 	int err = 0;
7828 
7829 	dname = strdup(path);
7830 	if (dname == NULL)
7831 		return -ENOMEM;
7832 
7833 	dir = dirname(dname);
7834 	if (mkdir(dir, 0700) && errno != EEXIST)
7835 		err = -errno;
7836 
7837 	free(dname);
7838 	if (err) {
7839 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7840 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7841 	}
7842 	return err;
7843 }
7844 
7845 static int check_path(const char *path)
7846 {
7847 	char *cp, errmsg[STRERR_BUFSIZE];
7848 	struct statfs st_fs;
7849 	char *dname, *dir;
7850 	int err = 0;
7851 
7852 	if (path == NULL)
7853 		return -EINVAL;
7854 
7855 	dname = strdup(path);
7856 	if (dname == NULL)
7857 		return -ENOMEM;
7858 
7859 	dir = dirname(dname);
7860 	if (statfs(dir, &st_fs)) {
7861 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7862 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7863 		err = -errno;
7864 	}
7865 	free(dname);
7866 
7867 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7868 		pr_warn("specified path %s is not on BPF FS\n", path);
7869 		err = -EINVAL;
7870 	}
7871 
7872 	return err;
7873 }
7874 
7875 int bpf_program__pin(struct bpf_program *prog, const char *path)
7876 {
7877 	char *cp, errmsg[STRERR_BUFSIZE];
7878 	int err;
7879 
7880 	if (prog->fd < 0) {
7881 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7882 		return libbpf_err(-EINVAL);
7883 	}
7884 
7885 	err = make_parent_dir(path);
7886 	if (err)
7887 		return libbpf_err(err);
7888 
7889 	err = check_path(path);
7890 	if (err)
7891 		return libbpf_err(err);
7892 
7893 	if (bpf_obj_pin(prog->fd, path)) {
7894 		err = -errno;
7895 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7896 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7897 		return libbpf_err(err);
7898 	}
7899 
7900 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7901 	return 0;
7902 }
7903 
7904 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7905 {
7906 	int err;
7907 
7908 	if (prog->fd < 0) {
7909 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7910 		return libbpf_err(-EINVAL);
7911 	}
7912 
7913 	err = check_path(path);
7914 	if (err)
7915 		return libbpf_err(err);
7916 
7917 	err = unlink(path);
7918 	if (err)
7919 		return libbpf_err(-errno);
7920 
7921 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7922 	return 0;
7923 }
7924 
7925 int bpf_map__pin(struct bpf_map *map, const char *path)
7926 {
7927 	char *cp, errmsg[STRERR_BUFSIZE];
7928 	int err;
7929 
7930 	if (map == NULL) {
7931 		pr_warn("invalid map pointer\n");
7932 		return libbpf_err(-EINVAL);
7933 	}
7934 
7935 	if (map->pin_path) {
7936 		if (path && strcmp(path, map->pin_path)) {
7937 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7938 				bpf_map__name(map), map->pin_path, path);
7939 			return libbpf_err(-EINVAL);
7940 		} else if (map->pinned) {
7941 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7942 				 bpf_map__name(map), map->pin_path);
7943 			return 0;
7944 		}
7945 	} else {
7946 		if (!path) {
7947 			pr_warn("missing a path to pin map '%s' at\n",
7948 				bpf_map__name(map));
7949 			return libbpf_err(-EINVAL);
7950 		} else if (map->pinned) {
7951 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7952 			return libbpf_err(-EEXIST);
7953 		}
7954 
7955 		map->pin_path = strdup(path);
7956 		if (!map->pin_path) {
7957 			err = -errno;
7958 			goto out_err;
7959 		}
7960 	}
7961 
7962 	err = make_parent_dir(map->pin_path);
7963 	if (err)
7964 		return libbpf_err(err);
7965 
7966 	err = check_path(map->pin_path);
7967 	if (err)
7968 		return libbpf_err(err);
7969 
7970 	if (bpf_obj_pin(map->fd, map->pin_path)) {
7971 		err = -errno;
7972 		goto out_err;
7973 	}
7974 
7975 	map->pinned = true;
7976 	pr_debug("pinned map '%s'\n", map->pin_path);
7977 
7978 	return 0;
7979 
7980 out_err:
7981 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7982 	pr_warn("failed to pin map: %s\n", cp);
7983 	return libbpf_err(err);
7984 }
7985 
7986 int bpf_map__unpin(struct bpf_map *map, const char *path)
7987 {
7988 	int err;
7989 
7990 	if (map == NULL) {
7991 		pr_warn("invalid map pointer\n");
7992 		return libbpf_err(-EINVAL);
7993 	}
7994 
7995 	if (map->pin_path) {
7996 		if (path && strcmp(path, map->pin_path)) {
7997 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7998 				bpf_map__name(map), map->pin_path, path);
7999 			return libbpf_err(-EINVAL);
8000 		}
8001 		path = map->pin_path;
8002 	} else if (!path) {
8003 		pr_warn("no path to unpin map '%s' from\n",
8004 			bpf_map__name(map));
8005 		return libbpf_err(-EINVAL);
8006 	}
8007 
8008 	err = check_path(path);
8009 	if (err)
8010 		return libbpf_err(err);
8011 
8012 	err = unlink(path);
8013 	if (err != 0)
8014 		return libbpf_err(-errno);
8015 
8016 	map->pinned = false;
8017 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8018 
8019 	return 0;
8020 }
8021 
8022 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8023 {
8024 	char *new = NULL;
8025 
8026 	if (path) {
8027 		new = strdup(path);
8028 		if (!new)
8029 			return libbpf_err(-errno);
8030 	}
8031 
8032 	free(map->pin_path);
8033 	map->pin_path = new;
8034 	return 0;
8035 }
8036 
8037 __alias(bpf_map__pin_path)
8038 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8039 
8040 const char *bpf_map__pin_path(const struct bpf_map *map)
8041 {
8042 	return map->pin_path;
8043 }
8044 
8045 bool bpf_map__is_pinned(const struct bpf_map *map)
8046 {
8047 	return map->pinned;
8048 }
8049 
8050 static void sanitize_pin_path(char *s)
8051 {
8052 	/* bpffs disallows periods in path names */
8053 	while (*s) {
8054 		if (*s == '.')
8055 			*s = '_';
8056 		s++;
8057 	}
8058 }
8059 
8060 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8061 {
8062 	struct bpf_map *map;
8063 	int err;
8064 
8065 	if (!obj)
8066 		return libbpf_err(-ENOENT);
8067 
8068 	if (!obj->loaded) {
8069 		pr_warn("object not yet loaded; load it first\n");
8070 		return libbpf_err(-ENOENT);
8071 	}
8072 
8073 	bpf_object__for_each_map(map, obj) {
8074 		char *pin_path = NULL;
8075 		char buf[PATH_MAX];
8076 
8077 		if (!map->autocreate)
8078 			continue;
8079 
8080 		if (path) {
8081 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8082 			if (err)
8083 				goto err_unpin_maps;
8084 			sanitize_pin_path(buf);
8085 			pin_path = buf;
8086 		} else if (!map->pin_path) {
8087 			continue;
8088 		}
8089 
8090 		err = bpf_map__pin(map, pin_path);
8091 		if (err)
8092 			goto err_unpin_maps;
8093 	}
8094 
8095 	return 0;
8096 
8097 err_unpin_maps:
8098 	while ((map = bpf_object__prev_map(obj, map))) {
8099 		if (!map->pin_path)
8100 			continue;
8101 
8102 		bpf_map__unpin(map, NULL);
8103 	}
8104 
8105 	return libbpf_err(err);
8106 }
8107 
8108 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8109 {
8110 	struct bpf_map *map;
8111 	int err;
8112 
8113 	if (!obj)
8114 		return libbpf_err(-ENOENT);
8115 
8116 	bpf_object__for_each_map(map, obj) {
8117 		char *pin_path = NULL;
8118 		char buf[PATH_MAX];
8119 
8120 		if (path) {
8121 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8122 			if (err)
8123 				return libbpf_err(err);
8124 			sanitize_pin_path(buf);
8125 			pin_path = buf;
8126 		} else if (!map->pin_path) {
8127 			continue;
8128 		}
8129 
8130 		err = bpf_map__unpin(map, pin_path);
8131 		if (err)
8132 			return libbpf_err(err);
8133 	}
8134 
8135 	return 0;
8136 }
8137 
8138 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8139 {
8140 	struct bpf_program *prog;
8141 	char buf[PATH_MAX];
8142 	int err;
8143 
8144 	if (!obj)
8145 		return libbpf_err(-ENOENT);
8146 
8147 	if (!obj->loaded) {
8148 		pr_warn("object not yet loaded; load it first\n");
8149 		return libbpf_err(-ENOENT);
8150 	}
8151 
8152 	bpf_object__for_each_program(prog, obj) {
8153 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8154 		if (err)
8155 			goto err_unpin_programs;
8156 
8157 		err = bpf_program__pin(prog, buf);
8158 		if (err)
8159 			goto err_unpin_programs;
8160 	}
8161 
8162 	return 0;
8163 
8164 err_unpin_programs:
8165 	while ((prog = bpf_object__prev_program(obj, prog))) {
8166 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8167 			continue;
8168 
8169 		bpf_program__unpin(prog, buf);
8170 	}
8171 
8172 	return libbpf_err(err);
8173 }
8174 
8175 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8176 {
8177 	struct bpf_program *prog;
8178 	int err;
8179 
8180 	if (!obj)
8181 		return libbpf_err(-ENOENT);
8182 
8183 	bpf_object__for_each_program(prog, obj) {
8184 		char buf[PATH_MAX];
8185 
8186 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8187 		if (err)
8188 			return libbpf_err(err);
8189 
8190 		err = bpf_program__unpin(prog, buf);
8191 		if (err)
8192 			return libbpf_err(err);
8193 	}
8194 
8195 	return 0;
8196 }
8197 
8198 int bpf_object__pin(struct bpf_object *obj, const char *path)
8199 {
8200 	int err;
8201 
8202 	err = bpf_object__pin_maps(obj, path);
8203 	if (err)
8204 		return libbpf_err(err);
8205 
8206 	err = bpf_object__pin_programs(obj, path);
8207 	if (err) {
8208 		bpf_object__unpin_maps(obj, path);
8209 		return libbpf_err(err);
8210 	}
8211 
8212 	return 0;
8213 }
8214 
8215 static void bpf_map__destroy(struct bpf_map *map)
8216 {
8217 	if (map->inner_map) {
8218 		bpf_map__destroy(map->inner_map);
8219 		zfree(&map->inner_map);
8220 	}
8221 
8222 	zfree(&map->init_slots);
8223 	map->init_slots_sz = 0;
8224 
8225 	if (map->mmaped) {
8226 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8227 		map->mmaped = NULL;
8228 	}
8229 
8230 	if (map->st_ops) {
8231 		zfree(&map->st_ops->data);
8232 		zfree(&map->st_ops->progs);
8233 		zfree(&map->st_ops->kern_func_off);
8234 		zfree(&map->st_ops);
8235 	}
8236 
8237 	zfree(&map->name);
8238 	zfree(&map->real_name);
8239 	zfree(&map->pin_path);
8240 
8241 	if (map->fd >= 0)
8242 		zclose(map->fd);
8243 }
8244 
8245 void bpf_object__close(struct bpf_object *obj)
8246 {
8247 	size_t i;
8248 
8249 	if (IS_ERR_OR_NULL(obj))
8250 		return;
8251 
8252 	usdt_manager_free(obj->usdt_man);
8253 	obj->usdt_man = NULL;
8254 
8255 	bpf_gen__free(obj->gen_loader);
8256 	bpf_object__elf_finish(obj);
8257 	bpf_object_unload(obj);
8258 	btf__free(obj->btf);
8259 	btf_ext__free(obj->btf_ext);
8260 
8261 	for (i = 0; i < obj->nr_maps; i++)
8262 		bpf_map__destroy(&obj->maps[i]);
8263 
8264 	zfree(&obj->btf_custom_path);
8265 	zfree(&obj->kconfig);
8266 	zfree(&obj->externs);
8267 	obj->nr_extern = 0;
8268 
8269 	zfree(&obj->maps);
8270 	obj->nr_maps = 0;
8271 
8272 	if (obj->programs && obj->nr_programs) {
8273 		for (i = 0; i < obj->nr_programs; i++)
8274 			bpf_program__exit(&obj->programs[i]);
8275 	}
8276 	zfree(&obj->programs);
8277 
8278 	free(obj);
8279 }
8280 
8281 const char *bpf_object__name(const struct bpf_object *obj)
8282 {
8283 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8284 }
8285 
8286 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8287 {
8288 	return obj ? obj->kern_version : 0;
8289 }
8290 
8291 struct btf *bpf_object__btf(const struct bpf_object *obj)
8292 {
8293 	return obj ? obj->btf : NULL;
8294 }
8295 
8296 int bpf_object__btf_fd(const struct bpf_object *obj)
8297 {
8298 	return obj->btf ? btf__fd(obj->btf) : -1;
8299 }
8300 
8301 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8302 {
8303 	if (obj->loaded)
8304 		return libbpf_err(-EINVAL);
8305 
8306 	obj->kern_version = kern_version;
8307 
8308 	return 0;
8309 }
8310 
8311 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8312 {
8313 	struct bpf_gen *gen;
8314 
8315 	if (!opts)
8316 		return -EFAULT;
8317 	if (!OPTS_VALID(opts, gen_loader_opts))
8318 		return -EINVAL;
8319 	gen = calloc(sizeof(*gen), 1);
8320 	if (!gen)
8321 		return -ENOMEM;
8322 	gen->opts = opts;
8323 	obj->gen_loader = gen;
8324 	return 0;
8325 }
8326 
8327 static struct bpf_program *
8328 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8329 		    bool forward)
8330 {
8331 	size_t nr_programs = obj->nr_programs;
8332 	ssize_t idx;
8333 
8334 	if (!nr_programs)
8335 		return NULL;
8336 
8337 	if (!p)
8338 		/* Iter from the beginning */
8339 		return forward ? &obj->programs[0] :
8340 			&obj->programs[nr_programs - 1];
8341 
8342 	if (p->obj != obj) {
8343 		pr_warn("error: program handler doesn't match object\n");
8344 		return errno = EINVAL, NULL;
8345 	}
8346 
8347 	idx = (p - obj->programs) + (forward ? 1 : -1);
8348 	if (idx >= obj->nr_programs || idx < 0)
8349 		return NULL;
8350 	return &obj->programs[idx];
8351 }
8352 
8353 struct bpf_program *
8354 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8355 {
8356 	struct bpf_program *prog = prev;
8357 
8358 	do {
8359 		prog = __bpf_program__iter(prog, obj, true);
8360 	} while (prog && prog_is_subprog(obj, prog));
8361 
8362 	return prog;
8363 }
8364 
8365 struct bpf_program *
8366 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8367 {
8368 	struct bpf_program *prog = next;
8369 
8370 	do {
8371 		prog = __bpf_program__iter(prog, obj, false);
8372 	} while (prog && prog_is_subprog(obj, prog));
8373 
8374 	return prog;
8375 }
8376 
8377 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8378 {
8379 	prog->prog_ifindex = ifindex;
8380 }
8381 
8382 const char *bpf_program__name(const struct bpf_program *prog)
8383 {
8384 	return prog->name;
8385 }
8386 
8387 const char *bpf_program__section_name(const struct bpf_program *prog)
8388 {
8389 	return prog->sec_name;
8390 }
8391 
8392 bool bpf_program__autoload(const struct bpf_program *prog)
8393 {
8394 	return prog->autoload;
8395 }
8396 
8397 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8398 {
8399 	if (prog->obj->loaded)
8400 		return libbpf_err(-EINVAL);
8401 
8402 	prog->autoload = autoload;
8403 	return 0;
8404 }
8405 
8406 bool bpf_program__autoattach(const struct bpf_program *prog)
8407 {
8408 	return prog->autoattach;
8409 }
8410 
8411 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8412 {
8413 	prog->autoattach = autoattach;
8414 }
8415 
8416 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8417 {
8418 	return prog->insns;
8419 }
8420 
8421 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8422 {
8423 	return prog->insns_cnt;
8424 }
8425 
8426 int bpf_program__set_insns(struct bpf_program *prog,
8427 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8428 {
8429 	struct bpf_insn *insns;
8430 
8431 	if (prog->obj->loaded)
8432 		return -EBUSY;
8433 
8434 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8435 	if (!insns) {
8436 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8437 		return -ENOMEM;
8438 	}
8439 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8440 
8441 	prog->insns = insns;
8442 	prog->insns_cnt = new_insn_cnt;
8443 	return 0;
8444 }
8445 
8446 int bpf_program__fd(const struct bpf_program *prog)
8447 {
8448 	if (!prog)
8449 		return libbpf_err(-EINVAL);
8450 
8451 	if (prog->fd < 0)
8452 		return libbpf_err(-ENOENT);
8453 
8454 	return prog->fd;
8455 }
8456 
8457 __alias(bpf_program__type)
8458 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8459 
8460 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8461 {
8462 	return prog->type;
8463 }
8464 
8465 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8466 {
8467 	if (prog->obj->loaded)
8468 		return libbpf_err(-EBUSY);
8469 
8470 	prog->type = type;
8471 	prog->sec_def = NULL;
8472 	return 0;
8473 }
8474 
8475 __alias(bpf_program__expected_attach_type)
8476 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8477 
8478 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8479 {
8480 	return prog->expected_attach_type;
8481 }
8482 
8483 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8484 					   enum bpf_attach_type type)
8485 {
8486 	if (prog->obj->loaded)
8487 		return libbpf_err(-EBUSY);
8488 
8489 	prog->expected_attach_type = type;
8490 	return 0;
8491 }
8492 
8493 __u32 bpf_program__flags(const struct bpf_program *prog)
8494 {
8495 	return prog->prog_flags;
8496 }
8497 
8498 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8499 {
8500 	if (prog->obj->loaded)
8501 		return libbpf_err(-EBUSY);
8502 
8503 	prog->prog_flags = flags;
8504 	return 0;
8505 }
8506 
8507 __u32 bpf_program__log_level(const struct bpf_program *prog)
8508 {
8509 	return prog->log_level;
8510 }
8511 
8512 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8513 {
8514 	if (prog->obj->loaded)
8515 		return libbpf_err(-EBUSY);
8516 
8517 	prog->log_level = log_level;
8518 	return 0;
8519 }
8520 
8521 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8522 {
8523 	*log_size = prog->log_size;
8524 	return prog->log_buf;
8525 }
8526 
8527 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8528 {
8529 	if (log_size && !log_buf)
8530 		return -EINVAL;
8531 	if (prog->log_size > UINT_MAX)
8532 		return -EINVAL;
8533 	if (prog->obj->loaded)
8534 		return -EBUSY;
8535 
8536 	prog->log_buf = log_buf;
8537 	prog->log_size = log_size;
8538 	return 0;
8539 }
8540 
8541 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8542 	.sec = (char *)sec_pfx,						    \
8543 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8544 	.expected_attach_type = atype,					    \
8545 	.cookie = (long)(flags),					    \
8546 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8547 	__VA_ARGS__							    \
8548 }
8549 
8550 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8551 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8552 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8553 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8554 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8555 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8556 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8557 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8558 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8559 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8560 
8561 static const struct bpf_sec_def section_defs[] = {
8562 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8563 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8564 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8565 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8566 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8567 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8568 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8569 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8570 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8571 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8572 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8573 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8574 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8575 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8576 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8577 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8578 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8579 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8580 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8581 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8582 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8583 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8584 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8585 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8586 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8587 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8588 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8589 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8590 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8591 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8592 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8593 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8594 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8595 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8596 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8597 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8598 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8599 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8600 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8601 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8602 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8603 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8604 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8605 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8606 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8607 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8608 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8609 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8610 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8611 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8612 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8613 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8614 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8615 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8616 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8617 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8618 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8619 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8620 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8621 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8622 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8623 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8624 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8625 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8626 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8627 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8628 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8629 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8630 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8631 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8632 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8633 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8634 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8635 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8636 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8637 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8638 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8639 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8640 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8641 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8642 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8643 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8644 };
8645 
8646 static size_t custom_sec_def_cnt;
8647 static struct bpf_sec_def *custom_sec_defs;
8648 static struct bpf_sec_def custom_fallback_def;
8649 static bool has_custom_fallback_def;
8650 
8651 static int last_custom_sec_def_handler_id;
8652 
8653 int libbpf_register_prog_handler(const char *sec,
8654 				 enum bpf_prog_type prog_type,
8655 				 enum bpf_attach_type exp_attach_type,
8656 				 const struct libbpf_prog_handler_opts *opts)
8657 {
8658 	struct bpf_sec_def *sec_def;
8659 
8660 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8661 		return libbpf_err(-EINVAL);
8662 
8663 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8664 		return libbpf_err(-E2BIG);
8665 
8666 	if (sec) {
8667 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8668 					      sizeof(*sec_def));
8669 		if (!sec_def)
8670 			return libbpf_err(-ENOMEM);
8671 
8672 		custom_sec_defs = sec_def;
8673 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8674 	} else {
8675 		if (has_custom_fallback_def)
8676 			return libbpf_err(-EBUSY);
8677 
8678 		sec_def = &custom_fallback_def;
8679 	}
8680 
8681 	sec_def->sec = sec ? strdup(sec) : NULL;
8682 	if (sec && !sec_def->sec)
8683 		return libbpf_err(-ENOMEM);
8684 
8685 	sec_def->prog_type = prog_type;
8686 	sec_def->expected_attach_type = exp_attach_type;
8687 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8688 
8689 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8690 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8691 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8692 
8693 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8694 
8695 	if (sec)
8696 		custom_sec_def_cnt++;
8697 	else
8698 		has_custom_fallback_def = true;
8699 
8700 	return sec_def->handler_id;
8701 }
8702 
8703 int libbpf_unregister_prog_handler(int handler_id)
8704 {
8705 	struct bpf_sec_def *sec_defs;
8706 	int i;
8707 
8708 	if (handler_id <= 0)
8709 		return libbpf_err(-EINVAL);
8710 
8711 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8712 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8713 		has_custom_fallback_def = false;
8714 		return 0;
8715 	}
8716 
8717 	for (i = 0; i < custom_sec_def_cnt; i++) {
8718 		if (custom_sec_defs[i].handler_id == handler_id)
8719 			break;
8720 	}
8721 
8722 	if (i == custom_sec_def_cnt)
8723 		return libbpf_err(-ENOENT);
8724 
8725 	free(custom_sec_defs[i].sec);
8726 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8727 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8728 	custom_sec_def_cnt--;
8729 
8730 	/* try to shrink the array, but it's ok if we couldn't */
8731 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8732 	if (sec_defs)
8733 		custom_sec_defs = sec_defs;
8734 
8735 	return 0;
8736 }
8737 
8738 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8739 {
8740 	size_t len = strlen(sec_def->sec);
8741 
8742 	/* "type/" always has to have proper SEC("type/extras") form */
8743 	if (sec_def->sec[len - 1] == '/') {
8744 		if (str_has_pfx(sec_name, sec_def->sec))
8745 			return true;
8746 		return false;
8747 	}
8748 
8749 	/* "type+" means it can be either exact SEC("type") or
8750 	 * well-formed SEC("type/extras") with proper '/' separator
8751 	 */
8752 	if (sec_def->sec[len - 1] == '+') {
8753 		len--;
8754 		/* not even a prefix */
8755 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8756 			return false;
8757 		/* exact match or has '/' separator */
8758 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8759 			return true;
8760 		return false;
8761 	}
8762 
8763 	return strcmp(sec_name, sec_def->sec) == 0;
8764 }
8765 
8766 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8767 {
8768 	const struct bpf_sec_def *sec_def;
8769 	int i, n;
8770 
8771 	n = custom_sec_def_cnt;
8772 	for (i = 0; i < n; i++) {
8773 		sec_def = &custom_sec_defs[i];
8774 		if (sec_def_matches(sec_def, sec_name))
8775 			return sec_def;
8776 	}
8777 
8778 	n = ARRAY_SIZE(section_defs);
8779 	for (i = 0; i < n; i++) {
8780 		sec_def = &section_defs[i];
8781 		if (sec_def_matches(sec_def, sec_name))
8782 			return sec_def;
8783 	}
8784 
8785 	if (has_custom_fallback_def)
8786 		return &custom_fallback_def;
8787 
8788 	return NULL;
8789 }
8790 
8791 #define MAX_TYPE_NAME_SIZE 32
8792 
8793 static char *libbpf_get_type_names(bool attach_type)
8794 {
8795 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8796 	char *buf;
8797 
8798 	buf = malloc(len);
8799 	if (!buf)
8800 		return NULL;
8801 
8802 	buf[0] = '\0';
8803 	/* Forge string buf with all available names */
8804 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8805 		const struct bpf_sec_def *sec_def = &section_defs[i];
8806 
8807 		if (attach_type) {
8808 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8809 				continue;
8810 
8811 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8812 				continue;
8813 		}
8814 
8815 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8816 			free(buf);
8817 			return NULL;
8818 		}
8819 		strcat(buf, " ");
8820 		strcat(buf, section_defs[i].sec);
8821 	}
8822 
8823 	return buf;
8824 }
8825 
8826 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8827 			     enum bpf_attach_type *expected_attach_type)
8828 {
8829 	const struct bpf_sec_def *sec_def;
8830 	char *type_names;
8831 
8832 	if (!name)
8833 		return libbpf_err(-EINVAL);
8834 
8835 	sec_def = find_sec_def(name);
8836 	if (sec_def) {
8837 		*prog_type = sec_def->prog_type;
8838 		*expected_attach_type = sec_def->expected_attach_type;
8839 		return 0;
8840 	}
8841 
8842 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8843 	type_names = libbpf_get_type_names(false);
8844 	if (type_names != NULL) {
8845 		pr_debug("supported section(type) names are:%s\n", type_names);
8846 		free(type_names);
8847 	}
8848 
8849 	return libbpf_err(-ESRCH);
8850 }
8851 
8852 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8853 {
8854 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8855 		return NULL;
8856 
8857 	return attach_type_name[t];
8858 }
8859 
8860 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8861 {
8862 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8863 		return NULL;
8864 
8865 	return link_type_name[t];
8866 }
8867 
8868 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8869 {
8870 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8871 		return NULL;
8872 
8873 	return map_type_name[t];
8874 }
8875 
8876 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8877 {
8878 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8879 		return NULL;
8880 
8881 	return prog_type_name[t];
8882 }
8883 
8884 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8885 						     int sec_idx,
8886 						     size_t offset)
8887 {
8888 	struct bpf_map *map;
8889 	size_t i;
8890 
8891 	for (i = 0; i < obj->nr_maps; i++) {
8892 		map = &obj->maps[i];
8893 		if (!bpf_map__is_struct_ops(map))
8894 			continue;
8895 		if (map->sec_idx == sec_idx &&
8896 		    map->sec_offset <= offset &&
8897 		    offset - map->sec_offset < map->def.value_size)
8898 			return map;
8899 	}
8900 
8901 	return NULL;
8902 }
8903 
8904 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8905 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8906 					    Elf64_Shdr *shdr, Elf_Data *data)
8907 {
8908 	const struct btf_member *member;
8909 	struct bpf_struct_ops *st_ops;
8910 	struct bpf_program *prog;
8911 	unsigned int shdr_idx;
8912 	const struct btf *btf;
8913 	struct bpf_map *map;
8914 	unsigned int moff, insn_idx;
8915 	const char *name;
8916 	__u32 member_idx;
8917 	Elf64_Sym *sym;
8918 	Elf64_Rel *rel;
8919 	int i, nrels;
8920 
8921 	btf = obj->btf;
8922 	nrels = shdr->sh_size / shdr->sh_entsize;
8923 	for (i = 0; i < nrels; i++) {
8924 		rel = elf_rel_by_idx(data, i);
8925 		if (!rel) {
8926 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8927 			return -LIBBPF_ERRNO__FORMAT;
8928 		}
8929 
8930 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8931 		if (!sym) {
8932 			pr_warn("struct_ops reloc: symbol %zx not found\n",
8933 				(size_t)ELF64_R_SYM(rel->r_info));
8934 			return -LIBBPF_ERRNO__FORMAT;
8935 		}
8936 
8937 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8938 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
8939 		if (!map) {
8940 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8941 				(size_t)rel->r_offset);
8942 			return -EINVAL;
8943 		}
8944 
8945 		moff = rel->r_offset - map->sec_offset;
8946 		shdr_idx = sym->st_shndx;
8947 		st_ops = map->st_ops;
8948 		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",
8949 			 map->name,
8950 			 (long long)(rel->r_info >> 32),
8951 			 (long long)sym->st_value,
8952 			 shdr_idx, (size_t)rel->r_offset,
8953 			 map->sec_offset, sym->st_name, name);
8954 
8955 		if (shdr_idx >= SHN_LORESERVE) {
8956 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8957 				map->name, (size_t)rel->r_offset, shdr_idx);
8958 			return -LIBBPF_ERRNO__RELOC;
8959 		}
8960 		if (sym->st_value % BPF_INSN_SZ) {
8961 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8962 				map->name, (unsigned long long)sym->st_value);
8963 			return -LIBBPF_ERRNO__FORMAT;
8964 		}
8965 		insn_idx = sym->st_value / BPF_INSN_SZ;
8966 
8967 		member = find_member_by_offset(st_ops->type, moff * 8);
8968 		if (!member) {
8969 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8970 				map->name, moff);
8971 			return -EINVAL;
8972 		}
8973 		member_idx = member - btf_members(st_ops->type);
8974 		name = btf__name_by_offset(btf, member->name_off);
8975 
8976 		if (!resolve_func_ptr(btf, member->type, NULL)) {
8977 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8978 				map->name, name);
8979 			return -EINVAL;
8980 		}
8981 
8982 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8983 		if (!prog) {
8984 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8985 				map->name, shdr_idx, name);
8986 			return -EINVAL;
8987 		}
8988 
8989 		/* prevent the use of BPF prog with invalid type */
8990 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8991 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8992 				map->name, prog->name);
8993 			return -EINVAL;
8994 		}
8995 
8996 		/* if we haven't yet processed this BPF program, record proper
8997 		 * attach_btf_id and member_idx
8998 		 */
8999 		if (!prog->attach_btf_id) {
9000 			prog->attach_btf_id = st_ops->type_id;
9001 			prog->expected_attach_type = member_idx;
9002 		}
9003 
9004 		/* struct_ops BPF prog can be re-used between multiple
9005 		 * .struct_ops & .struct_ops.link as long as it's the
9006 		 * same struct_ops struct definition and the same
9007 		 * function pointer field
9008 		 */
9009 		if (prog->attach_btf_id != st_ops->type_id ||
9010 		    prog->expected_attach_type != member_idx) {
9011 			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",
9012 				map->name, prog->name, prog->sec_name, prog->type,
9013 				prog->attach_btf_id, prog->expected_attach_type, name);
9014 			return -EINVAL;
9015 		}
9016 
9017 		st_ops->progs[member_idx] = prog;
9018 	}
9019 
9020 	return 0;
9021 }
9022 
9023 #define BTF_TRACE_PREFIX "btf_trace_"
9024 #define BTF_LSM_PREFIX "bpf_lsm_"
9025 #define BTF_ITER_PREFIX "bpf_iter_"
9026 #define BTF_MAX_NAME_SIZE 128
9027 
9028 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9029 				const char **prefix, int *kind)
9030 {
9031 	switch (attach_type) {
9032 	case BPF_TRACE_RAW_TP:
9033 		*prefix = BTF_TRACE_PREFIX;
9034 		*kind = BTF_KIND_TYPEDEF;
9035 		break;
9036 	case BPF_LSM_MAC:
9037 	case BPF_LSM_CGROUP:
9038 		*prefix = BTF_LSM_PREFIX;
9039 		*kind = BTF_KIND_FUNC;
9040 		break;
9041 	case BPF_TRACE_ITER:
9042 		*prefix = BTF_ITER_PREFIX;
9043 		*kind = BTF_KIND_FUNC;
9044 		break;
9045 	default:
9046 		*prefix = "";
9047 		*kind = BTF_KIND_FUNC;
9048 	}
9049 }
9050 
9051 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9052 				   const char *name, __u32 kind)
9053 {
9054 	char btf_type_name[BTF_MAX_NAME_SIZE];
9055 	int ret;
9056 
9057 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9058 		       "%s%s", prefix, name);
9059 	/* snprintf returns the number of characters written excluding the
9060 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9061 	 * indicates truncation.
9062 	 */
9063 	if (ret < 0 || ret >= sizeof(btf_type_name))
9064 		return -ENAMETOOLONG;
9065 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9066 }
9067 
9068 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9069 				     enum bpf_attach_type attach_type)
9070 {
9071 	const char *prefix;
9072 	int kind;
9073 
9074 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9075 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9076 }
9077 
9078 int libbpf_find_vmlinux_btf_id(const char *name,
9079 			       enum bpf_attach_type attach_type)
9080 {
9081 	struct btf *btf;
9082 	int err;
9083 
9084 	btf = btf__load_vmlinux_btf();
9085 	err = libbpf_get_error(btf);
9086 	if (err) {
9087 		pr_warn("vmlinux BTF is not found\n");
9088 		return libbpf_err(err);
9089 	}
9090 
9091 	err = find_attach_btf_id(btf, name, attach_type);
9092 	if (err <= 0)
9093 		pr_warn("%s is not found in vmlinux BTF\n", name);
9094 
9095 	btf__free(btf);
9096 	return libbpf_err(err);
9097 }
9098 
9099 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9100 {
9101 	struct bpf_prog_info info;
9102 	__u32 info_len = sizeof(info);
9103 	struct btf *btf;
9104 	int err;
9105 
9106 	memset(&info, 0, info_len);
9107 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9108 	if (err) {
9109 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9110 			attach_prog_fd, err);
9111 		return err;
9112 	}
9113 
9114 	err = -EINVAL;
9115 	if (!info.btf_id) {
9116 		pr_warn("The target program doesn't have BTF\n");
9117 		goto out;
9118 	}
9119 	btf = btf__load_from_kernel_by_id(info.btf_id);
9120 	err = libbpf_get_error(btf);
9121 	if (err) {
9122 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9123 		goto out;
9124 	}
9125 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9126 	btf__free(btf);
9127 	if (err <= 0) {
9128 		pr_warn("%s is not found in prog's BTF\n", name);
9129 		goto out;
9130 	}
9131 out:
9132 	return err;
9133 }
9134 
9135 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9136 			      enum bpf_attach_type attach_type,
9137 			      int *btf_obj_fd, int *btf_type_id)
9138 {
9139 	int ret, i;
9140 
9141 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9142 	if (ret > 0) {
9143 		*btf_obj_fd = 0; /* vmlinux BTF */
9144 		*btf_type_id = ret;
9145 		return 0;
9146 	}
9147 	if (ret != -ENOENT)
9148 		return ret;
9149 
9150 	ret = load_module_btfs(obj);
9151 	if (ret)
9152 		return ret;
9153 
9154 	for (i = 0; i < obj->btf_module_cnt; i++) {
9155 		const struct module_btf *mod = &obj->btf_modules[i];
9156 
9157 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9158 		if (ret > 0) {
9159 			*btf_obj_fd = mod->fd;
9160 			*btf_type_id = ret;
9161 			return 0;
9162 		}
9163 		if (ret == -ENOENT)
9164 			continue;
9165 
9166 		return ret;
9167 	}
9168 
9169 	return -ESRCH;
9170 }
9171 
9172 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9173 				     int *btf_obj_fd, int *btf_type_id)
9174 {
9175 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9176 	__u32 attach_prog_fd = prog->attach_prog_fd;
9177 	int err = 0;
9178 
9179 	/* BPF program's BTF ID */
9180 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9181 		if (!attach_prog_fd) {
9182 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9183 			return -EINVAL;
9184 		}
9185 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9186 		if (err < 0) {
9187 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9188 				 prog->name, attach_prog_fd, attach_name, err);
9189 			return err;
9190 		}
9191 		*btf_obj_fd = 0;
9192 		*btf_type_id = err;
9193 		return 0;
9194 	}
9195 
9196 	/* kernel/module BTF ID */
9197 	if (prog->obj->gen_loader) {
9198 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9199 		*btf_obj_fd = 0;
9200 		*btf_type_id = 1;
9201 	} else {
9202 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9203 	}
9204 	if (err) {
9205 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9206 			prog->name, attach_name, err);
9207 		return err;
9208 	}
9209 	return 0;
9210 }
9211 
9212 int libbpf_attach_type_by_name(const char *name,
9213 			       enum bpf_attach_type *attach_type)
9214 {
9215 	char *type_names;
9216 	const struct bpf_sec_def *sec_def;
9217 
9218 	if (!name)
9219 		return libbpf_err(-EINVAL);
9220 
9221 	sec_def = find_sec_def(name);
9222 	if (!sec_def) {
9223 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9224 		type_names = libbpf_get_type_names(true);
9225 		if (type_names != NULL) {
9226 			pr_debug("attachable section(type) names are:%s\n", type_names);
9227 			free(type_names);
9228 		}
9229 
9230 		return libbpf_err(-EINVAL);
9231 	}
9232 
9233 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9234 		return libbpf_err(-EINVAL);
9235 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9236 		return libbpf_err(-EINVAL);
9237 
9238 	*attach_type = sec_def->expected_attach_type;
9239 	return 0;
9240 }
9241 
9242 int bpf_map__fd(const struct bpf_map *map)
9243 {
9244 	return map ? map->fd : libbpf_err(-EINVAL);
9245 }
9246 
9247 static bool map_uses_real_name(const struct bpf_map *map)
9248 {
9249 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9250 	 * their user-visible name differs from kernel-visible name. Users see
9251 	 * such map's corresponding ELF section name as a map name.
9252 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9253 	 * maps to know which name has to be returned to the user.
9254 	 */
9255 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9256 		return true;
9257 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9258 		return true;
9259 	return false;
9260 }
9261 
9262 const char *bpf_map__name(const struct bpf_map *map)
9263 {
9264 	if (!map)
9265 		return NULL;
9266 
9267 	if (map_uses_real_name(map))
9268 		return map->real_name;
9269 
9270 	return map->name;
9271 }
9272 
9273 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9274 {
9275 	return map->def.type;
9276 }
9277 
9278 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9279 {
9280 	if (map->fd >= 0)
9281 		return libbpf_err(-EBUSY);
9282 	map->def.type = type;
9283 	return 0;
9284 }
9285 
9286 __u32 bpf_map__map_flags(const struct bpf_map *map)
9287 {
9288 	return map->def.map_flags;
9289 }
9290 
9291 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9292 {
9293 	if (map->fd >= 0)
9294 		return libbpf_err(-EBUSY);
9295 	map->def.map_flags = flags;
9296 	return 0;
9297 }
9298 
9299 __u64 bpf_map__map_extra(const struct bpf_map *map)
9300 {
9301 	return map->map_extra;
9302 }
9303 
9304 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9305 {
9306 	if (map->fd >= 0)
9307 		return libbpf_err(-EBUSY);
9308 	map->map_extra = map_extra;
9309 	return 0;
9310 }
9311 
9312 __u32 bpf_map__numa_node(const struct bpf_map *map)
9313 {
9314 	return map->numa_node;
9315 }
9316 
9317 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9318 {
9319 	if (map->fd >= 0)
9320 		return libbpf_err(-EBUSY);
9321 	map->numa_node = numa_node;
9322 	return 0;
9323 }
9324 
9325 __u32 bpf_map__key_size(const struct bpf_map *map)
9326 {
9327 	return map->def.key_size;
9328 }
9329 
9330 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9331 {
9332 	if (map->fd >= 0)
9333 		return libbpf_err(-EBUSY);
9334 	map->def.key_size = size;
9335 	return 0;
9336 }
9337 
9338 __u32 bpf_map__value_size(const struct bpf_map *map)
9339 {
9340 	return map->def.value_size;
9341 }
9342 
9343 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9344 {
9345 	if (map->fd >= 0)
9346 		return libbpf_err(-EBUSY);
9347 	map->def.value_size = size;
9348 	return 0;
9349 }
9350 
9351 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9352 {
9353 	return map ? map->btf_key_type_id : 0;
9354 }
9355 
9356 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9357 {
9358 	return map ? map->btf_value_type_id : 0;
9359 }
9360 
9361 int bpf_map__set_initial_value(struct bpf_map *map,
9362 			       const void *data, size_t size)
9363 {
9364 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9365 	    size != map->def.value_size || map->fd >= 0)
9366 		return libbpf_err(-EINVAL);
9367 
9368 	memcpy(map->mmaped, data, size);
9369 	return 0;
9370 }
9371 
9372 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9373 {
9374 	if (!map->mmaped)
9375 		return NULL;
9376 	*psize = map->def.value_size;
9377 	return map->mmaped;
9378 }
9379 
9380 bool bpf_map__is_internal(const struct bpf_map *map)
9381 {
9382 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9383 }
9384 
9385 __u32 bpf_map__ifindex(const struct bpf_map *map)
9386 {
9387 	return map->map_ifindex;
9388 }
9389 
9390 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9391 {
9392 	if (map->fd >= 0)
9393 		return libbpf_err(-EBUSY);
9394 	map->map_ifindex = ifindex;
9395 	return 0;
9396 }
9397 
9398 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9399 {
9400 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9401 		pr_warn("error: unsupported map type\n");
9402 		return libbpf_err(-EINVAL);
9403 	}
9404 	if (map->inner_map_fd != -1) {
9405 		pr_warn("error: inner_map_fd already specified\n");
9406 		return libbpf_err(-EINVAL);
9407 	}
9408 	if (map->inner_map) {
9409 		bpf_map__destroy(map->inner_map);
9410 		zfree(&map->inner_map);
9411 	}
9412 	map->inner_map_fd = fd;
9413 	return 0;
9414 }
9415 
9416 static struct bpf_map *
9417 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9418 {
9419 	ssize_t idx;
9420 	struct bpf_map *s, *e;
9421 
9422 	if (!obj || !obj->maps)
9423 		return errno = EINVAL, NULL;
9424 
9425 	s = obj->maps;
9426 	e = obj->maps + obj->nr_maps;
9427 
9428 	if ((m < s) || (m >= e)) {
9429 		pr_warn("error in %s: map handler doesn't belong to object\n",
9430 			 __func__);
9431 		return errno = EINVAL, NULL;
9432 	}
9433 
9434 	idx = (m - obj->maps) + i;
9435 	if (idx >= obj->nr_maps || idx < 0)
9436 		return NULL;
9437 	return &obj->maps[idx];
9438 }
9439 
9440 struct bpf_map *
9441 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9442 {
9443 	if (prev == NULL)
9444 		return obj->maps;
9445 
9446 	return __bpf_map__iter(prev, obj, 1);
9447 }
9448 
9449 struct bpf_map *
9450 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9451 {
9452 	if (next == NULL) {
9453 		if (!obj->nr_maps)
9454 			return NULL;
9455 		return obj->maps + obj->nr_maps - 1;
9456 	}
9457 
9458 	return __bpf_map__iter(next, obj, -1);
9459 }
9460 
9461 struct bpf_map *
9462 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9463 {
9464 	struct bpf_map *pos;
9465 
9466 	bpf_object__for_each_map(pos, obj) {
9467 		/* if it's a special internal map name (which always starts
9468 		 * with dot) then check if that special name matches the
9469 		 * real map name (ELF section name)
9470 		 */
9471 		if (name[0] == '.') {
9472 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9473 				return pos;
9474 			continue;
9475 		}
9476 		/* otherwise map name has to be an exact match */
9477 		if (map_uses_real_name(pos)) {
9478 			if (strcmp(pos->real_name, name) == 0)
9479 				return pos;
9480 			continue;
9481 		}
9482 		if (strcmp(pos->name, name) == 0)
9483 			return pos;
9484 	}
9485 	return errno = ENOENT, NULL;
9486 }
9487 
9488 int
9489 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9490 {
9491 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9492 }
9493 
9494 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9495 			   size_t value_sz, bool check_value_sz)
9496 {
9497 	if (map->fd <= 0)
9498 		return -ENOENT;
9499 
9500 	if (map->def.key_size != key_sz) {
9501 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9502 			map->name, key_sz, map->def.key_size);
9503 		return -EINVAL;
9504 	}
9505 
9506 	if (!check_value_sz)
9507 		return 0;
9508 
9509 	switch (map->def.type) {
9510 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9511 	case BPF_MAP_TYPE_PERCPU_HASH:
9512 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9513 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9514 		int num_cpu = libbpf_num_possible_cpus();
9515 		size_t elem_sz = roundup(map->def.value_size, 8);
9516 
9517 		if (value_sz != num_cpu * elem_sz) {
9518 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9519 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9520 			return -EINVAL;
9521 		}
9522 		break;
9523 	}
9524 	default:
9525 		if (map->def.value_size != value_sz) {
9526 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9527 				map->name, value_sz, map->def.value_size);
9528 			return -EINVAL;
9529 		}
9530 		break;
9531 	}
9532 	return 0;
9533 }
9534 
9535 int bpf_map__lookup_elem(const struct bpf_map *map,
9536 			 const void *key, size_t key_sz,
9537 			 void *value, size_t value_sz, __u64 flags)
9538 {
9539 	int err;
9540 
9541 	err = validate_map_op(map, key_sz, value_sz, true);
9542 	if (err)
9543 		return libbpf_err(err);
9544 
9545 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9546 }
9547 
9548 int bpf_map__update_elem(const struct bpf_map *map,
9549 			 const void *key, size_t key_sz,
9550 			 const void *value, size_t value_sz, __u64 flags)
9551 {
9552 	int err;
9553 
9554 	err = validate_map_op(map, key_sz, value_sz, true);
9555 	if (err)
9556 		return libbpf_err(err);
9557 
9558 	return bpf_map_update_elem(map->fd, key, value, flags);
9559 }
9560 
9561 int bpf_map__delete_elem(const struct bpf_map *map,
9562 			 const void *key, size_t key_sz, __u64 flags)
9563 {
9564 	int err;
9565 
9566 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9567 	if (err)
9568 		return libbpf_err(err);
9569 
9570 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9571 }
9572 
9573 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9574 				    const void *key, size_t key_sz,
9575 				    void *value, size_t value_sz, __u64 flags)
9576 {
9577 	int err;
9578 
9579 	err = validate_map_op(map, key_sz, value_sz, true);
9580 	if (err)
9581 		return libbpf_err(err);
9582 
9583 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9584 }
9585 
9586 int bpf_map__get_next_key(const struct bpf_map *map,
9587 			  const void *cur_key, void *next_key, size_t key_sz)
9588 {
9589 	int err;
9590 
9591 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9592 	if (err)
9593 		return libbpf_err(err);
9594 
9595 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9596 }
9597 
9598 long libbpf_get_error(const void *ptr)
9599 {
9600 	if (!IS_ERR_OR_NULL(ptr))
9601 		return 0;
9602 
9603 	if (IS_ERR(ptr))
9604 		errno = -PTR_ERR(ptr);
9605 
9606 	/* If ptr == NULL, then errno should be already set by the failing
9607 	 * API, because libbpf never returns NULL on success and it now always
9608 	 * sets errno on error. So no extra errno handling for ptr == NULL
9609 	 * case.
9610 	 */
9611 	return -errno;
9612 }
9613 
9614 /* Replace link's underlying BPF program with the new one */
9615 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9616 {
9617 	int ret;
9618 
9619 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9620 	return libbpf_err_errno(ret);
9621 }
9622 
9623 /* Release "ownership" of underlying BPF resource (typically, BPF program
9624  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9625  * link, when destructed through bpf_link__destroy() call won't attempt to
9626  * detach/unregisted that BPF resource. This is useful in situations where,
9627  * say, attached BPF program has to outlive userspace program that attached it
9628  * in the system. Depending on type of BPF program, though, there might be
9629  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9630  * exit of userspace program doesn't trigger automatic detachment and clean up
9631  * inside the kernel.
9632  */
9633 void bpf_link__disconnect(struct bpf_link *link)
9634 {
9635 	link->disconnected = true;
9636 }
9637 
9638 int bpf_link__destroy(struct bpf_link *link)
9639 {
9640 	int err = 0;
9641 
9642 	if (IS_ERR_OR_NULL(link))
9643 		return 0;
9644 
9645 	if (!link->disconnected && link->detach)
9646 		err = link->detach(link);
9647 	if (link->pin_path)
9648 		free(link->pin_path);
9649 	if (link->dealloc)
9650 		link->dealloc(link);
9651 	else
9652 		free(link);
9653 
9654 	return libbpf_err(err);
9655 }
9656 
9657 int bpf_link__fd(const struct bpf_link *link)
9658 {
9659 	return link->fd;
9660 }
9661 
9662 const char *bpf_link__pin_path(const struct bpf_link *link)
9663 {
9664 	return link->pin_path;
9665 }
9666 
9667 static int bpf_link__detach_fd(struct bpf_link *link)
9668 {
9669 	return libbpf_err_errno(close(link->fd));
9670 }
9671 
9672 struct bpf_link *bpf_link__open(const char *path)
9673 {
9674 	struct bpf_link *link;
9675 	int fd;
9676 
9677 	fd = bpf_obj_get(path);
9678 	if (fd < 0) {
9679 		fd = -errno;
9680 		pr_warn("failed to open link at %s: %d\n", path, fd);
9681 		return libbpf_err_ptr(fd);
9682 	}
9683 
9684 	link = calloc(1, sizeof(*link));
9685 	if (!link) {
9686 		close(fd);
9687 		return libbpf_err_ptr(-ENOMEM);
9688 	}
9689 	link->detach = &bpf_link__detach_fd;
9690 	link->fd = fd;
9691 
9692 	link->pin_path = strdup(path);
9693 	if (!link->pin_path) {
9694 		bpf_link__destroy(link);
9695 		return libbpf_err_ptr(-ENOMEM);
9696 	}
9697 
9698 	return link;
9699 }
9700 
9701 int bpf_link__detach(struct bpf_link *link)
9702 {
9703 	return bpf_link_detach(link->fd) ? -errno : 0;
9704 }
9705 
9706 int bpf_link__pin(struct bpf_link *link, const char *path)
9707 {
9708 	int err;
9709 
9710 	if (link->pin_path)
9711 		return libbpf_err(-EBUSY);
9712 	err = make_parent_dir(path);
9713 	if (err)
9714 		return libbpf_err(err);
9715 	err = check_path(path);
9716 	if (err)
9717 		return libbpf_err(err);
9718 
9719 	link->pin_path = strdup(path);
9720 	if (!link->pin_path)
9721 		return libbpf_err(-ENOMEM);
9722 
9723 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9724 		err = -errno;
9725 		zfree(&link->pin_path);
9726 		return libbpf_err(err);
9727 	}
9728 
9729 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9730 	return 0;
9731 }
9732 
9733 int bpf_link__unpin(struct bpf_link *link)
9734 {
9735 	int err;
9736 
9737 	if (!link->pin_path)
9738 		return libbpf_err(-EINVAL);
9739 
9740 	err = unlink(link->pin_path);
9741 	if (err != 0)
9742 		return -errno;
9743 
9744 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9745 	zfree(&link->pin_path);
9746 	return 0;
9747 }
9748 
9749 struct bpf_link_perf {
9750 	struct bpf_link link;
9751 	int perf_event_fd;
9752 	/* legacy kprobe support: keep track of probe identifier and type */
9753 	char *legacy_probe_name;
9754 	bool legacy_is_kprobe;
9755 	bool legacy_is_retprobe;
9756 };
9757 
9758 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9759 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9760 
9761 static int bpf_link_perf_detach(struct bpf_link *link)
9762 {
9763 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9764 	int err = 0;
9765 
9766 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9767 		err = -errno;
9768 
9769 	if (perf_link->perf_event_fd != link->fd)
9770 		close(perf_link->perf_event_fd);
9771 	close(link->fd);
9772 
9773 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9774 	if (perf_link->legacy_probe_name) {
9775 		if (perf_link->legacy_is_kprobe) {
9776 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9777 							 perf_link->legacy_is_retprobe);
9778 		} else {
9779 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9780 							 perf_link->legacy_is_retprobe);
9781 		}
9782 	}
9783 
9784 	return err;
9785 }
9786 
9787 static void bpf_link_perf_dealloc(struct bpf_link *link)
9788 {
9789 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9790 
9791 	free(perf_link->legacy_probe_name);
9792 	free(perf_link);
9793 }
9794 
9795 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9796 						     const struct bpf_perf_event_opts *opts)
9797 {
9798 	char errmsg[STRERR_BUFSIZE];
9799 	struct bpf_link_perf *link;
9800 	int prog_fd, link_fd = -1, err;
9801 	bool force_ioctl_attach;
9802 
9803 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9804 		return libbpf_err_ptr(-EINVAL);
9805 
9806 	if (pfd < 0) {
9807 		pr_warn("prog '%s': invalid perf event FD %d\n",
9808 			prog->name, pfd);
9809 		return libbpf_err_ptr(-EINVAL);
9810 	}
9811 	prog_fd = bpf_program__fd(prog);
9812 	if (prog_fd < 0) {
9813 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9814 			prog->name);
9815 		return libbpf_err_ptr(-EINVAL);
9816 	}
9817 
9818 	link = calloc(1, sizeof(*link));
9819 	if (!link)
9820 		return libbpf_err_ptr(-ENOMEM);
9821 	link->link.detach = &bpf_link_perf_detach;
9822 	link->link.dealloc = &bpf_link_perf_dealloc;
9823 	link->perf_event_fd = pfd;
9824 
9825 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
9826 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
9827 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9828 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9829 
9830 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9831 		if (link_fd < 0) {
9832 			err = -errno;
9833 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9834 				prog->name, pfd,
9835 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9836 			goto err_out;
9837 		}
9838 		link->link.fd = link_fd;
9839 	} else {
9840 		if (OPTS_GET(opts, bpf_cookie, 0)) {
9841 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
9842 			err = -EOPNOTSUPP;
9843 			goto err_out;
9844 		}
9845 
9846 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9847 			err = -errno;
9848 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9849 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9850 			if (err == -EPROTO)
9851 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9852 					prog->name, pfd);
9853 			goto err_out;
9854 		}
9855 		link->link.fd = pfd;
9856 	}
9857 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9858 		err = -errno;
9859 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9860 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9861 		goto err_out;
9862 	}
9863 
9864 	return &link->link;
9865 err_out:
9866 	if (link_fd >= 0)
9867 		close(link_fd);
9868 	free(link);
9869 	return libbpf_err_ptr(err);
9870 }
9871 
9872 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9873 {
9874 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9875 }
9876 
9877 /*
9878  * this function is expected to parse integer in the range of [0, 2^31-1] from
9879  * given file using scanf format string fmt. If actual parsed value is
9880  * negative, the result might be indistinguishable from error
9881  */
9882 static int parse_uint_from_file(const char *file, const char *fmt)
9883 {
9884 	char buf[STRERR_BUFSIZE];
9885 	int err, ret;
9886 	FILE *f;
9887 
9888 	f = fopen(file, "r");
9889 	if (!f) {
9890 		err = -errno;
9891 		pr_debug("failed to open '%s': %s\n", file,
9892 			 libbpf_strerror_r(err, buf, sizeof(buf)));
9893 		return err;
9894 	}
9895 	err = fscanf(f, fmt, &ret);
9896 	if (err != 1) {
9897 		err = err == EOF ? -EIO : -errno;
9898 		pr_debug("failed to parse '%s': %s\n", file,
9899 			libbpf_strerror_r(err, buf, sizeof(buf)));
9900 		fclose(f);
9901 		return err;
9902 	}
9903 	fclose(f);
9904 	return ret;
9905 }
9906 
9907 static int determine_kprobe_perf_type(void)
9908 {
9909 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
9910 
9911 	return parse_uint_from_file(file, "%d\n");
9912 }
9913 
9914 static int determine_uprobe_perf_type(void)
9915 {
9916 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
9917 
9918 	return parse_uint_from_file(file, "%d\n");
9919 }
9920 
9921 static int determine_kprobe_retprobe_bit(void)
9922 {
9923 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9924 
9925 	return parse_uint_from_file(file, "config:%d\n");
9926 }
9927 
9928 static int determine_uprobe_retprobe_bit(void)
9929 {
9930 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9931 
9932 	return parse_uint_from_file(file, "config:%d\n");
9933 }
9934 
9935 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9936 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9937 
9938 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9939 				 uint64_t offset, int pid, size_t ref_ctr_off)
9940 {
9941 	const size_t attr_sz = sizeof(struct perf_event_attr);
9942 	struct perf_event_attr attr;
9943 	char errmsg[STRERR_BUFSIZE];
9944 	int type, pfd;
9945 
9946 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9947 		return -EINVAL;
9948 
9949 	memset(&attr, 0, attr_sz);
9950 
9951 	type = uprobe ? determine_uprobe_perf_type()
9952 		      : determine_kprobe_perf_type();
9953 	if (type < 0) {
9954 		pr_warn("failed to determine %s perf type: %s\n",
9955 			uprobe ? "uprobe" : "kprobe",
9956 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9957 		return type;
9958 	}
9959 	if (retprobe) {
9960 		int bit = uprobe ? determine_uprobe_retprobe_bit()
9961 				 : determine_kprobe_retprobe_bit();
9962 
9963 		if (bit < 0) {
9964 			pr_warn("failed to determine %s retprobe bit: %s\n",
9965 				uprobe ? "uprobe" : "kprobe",
9966 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9967 			return bit;
9968 		}
9969 		attr.config |= 1 << bit;
9970 	}
9971 	attr.size = attr_sz;
9972 	attr.type = type;
9973 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9974 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9975 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
9976 
9977 	/* pid filter is meaningful only for uprobes */
9978 	pfd = syscall(__NR_perf_event_open, &attr,
9979 		      pid < 0 ? -1 : pid /* pid */,
9980 		      pid == -1 ? 0 : -1 /* cpu */,
9981 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9982 	return pfd >= 0 ? pfd : -errno;
9983 }
9984 
9985 static int append_to_file(const char *file, const char *fmt, ...)
9986 {
9987 	int fd, n, err = 0;
9988 	va_list ap;
9989 	char buf[1024];
9990 
9991 	va_start(ap, fmt);
9992 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
9993 	va_end(ap);
9994 
9995 	if (n < 0 || n >= sizeof(buf))
9996 		return -EINVAL;
9997 
9998 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9999 	if (fd < 0)
10000 		return -errno;
10001 
10002 	if (write(fd, buf, n) < 0)
10003 		err = -errno;
10004 
10005 	close(fd);
10006 	return err;
10007 }
10008 
10009 #define DEBUGFS "/sys/kernel/debug/tracing"
10010 #define TRACEFS "/sys/kernel/tracing"
10011 
10012 static bool use_debugfs(void)
10013 {
10014 	static int has_debugfs = -1;
10015 
10016 	if (has_debugfs < 0)
10017 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10018 
10019 	return has_debugfs == 1;
10020 }
10021 
10022 static const char *tracefs_path(void)
10023 {
10024 	return use_debugfs() ? DEBUGFS : TRACEFS;
10025 }
10026 
10027 static const char *tracefs_kprobe_events(void)
10028 {
10029 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10030 }
10031 
10032 static const char *tracefs_uprobe_events(void)
10033 {
10034 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10035 }
10036 
10037 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10038 					 const char *kfunc_name, size_t offset)
10039 {
10040 	static int index = 0;
10041 	int i;
10042 
10043 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10044 		 __sync_fetch_and_add(&index, 1));
10045 
10046 	/* sanitize binary_path in the probe name */
10047 	for (i = 0; buf[i]; i++) {
10048 		if (!isalnum(buf[i]))
10049 			buf[i] = '_';
10050 	}
10051 }
10052 
10053 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10054 				   const char *kfunc_name, size_t offset)
10055 {
10056 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10057 			      retprobe ? 'r' : 'p',
10058 			      retprobe ? "kretprobes" : "kprobes",
10059 			      probe_name, kfunc_name, offset);
10060 }
10061 
10062 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10063 {
10064 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10065 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10066 }
10067 
10068 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10069 {
10070 	char file[256];
10071 
10072 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10073 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10074 
10075 	return parse_uint_from_file(file, "%d\n");
10076 }
10077 
10078 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10079 					 const char *kfunc_name, size_t offset, int pid)
10080 {
10081 	const size_t attr_sz = sizeof(struct perf_event_attr);
10082 	struct perf_event_attr attr;
10083 	char errmsg[STRERR_BUFSIZE];
10084 	int type, pfd, err;
10085 
10086 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10087 	if (err < 0) {
10088 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10089 			kfunc_name, offset,
10090 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10091 		return err;
10092 	}
10093 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10094 	if (type < 0) {
10095 		err = type;
10096 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10097 			kfunc_name, offset,
10098 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10099 		goto err_clean_legacy;
10100 	}
10101 
10102 	memset(&attr, 0, attr_sz);
10103 	attr.size = attr_sz;
10104 	attr.config = type;
10105 	attr.type = PERF_TYPE_TRACEPOINT;
10106 
10107 	pfd = syscall(__NR_perf_event_open, &attr,
10108 		      pid < 0 ? -1 : pid, /* pid */
10109 		      pid == -1 ? 0 : -1, /* cpu */
10110 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10111 	if (pfd < 0) {
10112 		err = -errno;
10113 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10114 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10115 		goto err_clean_legacy;
10116 	}
10117 	return pfd;
10118 
10119 err_clean_legacy:
10120 	/* Clear the newly added legacy kprobe_event */
10121 	remove_kprobe_event_legacy(probe_name, retprobe);
10122 	return err;
10123 }
10124 
10125 static const char *arch_specific_syscall_pfx(void)
10126 {
10127 #if defined(__x86_64__)
10128 	return "x64";
10129 #elif defined(__i386__)
10130 	return "ia32";
10131 #elif defined(__s390x__)
10132 	return "s390x";
10133 #elif defined(__s390__)
10134 	return "s390";
10135 #elif defined(__arm__)
10136 	return "arm";
10137 #elif defined(__aarch64__)
10138 	return "arm64";
10139 #elif defined(__mips__)
10140 	return "mips";
10141 #elif defined(__riscv)
10142 	return "riscv";
10143 #elif defined(__powerpc__)
10144 	return "powerpc";
10145 #elif defined(__powerpc64__)
10146 	return "powerpc64";
10147 #else
10148 	return NULL;
10149 #endif
10150 }
10151 
10152 static int probe_kern_syscall_wrapper(void)
10153 {
10154 	char syscall_name[64];
10155 	const char *ksys_pfx;
10156 
10157 	ksys_pfx = arch_specific_syscall_pfx();
10158 	if (!ksys_pfx)
10159 		return 0;
10160 
10161 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10162 
10163 	if (determine_kprobe_perf_type() >= 0) {
10164 		int pfd;
10165 
10166 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10167 		if (pfd >= 0)
10168 			close(pfd);
10169 
10170 		return pfd >= 0 ? 1 : 0;
10171 	} else { /* legacy mode */
10172 		char probe_name[128];
10173 
10174 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10175 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10176 			return 0;
10177 
10178 		(void)remove_kprobe_event_legacy(probe_name, false);
10179 		return 1;
10180 	}
10181 }
10182 
10183 struct bpf_link *
10184 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10185 				const char *func_name,
10186 				const struct bpf_kprobe_opts *opts)
10187 {
10188 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10189 	enum probe_attach_mode attach_mode;
10190 	char errmsg[STRERR_BUFSIZE];
10191 	char *legacy_probe = NULL;
10192 	struct bpf_link *link;
10193 	size_t offset;
10194 	bool retprobe, legacy;
10195 	int pfd, err;
10196 
10197 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10198 		return libbpf_err_ptr(-EINVAL);
10199 
10200 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10201 	retprobe = OPTS_GET(opts, retprobe, false);
10202 	offset = OPTS_GET(opts, offset, 0);
10203 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10204 
10205 	legacy = determine_kprobe_perf_type() < 0;
10206 	switch (attach_mode) {
10207 	case PROBE_ATTACH_MODE_LEGACY:
10208 		legacy = true;
10209 		pe_opts.force_ioctl_attach = true;
10210 		break;
10211 	case PROBE_ATTACH_MODE_PERF:
10212 		if (legacy)
10213 			return libbpf_err_ptr(-ENOTSUP);
10214 		pe_opts.force_ioctl_attach = true;
10215 		break;
10216 	case PROBE_ATTACH_MODE_LINK:
10217 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10218 			return libbpf_err_ptr(-ENOTSUP);
10219 		break;
10220 	case PROBE_ATTACH_MODE_DEFAULT:
10221 		break;
10222 	default:
10223 		return libbpf_err_ptr(-EINVAL);
10224 	}
10225 
10226 	if (!legacy) {
10227 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10228 					    func_name, offset,
10229 					    -1 /* pid */, 0 /* ref_ctr_off */);
10230 	} else {
10231 		char probe_name[256];
10232 
10233 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10234 					     func_name, offset);
10235 
10236 		legacy_probe = strdup(probe_name);
10237 		if (!legacy_probe)
10238 			return libbpf_err_ptr(-ENOMEM);
10239 
10240 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10241 						    offset, -1 /* pid */);
10242 	}
10243 	if (pfd < 0) {
10244 		err = -errno;
10245 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10246 			prog->name, retprobe ? "kretprobe" : "kprobe",
10247 			func_name, offset,
10248 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10249 		goto err_out;
10250 	}
10251 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10252 	err = libbpf_get_error(link);
10253 	if (err) {
10254 		close(pfd);
10255 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10256 			prog->name, retprobe ? "kretprobe" : "kprobe",
10257 			func_name, offset,
10258 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10259 		goto err_clean_legacy;
10260 	}
10261 	if (legacy) {
10262 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10263 
10264 		perf_link->legacy_probe_name = legacy_probe;
10265 		perf_link->legacy_is_kprobe = true;
10266 		perf_link->legacy_is_retprobe = retprobe;
10267 	}
10268 
10269 	return link;
10270 
10271 err_clean_legacy:
10272 	if (legacy)
10273 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10274 err_out:
10275 	free(legacy_probe);
10276 	return libbpf_err_ptr(err);
10277 }
10278 
10279 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10280 					    bool retprobe,
10281 					    const char *func_name)
10282 {
10283 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10284 		.retprobe = retprobe,
10285 	);
10286 
10287 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10288 }
10289 
10290 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10291 					      const char *syscall_name,
10292 					      const struct bpf_ksyscall_opts *opts)
10293 {
10294 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10295 	char func_name[128];
10296 
10297 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10298 		return libbpf_err_ptr(-EINVAL);
10299 
10300 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10301 		/* arch_specific_syscall_pfx() should never return NULL here
10302 		 * because it is guarded by kernel_supports(). However, since
10303 		 * compiler does not know that we have an explicit conditional
10304 		 * as well.
10305 		 */
10306 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10307 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10308 	} else {
10309 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10310 	}
10311 
10312 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10313 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10314 
10315 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10316 }
10317 
10318 /* Adapted from perf/util/string.c */
10319 static bool glob_match(const char *str, const char *pat)
10320 {
10321 	while (*str && *pat && *pat != '*') {
10322 		if (*pat == '?') {      /* Matches any single character */
10323 			str++;
10324 			pat++;
10325 			continue;
10326 		}
10327 		if (*str != *pat)
10328 			return false;
10329 		str++;
10330 		pat++;
10331 	}
10332 	/* Check wild card */
10333 	if (*pat == '*') {
10334 		while (*pat == '*')
10335 			pat++;
10336 		if (!*pat) /* Tail wild card matches all */
10337 			return true;
10338 		while (*str)
10339 			if (glob_match(str++, pat))
10340 				return true;
10341 	}
10342 	return !*str && !*pat;
10343 }
10344 
10345 struct kprobe_multi_resolve {
10346 	const char *pattern;
10347 	unsigned long *addrs;
10348 	size_t cap;
10349 	size_t cnt;
10350 };
10351 
10352 static int
10353 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10354 			const char *sym_name, void *ctx)
10355 {
10356 	struct kprobe_multi_resolve *res = ctx;
10357 	int err;
10358 
10359 	if (!glob_match(sym_name, res->pattern))
10360 		return 0;
10361 
10362 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10363 				res->cnt + 1);
10364 	if (err)
10365 		return err;
10366 
10367 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10368 	return 0;
10369 }
10370 
10371 struct bpf_link *
10372 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10373 				      const char *pattern,
10374 				      const struct bpf_kprobe_multi_opts *opts)
10375 {
10376 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10377 	struct kprobe_multi_resolve res = {
10378 		.pattern = pattern,
10379 	};
10380 	struct bpf_link *link = NULL;
10381 	char errmsg[STRERR_BUFSIZE];
10382 	const unsigned long *addrs;
10383 	int err, link_fd, prog_fd;
10384 	const __u64 *cookies;
10385 	const char **syms;
10386 	bool retprobe;
10387 	size_t cnt;
10388 
10389 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10390 		return libbpf_err_ptr(-EINVAL);
10391 
10392 	syms    = OPTS_GET(opts, syms, false);
10393 	addrs   = OPTS_GET(opts, addrs, false);
10394 	cnt     = OPTS_GET(opts, cnt, false);
10395 	cookies = OPTS_GET(opts, cookies, false);
10396 
10397 	if (!pattern && !addrs && !syms)
10398 		return libbpf_err_ptr(-EINVAL);
10399 	if (pattern && (addrs || syms || cookies || cnt))
10400 		return libbpf_err_ptr(-EINVAL);
10401 	if (!pattern && !cnt)
10402 		return libbpf_err_ptr(-EINVAL);
10403 	if (addrs && syms)
10404 		return libbpf_err_ptr(-EINVAL);
10405 
10406 	if (pattern) {
10407 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10408 		if (err)
10409 			goto error;
10410 		if (!res.cnt) {
10411 			err = -ENOENT;
10412 			goto error;
10413 		}
10414 		addrs = res.addrs;
10415 		cnt = res.cnt;
10416 	}
10417 
10418 	retprobe = OPTS_GET(opts, retprobe, false);
10419 
10420 	lopts.kprobe_multi.syms = syms;
10421 	lopts.kprobe_multi.addrs = addrs;
10422 	lopts.kprobe_multi.cookies = cookies;
10423 	lopts.kprobe_multi.cnt = cnt;
10424 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10425 
10426 	link = calloc(1, sizeof(*link));
10427 	if (!link) {
10428 		err = -ENOMEM;
10429 		goto error;
10430 	}
10431 	link->detach = &bpf_link__detach_fd;
10432 
10433 	prog_fd = bpf_program__fd(prog);
10434 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10435 	if (link_fd < 0) {
10436 		err = -errno;
10437 		pr_warn("prog '%s': failed to attach: %s\n",
10438 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10439 		goto error;
10440 	}
10441 	link->fd = link_fd;
10442 	free(res.addrs);
10443 	return link;
10444 
10445 error:
10446 	free(link);
10447 	free(res.addrs);
10448 	return libbpf_err_ptr(err);
10449 }
10450 
10451 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10452 {
10453 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10454 	unsigned long offset = 0;
10455 	const char *func_name;
10456 	char *func;
10457 	int n;
10458 
10459 	*link = NULL;
10460 
10461 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10462 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10463 		return 0;
10464 
10465 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10466 	if (opts.retprobe)
10467 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10468 	else
10469 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10470 
10471 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10472 	if (n < 1) {
10473 		pr_warn("kprobe name is invalid: %s\n", func_name);
10474 		return -EINVAL;
10475 	}
10476 	if (opts.retprobe && offset != 0) {
10477 		free(func);
10478 		pr_warn("kretprobes do not support offset specification\n");
10479 		return -EINVAL;
10480 	}
10481 
10482 	opts.offset = offset;
10483 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10484 	free(func);
10485 	return libbpf_get_error(*link);
10486 }
10487 
10488 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10489 {
10490 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10491 	const char *syscall_name;
10492 
10493 	*link = NULL;
10494 
10495 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10496 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10497 		return 0;
10498 
10499 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10500 	if (opts.retprobe)
10501 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10502 	else
10503 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10504 
10505 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10506 	return *link ? 0 : -errno;
10507 }
10508 
10509 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10510 {
10511 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10512 	const char *spec;
10513 	char *pattern;
10514 	int n;
10515 
10516 	*link = NULL;
10517 
10518 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10519 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10520 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10521 		return 0;
10522 
10523 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10524 	if (opts.retprobe)
10525 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10526 	else
10527 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10528 
10529 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10530 	if (n < 1) {
10531 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10532 		return -EINVAL;
10533 	}
10534 
10535 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10536 	free(pattern);
10537 	return libbpf_get_error(*link);
10538 }
10539 
10540 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10541 					 const char *binary_path, uint64_t offset)
10542 {
10543 	int i;
10544 
10545 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10546 
10547 	/* sanitize binary_path in the probe name */
10548 	for (i = 0; buf[i]; i++) {
10549 		if (!isalnum(buf[i]))
10550 			buf[i] = '_';
10551 	}
10552 }
10553 
10554 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10555 					  const char *binary_path, size_t offset)
10556 {
10557 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10558 			      retprobe ? 'r' : 'p',
10559 			      retprobe ? "uretprobes" : "uprobes",
10560 			      probe_name, binary_path, offset);
10561 }
10562 
10563 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10564 {
10565 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10566 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10567 }
10568 
10569 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10570 {
10571 	char file[512];
10572 
10573 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10574 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10575 
10576 	return parse_uint_from_file(file, "%d\n");
10577 }
10578 
10579 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10580 					 const char *binary_path, size_t offset, int pid)
10581 {
10582 	const size_t attr_sz = sizeof(struct perf_event_attr);
10583 	struct perf_event_attr attr;
10584 	int type, pfd, err;
10585 
10586 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10587 	if (err < 0) {
10588 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10589 			binary_path, (size_t)offset, err);
10590 		return err;
10591 	}
10592 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10593 	if (type < 0) {
10594 		err = type;
10595 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10596 			binary_path, offset, err);
10597 		goto err_clean_legacy;
10598 	}
10599 
10600 	memset(&attr, 0, attr_sz);
10601 	attr.size = attr_sz;
10602 	attr.config = type;
10603 	attr.type = PERF_TYPE_TRACEPOINT;
10604 
10605 	pfd = syscall(__NR_perf_event_open, &attr,
10606 		      pid < 0 ? -1 : pid, /* pid */
10607 		      pid == -1 ? 0 : -1, /* cpu */
10608 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10609 	if (pfd < 0) {
10610 		err = -errno;
10611 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10612 		goto err_clean_legacy;
10613 	}
10614 	return pfd;
10615 
10616 err_clean_legacy:
10617 	/* Clear the newly added legacy uprobe_event */
10618 	remove_uprobe_event_legacy(probe_name, retprobe);
10619 	return err;
10620 }
10621 
10622 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10623 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10624 {
10625 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10626 		GElf_Shdr sh;
10627 
10628 		if (!gelf_getshdr(scn, &sh))
10629 			continue;
10630 		if (sh.sh_type == sh_type)
10631 			return scn;
10632 	}
10633 	return NULL;
10634 }
10635 
10636 /* Find offset of function name in the provided ELF object. "binary_path" is
10637  * the path to the ELF binary represented by "elf", and only used for error
10638  * reporting matters. "name" matches symbol name or name@@LIB for library
10639  * functions.
10640  */
10641 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
10642 {
10643 	int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10644 	bool is_shared_lib, is_name_qualified;
10645 	long ret = -ENOENT;
10646 	size_t name_len;
10647 	GElf_Ehdr ehdr;
10648 
10649 	if (!gelf_getehdr(elf, &ehdr)) {
10650 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10651 		ret = -LIBBPF_ERRNO__FORMAT;
10652 		goto out;
10653 	}
10654 	/* for shared lib case, we do not need to calculate relative offset */
10655 	is_shared_lib = ehdr.e_type == ET_DYN;
10656 
10657 	name_len = strlen(name);
10658 	/* Does name specify "@@LIB"? */
10659 	is_name_qualified = strstr(name, "@@") != NULL;
10660 
10661 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10662 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10663 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10664 	 * reported as a warning/error.
10665 	 */
10666 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10667 		size_t nr_syms, strtabidx, idx;
10668 		Elf_Data *symbols = NULL;
10669 		Elf_Scn *scn = NULL;
10670 		int last_bind = -1;
10671 		const char *sname;
10672 		GElf_Shdr sh;
10673 
10674 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10675 		if (!scn) {
10676 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10677 				 binary_path);
10678 			continue;
10679 		}
10680 		if (!gelf_getshdr(scn, &sh))
10681 			continue;
10682 		strtabidx = sh.sh_link;
10683 		symbols = elf_getdata(scn, 0);
10684 		if (!symbols) {
10685 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10686 				binary_path, elf_errmsg(-1));
10687 			ret = -LIBBPF_ERRNO__FORMAT;
10688 			goto out;
10689 		}
10690 		nr_syms = symbols->d_size / sh.sh_entsize;
10691 
10692 		for (idx = 0; idx < nr_syms; idx++) {
10693 			int curr_bind;
10694 			GElf_Sym sym;
10695 			Elf_Scn *sym_scn;
10696 			GElf_Shdr sym_sh;
10697 
10698 			if (!gelf_getsym(symbols, idx, &sym))
10699 				continue;
10700 
10701 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10702 				continue;
10703 
10704 			sname = elf_strptr(elf, strtabidx, sym.st_name);
10705 			if (!sname)
10706 				continue;
10707 
10708 			curr_bind = GELF_ST_BIND(sym.st_info);
10709 
10710 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
10711 			if (strncmp(sname, name, name_len) != 0)
10712 				continue;
10713 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
10714 			 * additional characters in sname should be of the form "@@LIB".
10715 			 */
10716 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10717 				continue;
10718 
10719 			if (ret >= 0) {
10720 				/* handle multiple matches */
10721 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10722 					/* Only accept one non-weak bind. */
10723 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10724 						sname, name, binary_path);
10725 					ret = -LIBBPF_ERRNO__FORMAT;
10726 					goto out;
10727 				} else if (curr_bind == STB_WEAK) {
10728 					/* already have a non-weak bind, and
10729 					 * this is a weak bind, so ignore.
10730 					 */
10731 					continue;
10732 				}
10733 			}
10734 
10735 			/* Transform symbol's virtual address (absolute for
10736 			 * binaries and relative for shared libs) into file
10737 			 * offset, which is what kernel is expecting for
10738 			 * uprobe/uretprobe attachment.
10739 			 * See Documentation/trace/uprobetracer.rst for more
10740 			 * details.
10741 			 * This is done by looking up symbol's containing
10742 			 * section's header and using it's virtual address
10743 			 * (sh_addr) and corresponding file offset (sh_offset)
10744 			 * to transform sym.st_value (virtual address) into
10745 			 * desired final file offset.
10746 			 */
10747 			sym_scn = elf_getscn(elf, sym.st_shndx);
10748 			if (!sym_scn)
10749 				continue;
10750 			if (!gelf_getshdr(sym_scn, &sym_sh))
10751 				continue;
10752 
10753 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10754 			last_bind = curr_bind;
10755 		}
10756 		if (ret > 0)
10757 			break;
10758 	}
10759 
10760 	if (ret > 0) {
10761 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10762 			 ret);
10763 	} else {
10764 		if (ret == 0) {
10765 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10766 				is_shared_lib ? "should not be 0 in a shared library" :
10767 						"try using shared library path instead");
10768 			ret = -ENOENT;
10769 		} else {
10770 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10771 		}
10772 	}
10773 out:
10774 	return ret;
10775 }
10776 
10777 /* Find offset of function name in ELF object specified by path. "name" matches
10778  * symbol name or name@@LIB for library functions.
10779  */
10780 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
10781 {
10782 	char errmsg[STRERR_BUFSIZE];
10783 	long ret = -ENOENT;
10784 	Elf *elf;
10785 	int fd;
10786 
10787 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10788 	if (fd < 0) {
10789 		ret = -errno;
10790 		pr_warn("failed to open %s: %s\n", binary_path,
10791 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10792 		return ret;
10793 	}
10794 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10795 	if (!elf) {
10796 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10797 		close(fd);
10798 		return -LIBBPF_ERRNO__FORMAT;
10799 	}
10800 
10801 	ret = elf_find_func_offset(elf, binary_path, name);
10802 	elf_end(elf);
10803 	close(fd);
10804 	return ret;
10805 }
10806 
10807 /* Find offset of function name in archive specified by path. Currently
10808  * supported are .zip files that do not compress their contents, as used on
10809  * Android in the form of APKs, for example. "file_name" is the name of the ELF
10810  * file inside the archive. "func_name" matches symbol name or name@@LIB for
10811  * library functions.
10812  *
10813  * An overview of the APK format specifically provided here:
10814  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
10815  */
10816 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
10817 					      const char *func_name)
10818 {
10819 	struct zip_archive *archive;
10820 	struct zip_entry entry;
10821 	long ret;
10822 	Elf *elf;
10823 
10824 	archive = zip_archive_open(archive_path);
10825 	if (IS_ERR(archive)) {
10826 		ret = PTR_ERR(archive);
10827 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
10828 		return ret;
10829 	}
10830 
10831 	ret = zip_archive_find_entry(archive, file_name, &entry);
10832 	if (ret) {
10833 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
10834 			archive_path, ret);
10835 		goto out;
10836 	}
10837 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
10838 		 (unsigned long)entry.data_offset);
10839 
10840 	if (entry.compression) {
10841 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
10842 			archive_path);
10843 		ret = -LIBBPF_ERRNO__FORMAT;
10844 		goto out;
10845 	}
10846 
10847 	elf = elf_memory((void *)entry.data, entry.data_length);
10848 	if (!elf) {
10849 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
10850 			elf_errmsg(-1));
10851 		ret = -LIBBPF_ERRNO__LIBELF;
10852 		goto out;
10853 	}
10854 
10855 	ret = elf_find_func_offset(elf, file_name, func_name);
10856 	if (ret > 0) {
10857 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
10858 			 func_name, file_name, archive_path, entry.data_offset, ret,
10859 			 ret + entry.data_offset);
10860 		ret += entry.data_offset;
10861 	}
10862 	elf_end(elf);
10863 
10864 out:
10865 	zip_archive_close(archive);
10866 	return ret;
10867 }
10868 
10869 static const char *arch_specific_lib_paths(void)
10870 {
10871 	/*
10872 	 * Based on https://packages.debian.org/sid/libc6.
10873 	 *
10874 	 * Assume that the traced program is built for the same architecture
10875 	 * as libbpf, which should cover the vast majority of cases.
10876 	 */
10877 #if defined(__x86_64__)
10878 	return "/lib/x86_64-linux-gnu";
10879 #elif defined(__i386__)
10880 	return "/lib/i386-linux-gnu";
10881 #elif defined(__s390x__)
10882 	return "/lib/s390x-linux-gnu";
10883 #elif defined(__s390__)
10884 	return "/lib/s390-linux-gnu";
10885 #elif defined(__arm__) && defined(__SOFTFP__)
10886 	return "/lib/arm-linux-gnueabi";
10887 #elif defined(__arm__) && !defined(__SOFTFP__)
10888 	return "/lib/arm-linux-gnueabihf";
10889 #elif defined(__aarch64__)
10890 	return "/lib/aarch64-linux-gnu";
10891 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10892 	return "/lib/mips64el-linux-gnuabi64";
10893 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10894 	return "/lib/mipsel-linux-gnu";
10895 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10896 	return "/lib/powerpc64le-linux-gnu";
10897 #elif defined(__sparc__) && defined(__arch64__)
10898 	return "/lib/sparc64-linux-gnu";
10899 #elif defined(__riscv) && __riscv_xlen == 64
10900 	return "/lib/riscv64-linux-gnu";
10901 #else
10902 	return NULL;
10903 #endif
10904 }
10905 
10906 /* Get full path to program/shared library. */
10907 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10908 {
10909 	const char *search_paths[3] = {};
10910 	int i, perm;
10911 
10912 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10913 		search_paths[0] = getenv("LD_LIBRARY_PATH");
10914 		search_paths[1] = "/usr/lib64:/usr/lib";
10915 		search_paths[2] = arch_specific_lib_paths();
10916 		perm = R_OK;
10917 	} else {
10918 		search_paths[0] = getenv("PATH");
10919 		search_paths[1] = "/usr/bin:/usr/sbin";
10920 		perm = R_OK | X_OK;
10921 	}
10922 
10923 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10924 		const char *s;
10925 
10926 		if (!search_paths[i])
10927 			continue;
10928 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10929 			char *next_path;
10930 			int seg_len;
10931 
10932 			if (s[0] == ':')
10933 				s++;
10934 			next_path = strchr(s, ':');
10935 			seg_len = next_path ? next_path - s : strlen(s);
10936 			if (!seg_len)
10937 				continue;
10938 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10939 			/* ensure it has required permissions */
10940 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
10941 				continue;
10942 			pr_debug("resolved '%s' to '%s'\n", file, result);
10943 			return 0;
10944 		}
10945 	}
10946 	return -ENOENT;
10947 }
10948 
10949 LIBBPF_API struct bpf_link *
10950 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10951 				const char *binary_path, size_t func_offset,
10952 				const struct bpf_uprobe_opts *opts)
10953 {
10954 	const char *archive_path = NULL, *archive_sep = NULL;
10955 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10956 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10957 	enum probe_attach_mode attach_mode;
10958 	char full_path[PATH_MAX];
10959 	struct bpf_link *link;
10960 	size_t ref_ctr_off;
10961 	int pfd, err;
10962 	bool retprobe, legacy;
10963 	const char *func_name;
10964 
10965 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10966 		return libbpf_err_ptr(-EINVAL);
10967 
10968 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10969 	retprobe = OPTS_GET(opts, retprobe, false);
10970 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10971 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10972 
10973 	if (!binary_path)
10974 		return libbpf_err_ptr(-EINVAL);
10975 
10976 	/* Check if "binary_path" refers to an archive. */
10977 	archive_sep = strstr(binary_path, "!/");
10978 	if (archive_sep) {
10979 		full_path[0] = '\0';
10980 		libbpf_strlcpy(full_path, binary_path,
10981 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
10982 		archive_path = full_path;
10983 		binary_path = archive_sep + 2;
10984 	} else if (!strchr(binary_path, '/')) {
10985 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
10986 		if (err) {
10987 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10988 				prog->name, binary_path, err);
10989 			return libbpf_err_ptr(err);
10990 		}
10991 		binary_path = full_path;
10992 	}
10993 	func_name = OPTS_GET(opts, func_name, NULL);
10994 	if (func_name) {
10995 		long sym_off;
10996 
10997 		if (archive_path) {
10998 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
10999 								    func_name);
11000 			binary_path = archive_path;
11001 		} else {
11002 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11003 		}
11004 		if (sym_off < 0)
11005 			return libbpf_err_ptr(sym_off);
11006 		func_offset += sym_off;
11007 	}
11008 
11009 	legacy = determine_uprobe_perf_type() < 0;
11010 	switch (attach_mode) {
11011 	case PROBE_ATTACH_MODE_LEGACY:
11012 		legacy = true;
11013 		pe_opts.force_ioctl_attach = true;
11014 		break;
11015 	case PROBE_ATTACH_MODE_PERF:
11016 		if (legacy)
11017 			return libbpf_err_ptr(-ENOTSUP);
11018 		pe_opts.force_ioctl_attach = true;
11019 		break;
11020 	case PROBE_ATTACH_MODE_LINK:
11021 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11022 			return libbpf_err_ptr(-ENOTSUP);
11023 		break;
11024 	case PROBE_ATTACH_MODE_DEFAULT:
11025 		break;
11026 	default:
11027 		return libbpf_err_ptr(-EINVAL);
11028 	}
11029 
11030 	if (!legacy) {
11031 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11032 					    func_offset, pid, ref_ctr_off);
11033 	} else {
11034 		char probe_name[PATH_MAX + 64];
11035 
11036 		if (ref_ctr_off)
11037 			return libbpf_err_ptr(-EINVAL);
11038 
11039 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11040 					     binary_path, func_offset);
11041 
11042 		legacy_probe = strdup(probe_name);
11043 		if (!legacy_probe)
11044 			return libbpf_err_ptr(-ENOMEM);
11045 
11046 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11047 						    binary_path, func_offset, pid);
11048 	}
11049 	if (pfd < 0) {
11050 		err = -errno;
11051 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11052 			prog->name, retprobe ? "uretprobe" : "uprobe",
11053 			binary_path, func_offset,
11054 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11055 		goto err_out;
11056 	}
11057 
11058 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11059 	err = libbpf_get_error(link);
11060 	if (err) {
11061 		close(pfd);
11062 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11063 			prog->name, retprobe ? "uretprobe" : "uprobe",
11064 			binary_path, func_offset,
11065 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11066 		goto err_clean_legacy;
11067 	}
11068 	if (legacy) {
11069 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11070 
11071 		perf_link->legacy_probe_name = legacy_probe;
11072 		perf_link->legacy_is_kprobe = false;
11073 		perf_link->legacy_is_retprobe = retprobe;
11074 	}
11075 	return link;
11076 
11077 err_clean_legacy:
11078 	if (legacy)
11079 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11080 err_out:
11081 	free(legacy_probe);
11082 	return libbpf_err_ptr(err);
11083 }
11084 
11085 /* Format of u[ret]probe section definition supporting auto-attach:
11086  * u[ret]probe/binary:function[+offset]
11087  *
11088  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11089  * full binary path via bpf_program__attach_uprobe_opts.
11090  *
11091  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11092  * specified (and auto-attach is not possible) or the above format is specified for
11093  * auto-attach.
11094  */
11095 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11096 {
11097 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11098 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11099 	int n, ret = -EINVAL;
11100 	long offset = 0;
11101 
11102 	*link = NULL;
11103 
11104 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11105 		   &probe_type, &binary_path, &func_name, &offset);
11106 	switch (n) {
11107 	case 1:
11108 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11109 		ret = 0;
11110 		break;
11111 	case 2:
11112 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11113 			prog->name, prog->sec_name);
11114 		break;
11115 	case 3:
11116 	case 4:
11117 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11118 				strcmp(probe_type, "uretprobe.s") == 0;
11119 		if (opts.retprobe && offset != 0) {
11120 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11121 				prog->name);
11122 			break;
11123 		}
11124 		opts.func_name = func_name;
11125 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11126 		ret = libbpf_get_error(*link);
11127 		break;
11128 	default:
11129 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11130 			prog->sec_name);
11131 		break;
11132 	}
11133 	free(probe_type);
11134 	free(binary_path);
11135 	free(func_name);
11136 
11137 	return ret;
11138 }
11139 
11140 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11141 					    bool retprobe, pid_t pid,
11142 					    const char *binary_path,
11143 					    size_t func_offset)
11144 {
11145 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11146 
11147 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11148 }
11149 
11150 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11151 					  pid_t pid, const char *binary_path,
11152 					  const char *usdt_provider, const char *usdt_name,
11153 					  const struct bpf_usdt_opts *opts)
11154 {
11155 	char resolved_path[512];
11156 	struct bpf_object *obj = prog->obj;
11157 	struct bpf_link *link;
11158 	__u64 usdt_cookie;
11159 	int err;
11160 
11161 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11162 		return libbpf_err_ptr(-EINVAL);
11163 
11164 	if (bpf_program__fd(prog) < 0) {
11165 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11166 			prog->name);
11167 		return libbpf_err_ptr(-EINVAL);
11168 	}
11169 
11170 	if (!binary_path)
11171 		return libbpf_err_ptr(-EINVAL);
11172 
11173 	if (!strchr(binary_path, '/')) {
11174 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11175 		if (err) {
11176 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11177 				prog->name, binary_path, err);
11178 			return libbpf_err_ptr(err);
11179 		}
11180 		binary_path = resolved_path;
11181 	}
11182 
11183 	/* USDT manager is instantiated lazily on first USDT attach. It will
11184 	 * be destroyed together with BPF object in bpf_object__close().
11185 	 */
11186 	if (IS_ERR(obj->usdt_man))
11187 		return libbpf_ptr(obj->usdt_man);
11188 	if (!obj->usdt_man) {
11189 		obj->usdt_man = usdt_manager_new(obj);
11190 		if (IS_ERR(obj->usdt_man))
11191 			return libbpf_ptr(obj->usdt_man);
11192 	}
11193 
11194 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11195 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11196 					usdt_provider, usdt_name, usdt_cookie);
11197 	err = libbpf_get_error(link);
11198 	if (err)
11199 		return libbpf_err_ptr(err);
11200 	return link;
11201 }
11202 
11203 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11204 {
11205 	char *path = NULL, *provider = NULL, *name = NULL;
11206 	const char *sec_name;
11207 	int n, err;
11208 
11209 	sec_name = bpf_program__section_name(prog);
11210 	if (strcmp(sec_name, "usdt") == 0) {
11211 		/* no auto-attach for just SEC("usdt") */
11212 		*link = NULL;
11213 		return 0;
11214 	}
11215 
11216 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11217 	if (n != 3) {
11218 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11219 			sec_name);
11220 		err = -EINVAL;
11221 	} else {
11222 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11223 						 provider, name, NULL);
11224 		err = libbpf_get_error(*link);
11225 	}
11226 	free(path);
11227 	free(provider);
11228 	free(name);
11229 	return err;
11230 }
11231 
11232 static int determine_tracepoint_id(const char *tp_category,
11233 				   const char *tp_name)
11234 {
11235 	char file[PATH_MAX];
11236 	int ret;
11237 
11238 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11239 		       tracefs_path(), tp_category, tp_name);
11240 	if (ret < 0)
11241 		return -errno;
11242 	if (ret >= sizeof(file)) {
11243 		pr_debug("tracepoint %s/%s path is too long\n",
11244 			 tp_category, tp_name);
11245 		return -E2BIG;
11246 	}
11247 	return parse_uint_from_file(file, "%d\n");
11248 }
11249 
11250 static int perf_event_open_tracepoint(const char *tp_category,
11251 				      const char *tp_name)
11252 {
11253 	const size_t attr_sz = sizeof(struct perf_event_attr);
11254 	struct perf_event_attr attr;
11255 	char errmsg[STRERR_BUFSIZE];
11256 	int tp_id, pfd, err;
11257 
11258 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11259 	if (tp_id < 0) {
11260 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11261 			tp_category, tp_name,
11262 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11263 		return tp_id;
11264 	}
11265 
11266 	memset(&attr, 0, attr_sz);
11267 	attr.type = PERF_TYPE_TRACEPOINT;
11268 	attr.size = attr_sz;
11269 	attr.config = tp_id;
11270 
11271 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11272 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11273 	if (pfd < 0) {
11274 		err = -errno;
11275 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11276 			tp_category, tp_name,
11277 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11278 		return err;
11279 	}
11280 	return pfd;
11281 }
11282 
11283 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11284 						     const char *tp_category,
11285 						     const char *tp_name,
11286 						     const struct bpf_tracepoint_opts *opts)
11287 {
11288 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11289 	char errmsg[STRERR_BUFSIZE];
11290 	struct bpf_link *link;
11291 	int pfd, err;
11292 
11293 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11294 		return libbpf_err_ptr(-EINVAL);
11295 
11296 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11297 
11298 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11299 	if (pfd < 0) {
11300 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11301 			prog->name, tp_category, tp_name,
11302 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11303 		return libbpf_err_ptr(pfd);
11304 	}
11305 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11306 	err = libbpf_get_error(link);
11307 	if (err) {
11308 		close(pfd);
11309 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11310 			prog->name, tp_category, tp_name,
11311 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11312 		return libbpf_err_ptr(err);
11313 	}
11314 	return link;
11315 }
11316 
11317 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11318 						const char *tp_category,
11319 						const char *tp_name)
11320 {
11321 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11322 }
11323 
11324 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11325 {
11326 	char *sec_name, *tp_cat, *tp_name;
11327 
11328 	*link = NULL;
11329 
11330 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11331 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11332 		return 0;
11333 
11334 	sec_name = strdup(prog->sec_name);
11335 	if (!sec_name)
11336 		return -ENOMEM;
11337 
11338 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11339 	if (str_has_pfx(prog->sec_name, "tp/"))
11340 		tp_cat = sec_name + sizeof("tp/") - 1;
11341 	else
11342 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11343 	tp_name = strchr(tp_cat, '/');
11344 	if (!tp_name) {
11345 		free(sec_name);
11346 		return -EINVAL;
11347 	}
11348 	*tp_name = '\0';
11349 	tp_name++;
11350 
11351 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11352 	free(sec_name);
11353 	return libbpf_get_error(*link);
11354 }
11355 
11356 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11357 						    const char *tp_name)
11358 {
11359 	char errmsg[STRERR_BUFSIZE];
11360 	struct bpf_link *link;
11361 	int prog_fd, pfd;
11362 
11363 	prog_fd = bpf_program__fd(prog);
11364 	if (prog_fd < 0) {
11365 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11366 		return libbpf_err_ptr(-EINVAL);
11367 	}
11368 
11369 	link = calloc(1, sizeof(*link));
11370 	if (!link)
11371 		return libbpf_err_ptr(-ENOMEM);
11372 	link->detach = &bpf_link__detach_fd;
11373 
11374 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11375 	if (pfd < 0) {
11376 		pfd = -errno;
11377 		free(link);
11378 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11379 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11380 		return libbpf_err_ptr(pfd);
11381 	}
11382 	link->fd = pfd;
11383 	return link;
11384 }
11385 
11386 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11387 {
11388 	static const char *const prefixes[] = {
11389 		"raw_tp",
11390 		"raw_tracepoint",
11391 		"raw_tp.w",
11392 		"raw_tracepoint.w",
11393 	};
11394 	size_t i;
11395 	const char *tp_name = NULL;
11396 
11397 	*link = NULL;
11398 
11399 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11400 		size_t pfx_len;
11401 
11402 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11403 			continue;
11404 
11405 		pfx_len = strlen(prefixes[i]);
11406 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11407 		if (prog->sec_name[pfx_len] == '\0')
11408 			return 0;
11409 
11410 		if (prog->sec_name[pfx_len] != '/')
11411 			continue;
11412 
11413 		tp_name = prog->sec_name + pfx_len + 1;
11414 		break;
11415 	}
11416 
11417 	if (!tp_name) {
11418 		pr_warn("prog '%s': invalid section name '%s'\n",
11419 			prog->name, prog->sec_name);
11420 		return -EINVAL;
11421 	}
11422 
11423 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11424 	return libbpf_get_error(*link);
11425 }
11426 
11427 /* Common logic for all BPF program types that attach to a btf_id */
11428 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11429 						   const struct bpf_trace_opts *opts)
11430 {
11431 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11432 	char errmsg[STRERR_BUFSIZE];
11433 	struct bpf_link *link;
11434 	int prog_fd, pfd;
11435 
11436 	if (!OPTS_VALID(opts, bpf_trace_opts))
11437 		return libbpf_err_ptr(-EINVAL);
11438 
11439 	prog_fd = bpf_program__fd(prog);
11440 	if (prog_fd < 0) {
11441 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11442 		return libbpf_err_ptr(-EINVAL);
11443 	}
11444 
11445 	link = calloc(1, sizeof(*link));
11446 	if (!link)
11447 		return libbpf_err_ptr(-ENOMEM);
11448 	link->detach = &bpf_link__detach_fd;
11449 
11450 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11451 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11452 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11453 	if (pfd < 0) {
11454 		pfd = -errno;
11455 		free(link);
11456 		pr_warn("prog '%s': failed to attach: %s\n",
11457 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11458 		return libbpf_err_ptr(pfd);
11459 	}
11460 	link->fd = pfd;
11461 	return link;
11462 }
11463 
11464 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11465 {
11466 	return bpf_program__attach_btf_id(prog, NULL);
11467 }
11468 
11469 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11470 						const struct bpf_trace_opts *opts)
11471 {
11472 	return bpf_program__attach_btf_id(prog, opts);
11473 }
11474 
11475 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11476 {
11477 	return bpf_program__attach_btf_id(prog, NULL);
11478 }
11479 
11480 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11481 {
11482 	*link = bpf_program__attach_trace(prog);
11483 	return libbpf_get_error(*link);
11484 }
11485 
11486 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11487 {
11488 	*link = bpf_program__attach_lsm(prog);
11489 	return libbpf_get_error(*link);
11490 }
11491 
11492 static struct bpf_link *
11493 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11494 		       const char *target_name)
11495 {
11496 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11497 			    .target_btf_id = btf_id);
11498 	enum bpf_attach_type attach_type;
11499 	char errmsg[STRERR_BUFSIZE];
11500 	struct bpf_link *link;
11501 	int prog_fd, link_fd;
11502 
11503 	prog_fd = bpf_program__fd(prog);
11504 	if (prog_fd < 0) {
11505 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11506 		return libbpf_err_ptr(-EINVAL);
11507 	}
11508 
11509 	link = calloc(1, sizeof(*link));
11510 	if (!link)
11511 		return libbpf_err_ptr(-ENOMEM);
11512 	link->detach = &bpf_link__detach_fd;
11513 
11514 	attach_type = bpf_program__expected_attach_type(prog);
11515 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11516 	if (link_fd < 0) {
11517 		link_fd = -errno;
11518 		free(link);
11519 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11520 			prog->name, target_name,
11521 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11522 		return libbpf_err_ptr(link_fd);
11523 	}
11524 	link->fd = link_fd;
11525 	return link;
11526 }
11527 
11528 struct bpf_link *
11529 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11530 {
11531 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11532 }
11533 
11534 struct bpf_link *
11535 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11536 {
11537 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11538 }
11539 
11540 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11541 {
11542 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11543 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11544 }
11545 
11546 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11547 					      int target_fd,
11548 					      const char *attach_func_name)
11549 {
11550 	int btf_id;
11551 
11552 	if (!!target_fd != !!attach_func_name) {
11553 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11554 			prog->name);
11555 		return libbpf_err_ptr(-EINVAL);
11556 	}
11557 
11558 	if (prog->type != BPF_PROG_TYPE_EXT) {
11559 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11560 			prog->name);
11561 		return libbpf_err_ptr(-EINVAL);
11562 	}
11563 
11564 	if (target_fd) {
11565 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11566 		if (btf_id < 0)
11567 			return libbpf_err_ptr(btf_id);
11568 
11569 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11570 	} else {
11571 		/* no target, so use raw_tracepoint_open for compatibility
11572 		 * with old kernels
11573 		 */
11574 		return bpf_program__attach_trace(prog);
11575 	}
11576 }
11577 
11578 struct bpf_link *
11579 bpf_program__attach_iter(const struct bpf_program *prog,
11580 			 const struct bpf_iter_attach_opts *opts)
11581 {
11582 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11583 	char errmsg[STRERR_BUFSIZE];
11584 	struct bpf_link *link;
11585 	int prog_fd, link_fd;
11586 	__u32 target_fd = 0;
11587 
11588 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11589 		return libbpf_err_ptr(-EINVAL);
11590 
11591 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11592 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11593 
11594 	prog_fd = bpf_program__fd(prog);
11595 	if (prog_fd < 0) {
11596 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11597 		return libbpf_err_ptr(-EINVAL);
11598 	}
11599 
11600 	link = calloc(1, sizeof(*link));
11601 	if (!link)
11602 		return libbpf_err_ptr(-ENOMEM);
11603 	link->detach = &bpf_link__detach_fd;
11604 
11605 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11606 				  &link_create_opts);
11607 	if (link_fd < 0) {
11608 		link_fd = -errno;
11609 		free(link);
11610 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11611 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11612 		return libbpf_err_ptr(link_fd);
11613 	}
11614 	link->fd = link_fd;
11615 	return link;
11616 }
11617 
11618 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11619 {
11620 	*link = bpf_program__attach_iter(prog, NULL);
11621 	return libbpf_get_error(*link);
11622 }
11623 
11624 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11625 {
11626 	struct bpf_link *link = NULL;
11627 	int err;
11628 
11629 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11630 		return libbpf_err_ptr(-EOPNOTSUPP);
11631 
11632 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11633 	if (err)
11634 		return libbpf_err_ptr(err);
11635 
11636 	/* When calling bpf_program__attach() explicitly, auto-attach support
11637 	 * is expected to work, so NULL returned link is considered an error.
11638 	 * This is different for skeleton's attach, see comment in
11639 	 * bpf_object__attach_skeleton().
11640 	 */
11641 	if (!link)
11642 		return libbpf_err_ptr(-EOPNOTSUPP);
11643 
11644 	return link;
11645 }
11646 
11647 struct bpf_link_struct_ops {
11648 	struct bpf_link link;
11649 	int map_fd;
11650 };
11651 
11652 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11653 {
11654 	struct bpf_link_struct_ops *st_link;
11655 	__u32 zero = 0;
11656 
11657 	st_link = container_of(link, struct bpf_link_struct_ops, link);
11658 
11659 	if (st_link->map_fd < 0)
11660 		/* w/o a real link */
11661 		return bpf_map_delete_elem(link->fd, &zero);
11662 
11663 	return close(link->fd);
11664 }
11665 
11666 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11667 {
11668 	struct bpf_link_struct_ops *link;
11669 	__u32 zero = 0;
11670 	int err, fd;
11671 
11672 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11673 		return libbpf_err_ptr(-EINVAL);
11674 
11675 	link = calloc(1, sizeof(*link));
11676 	if (!link)
11677 		return libbpf_err_ptr(-EINVAL);
11678 
11679 	/* kern_vdata should be prepared during the loading phase. */
11680 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11681 	/* It can be EBUSY if the map has been used to create or
11682 	 * update a link before.  We don't allow updating the value of
11683 	 * a struct_ops once it is set.  That ensures that the value
11684 	 * never changed.  So, it is safe to skip EBUSY.
11685 	 */
11686 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
11687 		free(link);
11688 		return libbpf_err_ptr(err);
11689 	}
11690 
11691 	link->link.detach = bpf_link__detach_struct_ops;
11692 
11693 	if (!(map->def.map_flags & BPF_F_LINK)) {
11694 		/* w/o a real link */
11695 		link->link.fd = map->fd;
11696 		link->map_fd = -1;
11697 		return &link->link;
11698 	}
11699 
11700 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
11701 	if (fd < 0) {
11702 		free(link);
11703 		return libbpf_err_ptr(fd);
11704 	}
11705 
11706 	link->link.fd = fd;
11707 	link->map_fd = map->fd;
11708 
11709 	return &link->link;
11710 }
11711 
11712 /*
11713  * Swap the back struct_ops of a link with a new struct_ops map.
11714  */
11715 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
11716 {
11717 	struct bpf_link_struct_ops *st_ops_link;
11718 	__u32 zero = 0;
11719 	int err;
11720 
11721 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
11722 		return -EINVAL;
11723 
11724 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
11725 	/* Ensure the type of a link is correct */
11726 	if (st_ops_link->map_fd < 0)
11727 		return -EINVAL;
11728 
11729 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11730 	/* It can be EBUSY if the map has been used to create or
11731 	 * update a link before.  We don't allow updating the value of
11732 	 * a struct_ops once it is set.  That ensures that the value
11733 	 * never changed.  So, it is safe to skip EBUSY.
11734 	 */
11735 	if (err && err != -EBUSY)
11736 		return err;
11737 
11738 	err = bpf_link_update(link->fd, map->fd, NULL);
11739 	if (err < 0)
11740 		return err;
11741 
11742 	st_ops_link->map_fd = map->fd;
11743 
11744 	return 0;
11745 }
11746 
11747 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11748 							  void *private_data);
11749 
11750 static enum bpf_perf_event_ret
11751 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11752 		       void **copy_mem, size_t *copy_size,
11753 		       bpf_perf_event_print_t fn, void *private_data)
11754 {
11755 	struct perf_event_mmap_page *header = mmap_mem;
11756 	__u64 data_head = ring_buffer_read_head(header);
11757 	__u64 data_tail = header->data_tail;
11758 	void *base = ((__u8 *)header) + page_size;
11759 	int ret = LIBBPF_PERF_EVENT_CONT;
11760 	struct perf_event_header *ehdr;
11761 	size_t ehdr_size;
11762 
11763 	while (data_head != data_tail) {
11764 		ehdr = base + (data_tail & (mmap_size - 1));
11765 		ehdr_size = ehdr->size;
11766 
11767 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11768 			void *copy_start = ehdr;
11769 			size_t len_first = base + mmap_size - copy_start;
11770 			size_t len_secnd = ehdr_size - len_first;
11771 
11772 			if (*copy_size < ehdr_size) {
11773 				free(*copy_mem);
11774 				*copy_mem = malloc(ehdr_size);
11775 				if (!*copy_mem) {
11776 					*copy_size = 0;
11777 					ret = LIBBPF_PERF_EVENT_ERROR;
11778 					break;
11779 				}
11780 				*copy_size = ehdr_size;
11781 			}
11782 
11783 			memcpy(*copy_mem, copy_start, len_first);
11784 			memcpy(*copy_mem + len_first, base, len_secnd);
11785 			ehdr = *copy_mem;
11786 		}
11787 
11788 		ret = fn(ehdr, private_data);
11789 		data_tail += ehdr_size;
11790 		if (ret != LIBBPF_PERF_EVENT_CONT)
11791 			break;
11792 	}
11793 
11794 	ring_buffer_write_tail(header, data_tail);
11795 	return libbpf_err(ret);
11796 }
11797 
11798 struct perf_buffer;
11799 
11800 struct perf_buffer_params {
11801 	struct perf_event_attr *attr;
11802 	/* if event_cb is specified, it takes precendence */
11803 	perf_buffer_event_fn event_cb;
11804 	/* sample_cb and lost_cb are higher-level common-case callbacks */
11805 	perf_buffer_sample_fn sample_cb;
11806 	perf_buffer_lost_fn lost_cb;
11807 	void *ctx;
11808 	int cpu_cnt;
11809 	int *cpus;
11810 	int *map_keys;
11811 };
11812 
11813 struct perf_cpu_buf {
11814 	struct perf_buffer *pb;
11815 	void *base; /* mmap()'ed memory */
11816 	void *buf; /* for reconstructing segmented data */
11817 	size_t buf_size;
11818 	int fd;
11819 	int cpu;
11820 	int map_key;
11821 };
11822 
11823 struct perf_buffer {
11824 	perf_buffer_event_fn event_cb;
11825 	perf_buffer_sample_fn sample_cb;
11826 	perf_buffer_lost_fn lost_cb;
11827 	void *ctx; /* passed into callbacks */
11828 
11829 	size_t page_size;
11830 	size_t mmap_size;
11831 	struct perf_cpu_buf **cpu_bufs;
11832 	struct epoll_event *events;
11833 	int cpu_cnt; /* number of allocated CPU buffers */
11834 	int epoll_fd; /* perf event FD */
11835 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11836 };
11837 
11838 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11839 				      struct perf_cpu_buf *cpu_buf)
11840 {
11841 	if (!cpu_buf)
11842 		return;
11843 	if (cpu_buf->base &&
11844 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11845 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11846 	if (cpu_buf->fd >= 0) {
11847 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11848 		close(cpu_buf->fd);
11849 	}
11850 	free(cpu_buf->buf);
11851 	free(cpu_buf);
11852 }
11853 
11854 void perf_buffer__free(struct perf_buffer *pb)
11855 {
11856 	int i;
11857 
11858 	if (IS_ERR_OR_NULL(pb))
11859 		return;
11860 	if (pb->cpu_bufs) {
11861 		for (i = 0; i < pb->cpu_cnt; i++) {
11862 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11863 
11864 			if (!cpu_buf)
11865 				continue;
11866 
11867 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11868 			perf_buffer__free_cpu_buf(pb, cpu_buf);
11869 		}
11870 		free(pb->cpu_bufs);
11871 	}
11872 	if (pb->epoll_fd >= 0)
11873 		close(pb->epoll_fd);
11874 	free(pb->events);
11875 	free(pb);
11876 }
11877 
11878 static struct perf_cpu_buf *
11879 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11880 			  int cpu, int map_key)
11881 {
11882 	struct perf_cpu_buf *cpu_buf;
11883 	char msg[STRERR_BUFSIZE];
11884 	int err;
11885 
11886 	cpu_buf = calloc(1, sizeof(*cpu_buf));
11887 	if (!cpu_buf)
11888 		return ERR_PTR(-ENOMEM);
11889 
11890 	cpu_buf->pb = pb;
11891 	cpu_buf->cpu = cpu;
11892 	cpu_buf->map_key = map_key;
11893 
11894 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11895 			      -1, PERF_FLAG_FD_CLOEXEC);
11896 	if (cpu_buf->fd < 0) {
11897 		err = -errno;
11898 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11899 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11900 		goto error;
11901 	}
11902 
11903 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11904 			     PROT_READ | PROT_WRITE, MAP_SHARED,
11905 			     cpu_buf->fd, 0);
11906 	if (cpu_buf->base == MAP_FAILED) {
11907 		cpu_buf->base = NULL;
11908 		err = -errno;
11909 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11910 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11911 		goto error;
11912 	}
11913 
11914 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11915 		err = -errno;
11916 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11917 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11918 		goto error;
11919 	}
11920 
11921 	return cpu_buf;
11922 
11923 error:
11924 	perf_buffer__free_cpu_buf(pb, cpu_buf);
11925 	return (struct perf_cpu_buf *)ERR_PTR(err);
11926 }
11927 
11928 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11929 					      struct perf_buffer_params *p);
11930 
11931 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11932 				     perf_buffer_sample_fn sample_cb,
11933 				     perf_buffer_lost_fn lost_cb,
11934 				     void *ctx,
11935 				     const struct perf_buffer_opts *opts)
11936 {
11937 	const size_t attr_sz = sizeof(struct perf_event_attr);
11938 	struct perf_buffer_params p = {};
11939 	struct perf_event_attr attr;
11940 	__u32 sample_period;
11941 
11942 	if (!OPTS_VALID(opts, perf_buffer_opts))
11943 		return libbpf_err_ptr(-EINVAL);
11944 
11945 	sample_period = OPTS_GET(opts, sample_period, 1);
11946 	if (!sample_period)
11947 		sample_period = 1;
11948 
11949 	memset(&attr, 0, attr_sz);
11950 	attr.size = attr_sz;
11951 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11952 	attr.type = PERF_TYPE_SOFTWARE;
11953 	attr.sample_type = PERF_SAMPLE_RAW;
11954 	attr.sample_period = sample_period;
11955 	attr.wakeup_events = sample_period;
11956 
11957 	p.attr = &attr;
11958 	p.sample_cb = sample_cb;
11959 	p.lost_cb = lost_cb;
11960 	p.ctx = ctx;
11961 
11962 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11963 }
11964 
11965 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11966 					 struct perf_event_attr *attr,
11967 					 perf_buffer_event_fn event_cb, void *ctx,
11968 					 const struct perf_buffer_raw_opts *opts)
11969 {
11970 	struct perf_buffer_params p = {};
11971 
11972 	if (!attr)
11973 		return libbpf_err_ptr(-EINVAL);
11974 
11975 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11976 		return libbpf_err_ptr(-EINVAL);
11977 
11978 	p.attr = attr;
11979 	p.event_cb = event_cb;
11980 	p.ctx = ctx;
11981 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11982 	p.cpus = OPTS_GET(opts, cpus, NULL);
11983 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
11984 
11985 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11986 }
11987 
11988 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11989 					      struct perf_buffer_params *p)
11990 {
11991 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
11992 	struct bpf_map_info map;
11993 	char msg[STRERR_BUFSIZE];
11994 	struct perf_buffer *pb;
11995 	bool *online = NULL;
11996 	__u32 map_info_len;
11997 	int err, i, j, n;
11998 
11999 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12000 		pr_warn("page count should be power of two, but is %zu\n",
12001 			page_cnt);
12002 		return ERR_PTR(-EINVAL);
12003 	}
12004 
12005 	/* best-effort sanity checks */
12006 	memset(&map, 0, sizeof(map));
12007 	map_info_len = sizeof(map);
12008 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12009 	if (err) {
12010 		err = -errno;
12011 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12012 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12013 		 */
12014 		if (err != -EINVAL) {
12015 			pr_warn("failed to get map info for map FD %d: %s\n",
12016 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12017 			return ERR_PTR(err);
12018 		}
12019 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12020 			 map_fd);
12021 	} else {
12022 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12023 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12024 				map.name);
12025 			return ERR_PTR(-EINVAL);
12026 		}
12027 	}
12028 
12029 	pb = calloc(1, sizeof(*pb));
12030 	if (!pb)
12031 		return ERR_PTR(-ENOMEM);
12032 
12033 	pb->event_cb = p->event_cb;
12034 	pb->sample_cb = p->sample_cb;
12035 	pb->lost_cb = p->lost_cb;
12036 	pb->ctx = p->ctx;
12037 
12038 	pb->page_size = getpagesize();
12039 	pb->mmap_size = pb->page_size * page_cnt;
12040 	pb->map_fd = map_fd;
12041 
12042 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12043 	if (pb->epoll_fd < 0) {
12044 		err = -errno;
12045 		pr_warn("failed to create epoll instance: %s\n",
12046 			libbpf_strerror_r(err, msg, sizeof(msg)));
12047 		goto error;
12048 	}
12049 
12050 	if (p->cpu_cnt > 0) {
12051 		pb->cpu_cnt = p->cpu_cnt;
12052 	} else {
12053 		pb->cpu_cnt = libbpf_num_possible_cpus();
12054 		if (pb->cpu_cnt < 0) {
12055 			err = pb->cpu_cnt;
12056 			goto error;
12057 		}
12058 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12059 			pb->cpu_cnt = map.max_entries;
12060 	}
12061 
12062 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12063 	if (!pb->events) {
12064 		err = -ENOMEM;
12065 		pr_warn("failed to allocate events: out of memory\n");
12066 		goto error;
12067 	}
12068 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12069 	if (!pb->cpu_bufs) {
12070 		err = -ENOMEM;
12071 		pr_warn("failed to allocate buffers: out of memory\n");
12072 		goto error;
12073 	}
12074 
12075 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12076 	if (err) {
12077 		pr_warn("failed to get online CPU mask: %d\n", err);
12078 		goto error;
12079 	}
12080 
12081 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12082 		struct perf_cpu_buf *cpu_buf;
12083 		int cpu, map_key;
12084 
12085 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12086 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12087 
12088 		/* in case user didn't explicitly requested particular CPUs to
12089 		 * be attached to, skip offline/not present CPUs
12090 		 */
12091 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12092 			continue;
12093 
12094 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12095 		if (IS_ERR(cpu_buf)) {
12096 			err = PTR_ERR(cpu_buf);
12097 			goto error;
12098 		}
12099 
12100 		pb->cpu_bufs[j] = cpu_buf;
12101 
12102 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12103 					  &cpu_buf->fd, 0);
12104 		if (err) {
12105 			err = -errno;
12106 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12107 				cpu, map_key, cpu_buf->fd,
12108 				libbpf_strerror_r(err, msg, sizeof(msg)));
12109 			goto error;
12110 		}
12111 
12112 		pb->events[j].events = EPOLLIN;
12113 		pb->events[j].data.ptr = cpu_buf;
12114 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12115 			      &pb->events[j]) < 0) {
12116 			err = -errno;
12117 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12118 				cpu, cpu_buf->fd,
12119 				libbpf_strerror_r(err, msg, sizeof(msg)));
12120 			goto error;
12121 		}
12122 		j++;
12123 	}
12124 	pb->cpu_cnt = j;
12125 	free(online);
12126 
12127 	return pb;
12128 
12129 error:
12130 	free(online);
12131 	if (pb)
12132 		perf_buffer__free(pb);
12133 	return ERR_PTR(err);
12134 }
12135 
12136 struct perf_sample_raw {
12137 	struct perf_event_header header;
12138 	uint32_t size;
12139 	char data[];
12140 };
12141 
12142 struct perf_sample_lost {
12143 	struct perf_event_header header;
12144 	uint64_t id;
12145 	uint64_t lost;
12146 	uint64_t sample_id;
12147 };
12148 
12149 static enum bpf_perf_event_ret
12150 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12151 {
12152 	struct perf_cpu_buf *cpu_buf = ctx;
12153 	struct perf_buffer *pb = cpu_buf->pb;
12154 	void *data = e;
12155 
12156 	/* user wants full control over parsing perf event */
12157 	if (pb->event_cb)
12158 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12159 
12160 	switch (e->type) {
12161 	case PERF_RECORD_SAMPLE: {
12162 		struct perf_sample_raw *s = data;
12163 
12164 		if (pb->sample_cb)
12165 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12166 		break;
12167 	}
12168 	case PERF_RECORD_LOST: {
12169 		struct perf_sample_lost *s = data;
12170 
12171 		if (pb->lost_cb)
12172 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12173 		break;
12174 	}
12175 	default:
12176 		pr_warn("unknown perf sample type %d\n", e->type);
12177 		return LIBBPF_PERF_EVENT_ERROR;
12178 	}
12179 	return LIBBPF_PERF_EVENT_CONT;
12180 }
12181 
12182 static int perf_buffer__process_records(struct perf_buffer *pb,
12183 					struct perf_cpu_buf *cpu_buf)
12184 {
12185 	enum bpf_perf_event_ret ret;
12186 
12187 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12188 				     pb->page_size, &cpu_buf->buf,
12189 				     &cpu_buf->buf_size,
12190 				     perf_buffer__process_record, cpu_buf);
12191 	if (ret != LIBBPF_PERF_EVENT_CONT)
12192 		return ret;
12193 	return 0;
12194 }
12195 
12196 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12197 {
12198 	return pb->epoll_fd;
12199 }
12200 
12201 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12202 {
12203 	int i, cnt, err;
12204 
12205 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12206 	if (cnt < 0)
12207 		return -errno;
12208 
12209 	for (i = 0; i < cnt; i++) {
12210 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12211 
12212 		err = perf_buffer__process_records(pb, cpu_buf);
12213 		if (err) {
12214 			pr_warn("error while processing records: %d\n", err);
12215 			return libbpf_err(err);
12216 		}
12217 	}
12218 	return cnt;
12219 }
12220 
12221 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12222  * manager.
12223  */
12224 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12225 {
12226 	return pb->cpu_cnt;
12227 }
12228 
12229 /*
12230  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12231  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12232  * select()/poll()/epoll() Linux syscalls.
12233  */
12234 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12235 {
12236 	struct perf_cpu_buf *cpu_buf;
12237 
12238 	if (buf_idx >= pb->cpu_cnt)
12239 		return libbpf_err(-EINVAL);
12240 
12241 	cpu_buf = pb->cpu_bufs[buf_idx];
12242 	if (!cpu_buf)
12243 		return libbpf_err(-ENOENT);
12244 
12245 	return cpu_buf->fd;
12246 }
12247 
12248 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12249 {
12250 	struct perf_cpu_buf *cpu_buf;
12251 
12252 	if (buf_idx >= pb->cpu_cnt)
12253 		return libbpf_err(-EINVAL);
12254 
12255 	cpu_buf = pb->cpu_bufs[buf_idx];
12256 	if (!cpu_buf)
12257 		return libbpf_err(-ENOENT);
12258 
12259 	*buf = cpu_buf->base;
12260 	*buf_size = pb->mmap_size;
12261 	return 0;
12262 }
12263 
12264 /*
12265  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12266  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12267  * consume, do nothing and return success.
12268  * Returns:
12269  *   - 0 on success;
12270  *   - <0 on failure.
12271  */
12272 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12273 {
12274 	struct perf_cpu_buf *cpu_buf;
12275 
12276 	if (buf_idx >= pb->cpu_cnt)
12277 		return libbpf_err(-EINVAL);
12278 
12279 	cpu_buf = pb->cpu_bufs[buf_idx];
12280 	if (!cpu_buf)
12281 		return libbpf_err(-ENOENT);
12282 
12283 	return perf_buffer__process_records(pb, cpu_buf);
12284 }
12285 
12286 int perf_buffer__consume(struct perf_buffer *pb)
12287 {
12288 	int i, err;
12289 
12290 	for (i = 0; i < pb->cpu_cnt; i++) {
12291 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12292 
12293 		if (!cpu_buf)
12294 			continue;
12295 
12296 		err = perf_buffer__process_records(pb, cpu_buf);
12297 		if (err) {
12298 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12299 			return libbpf_err(err);
12300 		}
12301 	}
12302 	return 0;
12303 }
12304 
12305 int bpf_program__set_attach_target(struct bpf_program *prog,
12306 				   int attach_prog_fd,
12307 				   const char *attach_func_name)
12308 {
12309 	int btf_obj_fd = 0, btf_id = 0, err;
12310 
12311 	if (!prog || attach_prog_fd < 0)
12312 		return libbpf_err(-EINVAL);
12313 
12314 	if (prog->obj->loaded)
12315 		return libbpf_err(-EINVAL);
12316 
12317 	if (attach_prog_fd && !attach_func_name) {
12318 		/* remember attach_prog_fd and let bpf_program__load() find
12319 		 * BTF ID during the program load
12320 		 */
12321 		prog->attach_prog_fd = attach_prog_fd;
12322 		return 0;
12323 	}
12324 
12325 	if (attach_prog_fd) {
12326 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12327 						 attach_prog_fd);
12328 		if (btf_id < 0)
12329 			return libbpf_err(btf_id);
12330 	} else {
12331 		if (!attach_func_name)
12332 			return libbpf_err(-EINVAL);
12333 
12334 		/* load btf_vmlinux, if not yet */
12335 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12336 		if (err)
12337 			return libbpf_err(err);
12338 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12339 					 prog->expected_attach_type,
12340 					 &btf_obj_fd, &btf_id);
12341 		if (err)
12342 			return libbpf_err(err);
12343 	}
12344 
12345 	prog->attach_btf_id = btf_id;
12346 	prog->attach_btf_obj_fd = btf_obj_fd;
12347 	prog->attach_prog_fd = attach_prog_fd;
12348 	return 0;
12349 }
12350 
12351 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12352 {
12353 	int err = 0, n, len, start, end = -1;
12354 	bool *tmp;
12355 
12356 	*mask = NULL;
12357 	*mask_sz = 0;
12358 
12359 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12360 	while (*s) {
12361 		if (*s == ',' || *s == '\n') {
12362 			s++;
12363 			continue;
12364 		}
12365 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12366 		if (n <= 0 || n > 2) {
12367 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12368 			err = -EINVAL;
12369 			goto cleanup;
12370 		} else if (n == 1) {
12371 			end = start;
12372 		}
12373 		if (start < 0 || start > end) {
12374 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12375 				start, end, s);
12376 			err = -EINVAL;
12377 			goto cleanup;
12378 		}
12379 		tmp = realloc(*mask, end + 1);
12380 		if (!tmp) {
12381 			err = -ENOMEM;
12382 			goto cleanup;
12383 		}
12384 		*mask = tmp;
12385 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12386 		memset(tmp + start, 1, end - start + 1);
12387 		*mask_sz = end + 1;
12388 		s += len;
12389 	}
12390 	if (!*mask_sz) {
12391 		pr_warn("Empty CPU range\n");
12392 		return -EINVAL;
12393 	}
12394 	return 0;
12395 cleanup:
12396 	free(*mask);
12397 	*mask = NULL;
12398 	return err;
12399 }
12400 
12401 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12402 {
12403 	int fd, err = 0, len;
12404 	char buf[128];
12405 
12406 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12407 	if (fd < 0) {
12408 		err = -errno;
12409 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12410 		return err;
12411 	}
12412 	len = read(fd, buf, sizeof(buf));
12413 	close(fd);
12414 	if (len <= 0) {
12415 		err = len ? -errno : -EINVAL;
12416 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12417 		return err;
12418 	}
12419 	if (len >= sizeof(buf)) {
12420 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12421 		return -E2BIG;
12422 	}
12423 	buf[len] = '\0';
12424 
12425 	return parse_cpu_mask_str(buf, mask, mask_sz);
12426 }
12427 
12428 int libbpf_num_possible_cpus(void)
12429 {
12430 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12431 	static int cpus;
12432 	int err, n, i, tmp_cpus;
12433 	bool *mask;
12434 
12435 	tmp_cpus = READ_ONCE(cpus);
12436 	if (tmp_cpus > 0)
12437 		return tmp_cpus;
12438 
12439 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12440 	if (err)
12441 		return libbpf_err(err);
12442 
12443 	tmp_cpus = 0;
12444 	for (i = 0; i < n; i++) {
12445 		if (mask[i])
12446 			tmp_cpus++;
12447 	}
12448 	free(mask);
12449 
12450 	WRITE_ONCE(cpus, tmp_cpus);
12451 	return tmp_cpus;
12452 }
12453 
12454 static int populate_skeleton_maps(const struct bpf_object *obj,
12455 				  struct bpf_map_skeleton *maps,
12456 				  size_t map_cnt)
12457 {
12458 	int i;
12459 
12460 	for (i = 0; i < map_cnt; i++) {
12461 		struct bpf_map **map = maps[i].map;
12462 		const char *name = maps[i].name;
12463 		void **mmaped = maps[i].mmaped;
12464 
12465 		*map = bpf_object__find_map_by_name(obj, name);
12466 		if (!*map) {
12467 			pr_warn("failed to find skeleton map '%s'\n", name);
12468 			return -ESRCH;
12469 		}
12470 
12471 		/* externs shouldn't be pre-setup from user code */
12472 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12473 			*mmaped = (*map)->mmaped;
12474 	}
12475 	return 0;
12476 }
12477 
12478 static int populate_skeleton_progs(const struct bpf_object *obj,
12479 				   struct bpf_prog_skeleton *progs,
12480 				   size_t prog_cnt)
12481 {
12482 	int i;
12483 
12484 	for (i = 0; i < prog_cnt; i++) {
12485 		struct bpf_program **prog = progs[i].prog;
12486 		const char *name = progs[i].name;
12487 
12488 		*prog = bpf_object__find_program_by_name(obj, name);
12489 		if (!*prog) {
12490 			pr_warn("failed to find skeleton program '%s'\n", name);
12491 			return -ESRCH;
12492 		}
12493 	}
12494 	return 0;
12495 }
12496 
12497 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12498 			      const struct bpf_object_open_opts *opts)
12499 {
12500 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12501 		.object_name = s->name,
12502 	);
12503 	struct bpf_object *obj;
12504 	int err;
12505 
12506 	/* Attempt to preserve opts->object_name, unless overriden by user
12507 	 * explicitly. Overwriting object name for skeletons is discouraged,
12508 	 * as it breaks global data maps, because they contain object name
12509 	 * prefix as their own map name prefix. When skeleton is generated,
12510 	 * bpftool is making an assumption that this name will stay the same.
12511 	 */
12512 	if (opts) {
12513 		memcpy(&skel_opts, opts, sizeof(*opts));
12514 		if (!opts->object_name)
12515 			skel_opts.object_name = s->name;
12516 	}
12517 
12518 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12519 	err = libbpf_get_error(obj);
12520 	if (err) {
12521 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12522 			s->name, err);
12523 		return libbpf_err(err);
12524 	}
12525 
12526 	*s->obj = obj;
12527 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12528 	if (err) {
12529 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12530 		return libbpf_err(err);
12531 	}
12532 
12533 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12534 	if (err) {
12535 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12536 		return libbpf_err(err);
12537 	}
12538 
12539 	return 0;
12540 }
12541 
12542 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12543 {
12544 	int err, len, var_idx, i;
12545 	const char *var_name;
12546 	const struct bpf_map *map;
12547 	struct btf *btf;
12548 	__u32 map_type_id;
12549 	const struct btf_type *map_type, *var_type;
12550 	const struct bpf_var_skeleton *var_skel;
12551 	struct btf_var_secinfo *var;
12552 
12553 	if (!s->obj)
12554 		return libbpf_err(-EINVAL);
12555 
12556 	btf = bpf_object__btf(s->obj);
12557 	if (!btf) {
12558 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12559 			bpf_object__name(s->obj));
12560 		return libbpf_err(-errno);
12561 	}
12562 
12563 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12564 	if (err) {
12565 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12566 		return libbpf_err(err);
12567 	}
12568 
12569 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12570 	if (err) {
12571 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12572 		return libbpf_err(err);
12573 	}
12574 
12575 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12576 		var_skel = &s->vars[var_idx];
12577 		map = *var_skel->map;
12578 		map_type_id = bpf_map__btf_value_type_id(map);
12579 		map_type = btf__type_by_id(btf, map_type_id);
12580 
12581 		if (!btf_is_datasec(map_type)) {
12582 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12583 				bpf_map__name(map),
12584 				__btf_kind_str(btf_kind(map_type)));
12585 			return libbpf_err(-EINVAL);
12586 		}
12587 
12588 		len = btf_vlen(map_type);
12589 		var = btf_var_secinfos(map_type);
12590 		for (i = 0; i < len; i++, var++) {
12591 			var_type = btf__type_by_id(btf, var->type);
12592 			var_name = btf__name_by_offset(btf, var_type->name_off);
12593 			if (strcmp(var_name, var_skel->name) == 0) {
12594 				*var_skel->addr = map->mmaped + var->offset;
12595 				break;
12596 			}
12597 		}
12598 	}
12599 	return 0;
12600 }
12601 
12602 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12603 {
12604 	if (!s)
12605 		return;
12606 	free(s->maps);
12607 	free(s->progs);
12608 	free(s->vars);
12609 	free(s);
12610 }
12611 
12612 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12613 {
12614 	int i, err;
12615 
12616 	err = bpf_object__load(*s->obj);
12617 	if (err) {
12618 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12619 		return libbpf_err(err);
12620 	}
12621 
12622 	for (i = 0; i < s->map_cnt; i++) {
12623 		struct bpf_map *map = *s->maps[i].map;
12624 		size_t mmap_sz = bpf_map_mmap_sz(map);
12625 		int prot, map_fd = bpf_map__fd(map);
12626 		void **mmaped = s->maps[i].mmaped;
12627 
12628 		if (!mmaped)
12629 			continue;
12630 
12631 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12632 			*mmaped = NULL;
12633 			continue;
12634 		}
12635 
12636 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12637 			prot = PROT_READ;
12638 		else
12639 			prot = PROT_READ | PROT_WRITE;
12640 
12641 		/* Remap anonymous mmap()-ed "map initialization image" as
12642 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12643 		 * memory address. This will cause kernel to change process'
12644 		 * page table to point to a different piece of kernel memory,
12645 		 * but from userspace point of view memory address (and its
12646 		 * contents, being identical at this point) will stay the
12647 		 * same. This mapping will be released by bpf_object__close()
12648 		 * as per normal clean up procedure, so we don't need to worry
12649 		 * about it from skeleton's clean up perspective.
12650 		 */
12651 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
12652 				MAP_SHARED | MAP_FIXED, map_fd, 0);
12653 		if (*mmaped == MAP_FAILED) {
12654 			err = -errno;
12655 			*mmaped = NULL;
12656 			pr_warn("failed to re-mmap() map '%s': %d\n",
12657 				 bpf_map__name(map), err);
12658 			return libbpf_err(err);
12659 		}
12660 	}
12661 
12662 	return 0;
12663 }
12664 
12665 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12666 {
12667 	int i, err;
12668 
12669 	for (i = 0; i < s->prog_cnt; i++) {
12670 		struct bpf_program *prog = *s->progs[i].prog;
12671 		struct bpf_link **link = s->progs[i].link;
12672 
12673 		if (!prog->autoload || !prog->autoattach)
12674 			continue;
12675 
12676 		/* auto-attaching not supported for this program */
12677 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12678 			continue;
12679 
12680 		/* if user already set the link manually, don't attempt auto-attach */
12681 		if (*link)
12682 			continue;
12683 
12684 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12685 		if (err) {
12686 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12687 				bpf_program__name(prog), err);
12688 			return libbpf_err(err);
12689 		}
12690 
12691 		/* It's possible that for some SEC() definitions auto-attach
12692 		 * is supported in some cases (e.g., if definition completely
12693 		 * specifies target information), but is not in other cases.
12694 		 * SEC("uprobe") is one such case. If user specified target
12695 		 * binary and function name, such BPF program can be
12696 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12697 		 * attach to fail. It should just be skipped.
12698 		 * attach_fn signals such case with returning 0 (no error) and
12699 		 * setting link to NULL.
12700 		 */
12701 	}
12702 
12703 	return 0;
12704 }
12705 
12706 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12707 {
12708 	int i;
12709 
12710 	for (i = 0; i < s->prog_cnt; i++) {
12711 		struct bpf_link **link = s->progs[i].link;
12712 
12713 		bpf_link__destroy(*link);
12714 		*link = NULL;
12715 	}
12716 }
12717 
12718 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12719 {
12720 	if (!s)
12721 		return;
12722 
12723 	if (s->progs)
12724 		bpf_object__detach_skeleton(s);
12725 	if (s->obj)
12726 		bpf_object__close(*s->obj);
12727 	free(s->maps);
12728 	free(s->progs);
12729 	free(s);
12730 }
12731