xref: /linux/tools/lib/bpf/libbpf.c (revision 9779193e871b144e34ec4a3e50109b3778a51a69)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/bpf_perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define MAX_EVENT_NAME_LEN	64
63 
64 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
65 
66 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
67 
68 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
69  * compilation if user enables corresponding warning. Disable it explicitly.
70  */
71 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
72 
73 #define __printf(a, b)	__attribute__((format(printf, a, b)))
74 
75 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
76 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
77 static int map_set_def_max_entries(struct bpf_map *map);
78 
79 static const char * const attach_type_name[] = {
80 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
81 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
82 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
83 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
84 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
85 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
86 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
87 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
88 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
89 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
90 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
91 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
92 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
93 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
94 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
95 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
96 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
97 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
98 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
99 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
100 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
101 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
102 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
103 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
104 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
105 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
106 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
107 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
108 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
109 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
110 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
111 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
112 	[BPF_LIRC_MODE2]		= "lirc_mode2",
113 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
114 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
115 	[BPF_TRACE_FENTRY]		= "trace_fentry",
116 	[BPF_TRACE_FEXIT]		= "trace_fexit",
117 	[BPF_MODIFY_RETURN]		= "modify_return",
118 	[BPF_TRACE_FSESSION]		= "trace_fsession",
119 	[BPF_LSM_MAC]			= "lsm_mac",
120 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
121 	[BPF_SK_LOOKUP]			= "sk_lookup",
122 	[BPF_TRACE_ITER]		= "trace_iter",
123 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
124 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
125 	[BPF_XDP]			= "xdp",
126 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
127 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
128 	[BPF_PERF_EVENT]		= "perf_event",
129 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
130 	[BPF_STRUCT_OPS]		= "struct_ops",
131 	[BPF_NETFILTER]			= "netfilter",
132 	[BPF_TCX_INGRESS]		= "tcx_ingress",
133 	[BPF_TCX_EGRESS]		= "tcx_egress",
134 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
135 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
136 	[BPF_NETKIT_PEER]		= "netkit_peer",
137 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
138 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
139 };
140 
141 static const char * const link_type_name[] = {
142 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
143 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
144 	[BPF_LINK_TYPE_TRACING]			= "tracing",
145 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
146 	[BPF_LINK_TYPE_ITER]			= "iter",
147 	[BPF_LINK_TYPE_NETNS]			= "netns",
148 	[BPF_LINK_TYPE_XDP]			= "xdp",
149 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
150 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
151 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
152 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
153 	[BPF_LINK_TYPE_TCX]			= "tcx",
154 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
155 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
156 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
157 };
158 
159 static const char * const map_type_name[] = {
160 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
161 	[BPF_MAP_TYPE_HASH]			= "hash",
162 	[BPF_MAP_TYPE_ARRAY]			= "array",
163 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
164 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
165 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
166 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
167 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
168 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
169 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
170 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
171 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
172 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
173 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
174 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
175 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
176 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
177 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
178 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
179 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
180 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
181 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
182 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
183 	[BPF_MAP_TYPE_QUEUE]			= "queue",
184 	[BPF_MAP_TYPE_STACK]			= "stack",
185 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
186 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
187 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
188 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
189 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
190 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
191 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
192 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
193 	[BPF_MAP_TYPE_ARENA]			= "arena",
194 	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
195 	[BPF_MAP_TYPE_RHASH]			= "rhash",
196 };
197 
198 static const char * const prog_type_name[] = {
199 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
200 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
201 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
202 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
203 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
204 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
205 	[BPF_PROG_TYPE_XDP]			= "xdp",
206 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
207 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
208 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
209 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
210 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
211 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
212 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
213 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
214 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
215 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
216 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
217 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
218 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
219 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
220 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
221 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
222 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
223 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
224 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
225 	[BPF_PROG_TYPE_TRACING]			= "tracing",
226 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
227 	[BPF_PROG_TYPE_EXT]			= "ext",
228 	[BPF_PROG_TYPE_LSM]			= "lsm",
229 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
230 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
231 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
232 };
233 
234 static int __base_pr(enum libbpf_print_level level, const char *format,
235 		     va_list args)
236 {
237 	const char *env_var = "LIBBPF_LOG_LEVEL";
238 	static enum libbpf_print_level min_level = LIBBPF_INFO;
239 	static bool initialized;
240 
241 	if (!initialized) {
242 		char *verbosity;
243 
244 		initialized = true;
245 		verbosity = getenv(env_var);
246 		if (verbosity) {
247 			if (strcasecmp(verbosity, "warn") == 0)
248 				min_level = LIBBPF_WARN;
249 			else if (strcasecmp(verbosity, "debug") == 0)
250 				min_level = LIBBPF_DEBUG;
251 			else if (strcasecmp(verbosity, "info") == 0)
252 				min_level = LIBBPF_INFO;
253 			else
254 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
255 					env_var, verbosity);
256 		}
257 	}
258 
259 	/* if too verbose, skip logging  */
260 	if (level > min_level)
261 		return 0;
262 
263 	return vfprintf(stderr, format, args);
264 }
265 
266 static libbpf_print_fn_t __libbpf_pr = __base_pr;
267 
268 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
269 {
270 	libbpf_print_fn_t old_print_fn;
271 
272 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
273 
274 	return old_print_fn;
275 }
276 
277 __printf(2, 3)
278 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
279 {
280 	va_list args;
281 	int old_errno;
282 	libbpf_print_fn_t print_fn;
283 
284 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
285 	if (!print_fn)
286 		return;
287 
288 	old_errno = errno;
289 
290 	va_start(args, format);
291 	print_fn(level, format, args);
292 	va_end(args);
293 
294 	errno = old_errno;
295 }
296 
297 static void pr_perm_msg(int err)
298 {
299 	struct rlimit limit;
300 	char buf[100];
301 
302 	if (err != -EPERM || geteuid() != 0)
303 		return;
304 
305 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
306 	if (err)
307 		return;
308 
309 	if (limit.rlim_cur == RLIM_INFINITY)
310 		return;
311 
312 	if (limit.rlim_cur < 1024)
313 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
314 	else if (limit.rlim_cur < 1024*1024)
315 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
316 	else
317 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
318 
319 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
320 		buf);
321 }
322 
323 /* Copied from tools/perf/util/util.h */
324 #ifndef zfree
325 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
326 #endif
327 
328 #ifndef zclose
329 # define zclose(fd) ({			\
330 	int ___err = 0;			\
331 	if ((fd) >= 0)			\
332 		___err = close((fd));	\
333 	fd = -1;			\
334 	___err; })
335 #endif
336 
337 static inline __u64 ptr_to_u64(const void *ptr)
338 {
339 	return (__u64) (unsigned long) ptr;
340 }
341 
342 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
343 {
344 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
345 	return 0;
346 }
347 
348 __u32 libbpf_major_version(void)
349 {
350 	return LIBBPF_MAJOR_VERSION;
351 }
352 
353 __u32 libbpf_minor_version(void)
354 {
355 	return LIBBPF_MINOR_VERSION;
356 }
357 
358 const char *libbpf_version_string(void)
359 {
360 #define __S(X) #X
361 #define _S(X) __S(X)
362 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
363 #undef _S
364 #undef __S
365 }
366 
367 enum reloc_type {
368 	RELO_LD64,
369 	RELO_CALL,
370 	RELO_DATA,
371 	RELO_EXTERN_LD64,
372 	RELO_EXTERN_CALL,
373 	RELO_SUBPROG_ADDR,
374 	RELO_CORE,
375 	RELO_INSN_ARRAY,
376 };
377 
378 struct reloc_desc {
379 	enum reloc_type type;
380 	int insn_idx;
381 	union {
382 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
383 		struct {
384 			int map_idx;
385 			unsigned int sym_off;
386 			/*
387 			 * The following two fields can be unionized, as the
388 			 * ext_idx field is used for extern symbols, and the
389 			 * sym_size is used for jump tables, which are never
390 			 * extern
391 			 */
392 			union {
393 				int ext_idx;
394 				int sym_size;
395 			};
396 		};
397 	};
398 };
399 
400 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
401 enum sec_def_flags {
402 	SEC_NONE = 0,
403 	/* expected_attach_type is optional, if kernel doesn't support that */
404 	SEC_EXP_ATTACH_OPT = 1,
405 	/* legacy, only used by libbpf_get_type_names() and
406 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
407 	 * This used to be associated with cgroup (and few other) BPF programs
408 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
409 	 * meaningless nowadays, though.
410 	 */
411 	SEC_ATTACHABLE = 2,
412 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
413 	/* attachment target is specified through BTF ID in either kernel or
414 	 * other BPF program's BTF object
415 	 */
416 	SEC_ATTACH_BTF = 4,
417 	/* BPF program type allows sleeping/blocking in kernel */
418 	SEC_SLEEPABLE = 8,
419 	/* BPF program support non-linear XDP buffer */
420 	SEC_XDP_FRAGS = 16,
421 	/* Setup proper attach type for usdt probes. */
422 	SEC_USDT = 32,
423 };
424 
425 struct bpf_sec_def {
426 	char *sec;
427 	enum bpf_prog_type prog_type;
428 	enum bpf_attach_type expected_attach_type;
429 	long cookie;
430 	int handler_id;
431 
432 	libbpf_prog_setup_fn_t prog_setup_fn;
433 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
434 	libbpf_prog_attach_fn_t prog_attach_fn;
435 };
436 
437 struct bpf_light_subprog {
438 	__u32 sec_insn_off;
439 	__u32 sub_insn_off;
440 };
441 
442 /*
443  * bpf_prog should be a better name but it has been used in
444  * linux/filter.h.
445  */
446 struct bpf_program {
447 	char *name;
448 	char *sec_name;
449 	size_t sec_idx;
450 	const struct bpf_sec_def *sec_def;
451 	/* this program's instruction offset (in number of instructions)
452 	 * within its containing ELF section
453 	 */
454 	size_t sec_insn_off;
455 	/* number of original instructions in ELF section belonging to this
456 	 * program, not taking into account subprogram instructions possible
457 	 * appended later during relocation
458 	 */
459 	size_t sec_insn_cnt;
460 	/* Offset (in number of instructions) of the start of instruction
461 	 * belonging to this BPF program  within its containing main BPF
462 	 * program. For the entry-point (main) BPF program, this is always
463 	 * zero. For a sub-program, this gets reset before each of main BPF
464 	 * programs are processed and relocated and is used to determined
465 	 * whether sub-program was already appended to the main program, and
466 	 * if yes, at which instruction offset.
467 	 */
468 	size_t sub_insn_off;
469 
470 	/* instructions that belong to BPF program; insns[0] is located at
471 	 * sec_insn_off instruction within its ELF section in ELF file, so
472 	 * when mapping ELF file instruction index to the local instruction,
473 	 * one needs to subtract sec_insn_off; and vice versa.
474 	 */
475 	struct bpf_insn *insns;
476 	/* actual number of instruction in this BPF program's image; for
477 	 * entry-point BPF programs this includes the size of main program
478 	 * itself plus all the used sub-programs, appended at the end
479 	 */
480 	size_t insns_cnt;
481 
482 	struct reloc_desc *reloc_desc;
483 	int nr_reloc;
484 
485 	/* BPF verifier log settings */
486 	char *log_buf;
487 	size_t log_size;
488 	__u32 log_level;
489 
490 	struct bpf_object *obj;
491 
492 	int fd;
493 	bool autoload;
494 	bool autoattach;
495 	bool sym_global;
496 	bool mark_btf_static;
497 	enum bpf_prog_type type;
498 	enum bpf_attach_type expected_attach_type;
499 	int exception_cb_idx;
500 
501 	int prog_ifindex;
502 	__u32 attach_btf_obj_fd;
503 	__u32 attach_btf_id;
504 	__u32 attach_prog_fd;
505 
506 	void *func_info;
507 	__u32 func_info_rec_size;
508 	__u32 func_info_cnt;
509 
510 	void *line_info;
511 	__u32 line_info_rec_size;
512 	__u32 line_info_cnt;
513 	__u32 prog_flags;
514 	__u8  hash[SHA256_DIGEST_LENGTH];
515 
516 	struct bpf_light_subprog *subprogs;
517 	__u32 subprog_cnt;
518 };
519 
520 struct bpf_struct_ops {
521 	struct bpf_program **progs;
522 	__u32 *kern_func_off;
523 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
524 	void *data;
525 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
526 	 *      btf_vmlinux's format.
527 	 * struct bpf_struct_ops_tcp_congestion_ops {
528 	 *	[... some other kernel fields ...]
529 	 *	struct tcp_congestion_ops data;
530 	 * }
531 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
532 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
533 	 * from "data".
534 	 */
535 	void *kern_vdata;
536 	__u32 type_id;
537 };
538 
539 #define DATA_SEC ".data"
540 #define BSS_SEC ".bss"
541 #define RODATA_SEC ".rodata"
542 #define KCONFIG_SEC ".kconfig"
543 #define KSYMS_SEC ".ksyms"
544 #define STRUCT_OPS_SEC ".struct_ops"
545 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
546 #define ARENA_SEC ".addr_space.1"
547 
548 enum libbpf_map_type {
549 	LIBBPF_MAP_UNSPEC,
550 	LIBBPF_MAP_DATA,
551 	LIBBPF_MAP_BSS,
552 	LIBBPF_MAP_RODATA,
553 	LIBBPF_MAP_KCONFIG,
554 };
555 
556 struct bpf_map_def {
557 	unsigned int type;
558 	unsigned int key_size;
559 	unsigned int value_size;
560 	unsigned int max_entries;
561 	unsigned int map_flags;
562 };
563 
564 struct bpf_map {
565 	struct bpf_object *obj;
566 	char *name;
567 	/* real_name is defined for special internal maps (.rodata*,
568 	 * .data*, .bss, .kconfig) and preserves their original ELF section
569 	 * name. This is important to be able to find corresponding BTF
570 	 * DATASEC information.
571 	 */
572 	char *real_name;
573 	int fd;
574 	int sec_idx;
575 	size_t sec_offset;
576 	int map_ifindex;
577 	int inner_map_fd;
578 	struct bpf_map_def def;
579 	__u32 numa_node;
580 	__u32 btf_var_idx;
581 	int mod_btf_fd;
582 	__u32 btf_key_type_id;
583 	__u32 btf_value_type_id;
584 	__u32 btf_vmlinux_value_type_id;
585 	enum libbpf_map_type libbpf_type;
586 	void *mmaped;
587 	struct bpf_struct_ops *st_ops;
588 	struct bpf_map *inner_map;
589 	void **init_slots;
590 	int init_slots_sz;
591 	char *pin_path;
592 	bool pinned;
593 	bool reused;
594 	bool autocreate;
595 	bool autoattach;
596 	__u64 map_extra;
597 	struct bpf_program *excl_prog;
598 };
599 
600 enum extern_type {
601 	EXT_UNKNOWN,
602 	EXT_KCFG,
603 	EXT_KSYM,
604 };
605 
606 enum kcfg_type {
607 	KCFG_UNKNOWN,
608 	KCFG_CHAR,
609 	KCFG_BOOL,
610 	KCFG_INT,
611 	KCFG_TRISTATE,
612 	KCFG_CHAR_ARR,
613 };
614 
615 struct extern_desc {
616 	enum extern_type type;
617 	int sym_idx;
618 	int btf_id;
619 	int sec_btf_id;
620 	char *name;
621 	char *essent_name;
622 	bool is_set;
623 	bool is_weak;
624 	union {
625 		struct {
626 			enum kcfg_type type;
627 			int sz;
628 			int align;
629 			int data_off;
630 			bool is_signed;
631 		} kcfg;
632 		struct {
633 			unsigned long long addr;
634 
635 			/* target btf_id of the corresponding kernel var. */
636 			int kernel_btf_obj_fd;
637 			int kernel_btf_id;
638 
639 			/* local btf_id of the ksym extern's type. */
640 			__u32 type_id;
641 			/* BTF fd index to be patched in for insn->off, this is
642 			 * 0 for vmlinux BTF, index in obj->fd_array for module
643 			 * BTF
644 			 */
645 			__s16 btf_fd_idx;
646 		} ksym;
647 	};
648 };
649 
650 struct module_btf {
651 	struct btf *btf;
652 	char *name;
653 	__u32 id;
654 	int fd;
655 	int fd_array_idx;
656 };
657 
658 enum sec_type {
659 	SEC_UNUSED = 0,
660 	SEC_RELO,
661 	SEC_BSS,
662 	SEC_DATA,
663 	SEC_RODATA,
664 	SEC_ST_OPS,
665 };
666 
667 struct elf_sec_desc {
668 	enum sec_type sec_type;
669 	Elf64_Shdr *shdr;
670 	Elf_Data *data;
671 };
672 
673 struct elf_state {
674 	int fd;
675 	const void *obj_buf;
676 	size_t obj_buf_sz;
677 	Elf *elf;
678 	Elf64_Ehdr *ehdr;
679 	Elf_Data *symbols;
680 	Elf_Data *arena_data;
681 	size_t shstrndx; /* section index for section name strings */
682 	size_t strtabidx;
683 	struct elf_sec_desc *secs;
684 	size_t sec_cnt;
685 	int btf_maps_shndx;
686 	__u32 btf_maps_sec_btf_id;
687 	int text_shndx;
688 	int symbols_shndx;
689 	bool has_st_ops;
690 	int arena_data_shndx;
691 	int jumptables_data_shndx;
692 };
693 
694 struct usdt_manager;
695 
696 enum bpf_object_state {
697 	OBJ_OPEN,
698 	OBJ_PREPARED,
699 	OBJ_LOADED,
700 };
701 
702 struct bpf_object {
703 	char name[BPF_OBJ_NAME_LEN];
704 	char license[64];
705 	__u32 kern_version;
706 
707 	enum bpf_object_state state;
708 	struct bpf_program *programs;
709 	size_t nr_programs;
710 	struct bpf_map *maps;
711 	size_t nr_maps;
712 	size_t maps_cap;
713 
714 	char *kconfig;
715 	struct extern_desc *externs;
716 	int nr_extern;
717 	int kconfig_map_idx;
718 
719 	bool has_subcalls;
720 	bool has_rodata;
721 
722 	struct bpf_gen *gen_loader;
723 
724 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
725 	struct elf_state efile;
726 
727 	unsigned char byteorder;
728 
729 	struct btf *btf;
730 	struct btf_ext *btf_ext;
731 
732 	/* Parse and load BTF vmlinux if any of the programs in the object need
733 	 * it at load time.
734 	 */
735 	struct btf *btf_vmlinux;
736 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
737 	 * override for vmlinux BTF.
738 	 */
739 	char *btf_custom_path;
740 	/* vmlinux BTF override for CO-RE relocations */
741 	struct btf *btf_vmlinux_override;
742 	/* Lazily initialized kernel module BTFs */
743 	struct module_btf *btf_modules;
744 	bool btf_modules_loaded;
745 	size_t btf_module_cnt;
746 	size_t btf_module_cap;
747 
748 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
749 	char *log_buf;
750 	size_t log_size;
751 	__u32 log_level;
752 
753 	int *fd_array;
754 	size_t fd_array_cap;
755 	size_t fd_array_cnt;
756 
757 	struct usdt_manager *usdt_man;
758 
759 	int arena_map_idx;
760 	void *arena_data;
761 	size_t arena_data_sz;
762 	size_t arena_data_off;
763 
764 	void *jumptables_data;
765 	size_t jumptables_data_sz;
766 
767 	struct {
768 		struct bpf_program *prog;
769 		unsigned int sym_off;
770 		int fd;
771 	} *jumptable_maps;
772 	size_t jumptable_map_cnt;
773 
774 	struct kern_feature_cache *feat_cache;
775 	char *token_path;
776 	int token_fd;
777 
778 	char path[];
779 };
780 
781 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
782 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
783 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
784 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
785 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
786 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
787 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
788 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
789 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
790 
791 void bpf_program__unload(struct bpf_program *prog)
792 {
793 	if (!prog)
794 		return;
795 
796 	zclose(prog->fd);
797 
798 	zfree(&prog->func_info);
799 	zfree(&prog->line_info);
800 	zfree(&prog->subprogs);
801 }
802 
803 static void bpf_program__exit(struct bpf_program *prog)
804 {
805 	if (!prog)
806 		return;
807 
808 	bpf_program__unload(prog);
809 	zfree(&prog->name);
810 	zfree(&prog->sec_name);
811 	zfree(&prog->insns);
812 	zfree(&prog->reloc_desc);
813 
814 	prog->nr_reloc = 0;
815 	prog->insns_cnt = 0;
816 	prog->sec_idx = -1;
817 }
818 
819 static bool insn_is_subprog_call(const struct bpf_insn *insn)
820 {
821 	return BPF_CLASS(insn->code) == BPF_JMP &&
822 	       BPF_OP(insn->code) == BPF_CALL &&
823 	       BPF_SRC(insn->code) == BPF_K &&
824 	       insn->src_reg == BPF_PSEUDO_CALL &&
825 	       insn->dst_reg == 0 &&
826 	       insn->off == 0;
827 }
828 
829 static bool is_call_insn(const struct bpf_insn *insn)
830 {
831 	return insn->code == (BPF_JMP | BPF_CALL);
832 }
833 
834 static bool insn_is_pseudo_func(struct bpf_insn *insn)
835 {
836 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
837 }
838 
839 static int
840 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
841 		      const char *name, size_t sec_idx, const char *sec_name,
842 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
843 {
844 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
845 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
846 			sec_name, name, sec_off, insn_data_sz);
847 		return -EINVAL;
848 	}
849 
850 	memset(prog, 0, sizeof(*prog));
851 	prog->obj = obj;
852 
853 	prog->sec_idx = sec_idx;
854 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
855 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
856 	/* insns_cnt can later be increased by appending used subprograms */
857 	prog->insns_cnt = prog->sec_insn_cnt;
858 
859 	prog->type = BPF_PROG_TYPE_UNSPEC;
860 	prog->fd = -1;
861 	prog->exception_cb_idx = -1;
862 
863 	/* libbpf's convention for SEC("?abc...") is that it's just like
864 	 * SEC("abc...") but the corresponding bpf_program starts out with
865 	 * autoload set to false.
866 	 */
867 	if (sec_name[0] == '?') {
868 		prog->autoload = false;
869 		/* from now on forget there was ? in section name */
870 		sec_name++;
871 	} else {
872 		prog->autoload = true;
873 	}
874 
875 	prog->autoattach = true;
876 
877 	/* inherit object's log_level */
878 	prog->log_level = obj->log_level;
879 
880 	prog->sec_name = strdup(sec_name);
881 	if (!prog->sec_name)
882 		goto errout;
883 
884 	prog->name = strdup(name);
885 	if (!prog->name)
886 		goto errout;
887 
888 	prog->insns = malloc(insn_data_sz);
889 	if (!prog->insns)
890 		goto errout;
891 	memcpy(prog->insns, insn_data, insn_data_sz);
892 
893 	return 0;
894 errout:
895 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
896 	bpf_program__exit(prog);
897 	return -ENOMEM;
898 }
899 
900 static int
901 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
902 			 const char *sec_name, int sec_idx)
903 {
904 	Elf_Data *symbols = obj->efile.symbols;
905 	struct bpf_program *prog, *progs;
906 	void *data = sec_data->d_buf;
907 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
908 	int nr_progs, err, i;
909 	const char *name;
910 	Elf64_Sym *sym;
911 
912 	progs = obj->programs;
913 	nr_progs = obj->nr_programs;
914 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
915 
916 	for (i = 0; i < nr_syms; i++) {
917 		sym = elf_sym_by_idx(obj, i);
918 
919 		if (sym->st_shndx != sec_idx)
920 			continue;
921 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
922 			continue;
923 
924 		prog_sz = sym->st_size;
925 		sec_off = sym->st_value;
926 
927 		name = elf_sym_str(obj, sym->st_name);
928 		if (!name) {
929 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
930 				sec_name, sec_off);
931 			return -LIBBPF_ERRNO__FORMAT;
932 		}
933 
934 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
935 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
936 				sec_name, sec_off);
937 			return -LIBBPF_ERRNO__FORMAT;
938 		}
939 
940 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
941 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
942 			return -ENOTSUP;
943 		}
944 
945 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
946 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
947 
948 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
949 		if (!progs) {
950 			/*
951 			 * In this case the original obj->programs
952 			 * is still valid, so don't need special treat for
953 			 * bpf_close_object().
954 			 */
955 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
956 				sec_name, name);
957 			return -ENOMEM;
958 		}
959 		obj->programs = progs;
960 
961 		prog = &progs[nr_progs];
962 
963 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
964 					    sec_off, data + sec_off, prog_sz);
965 		if (err)
966 			return err;
967 
968 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
969 			prog->sym_global = true;
970 
971 		/* if function is a global/weak symbol, but has restricted
972 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
973 		 * as static to enable more permissive BPF verification mode
974 		 * with more outside context available to BPF verifier
975 		 */
976 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
977 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
978 			prog->mark_btf_static = true;
979 
980 		nr_progs++;
981 		obj->nr_programs = nr_progs;
982 	}
983 
984 	return 0;
985 }
986 
987 static void bpf_object_bswap_progs(struct bpf_object *obj)
988 {
989 	struct bpf_program *prog = obj->programs;
990 	struct bpf_insn *insn;
991 	int p, i;
992 
993 	for (p = 0; p < obj->nr_programs; p++, prog++) {
994 		insn = prog->insns;
995 		for (i = 0; i < prog->insns_cnt; i++, insn++)
996 			bpf_insn_bswap(insn);
997 	}
998 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
999 }
1000 
1001 static const struct btf_member *
1002 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1003 {
1004 	struct btf_member *m;
1005 	int i;
1006 
1007 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1008 		if (btf_member_bit_offset(t, i) == bit_offset)
1009 			return m;
1010 	}
1011 
1012 	return NULL;
1013 }
1014 
1015 static const struct btf_member *
1016 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1017 		    const char *name)
1018 {
1019 	struct btf_member *m;
1020 	int i;
1021 
1022 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1023 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1024 			return m;
1025 	}
1026 
1027 	return NULL;
1028 }
1029 
1030 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1031 			    __u16 kind, struct btf **res_btf,
1032 			    struct module_btf **res_mod_btf);
1033 
1034 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1035 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1036 				   const char *name, __u32 kind);
1037 
1038 static int
1039 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1040 			   struct module_btf **mod_btf,
1041 			   const struct btf_type **type, __u32 *type_id,
1042 			   const struct btf_type **vtype, __u32 *vtype_id,
1043 			   const struct btf_member **data_member)
1044 {
1045 	const struct btf_type *kern_type, *kern_vtype;
1046 	const struct btf_member *kern_data_member;
1047 	struct btf *btf = NULL;
1048 	__s32 kern_vtype_id, kern_type_id;
1049 	char tname[192], stname[256];
1050 	__u32 i;
1051 
1052 	snprintf(tname, sizeof(tname), "%.*s",
1053 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1054 
1055 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1056 
1057 	/* Look for the corresponding "map_value" type that will be used
1058 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1059 	 * and the mod_btf.
1060 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1061 	 */
1062 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1063 	if (kern_vtype_id < 0) {
1064 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1065 		return kern_vtype_id;
1066 	}
1067 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1068 
1069 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1070 	if (kern_type_id < 0) {
1071 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1072 		return kern_type_id;
1073 	}
1074 	kern_type = btf__type_by_id(btf, kern_type_id);
1075 
1076 	/* Find "struct tcp_congestion_ops" from
1077 	 * struct bpf_struct_ops_tcp_congestion_ops {
1078 	 *	[ ... ]
1079 	 *	struct tcp_congestion_ops data;
1080 	 * }
1081 	 */
1082 	kern_data_member = btf_members(kern_vtype);
1083 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1084 		if (kern_data_member->type == kern_type_id)
1085 			break;
1086 	}
1087 	if (i == btf_vlen(kern_vtype)) {
1088 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1089 			tname, stname);
1090 		return -EINVAL;
1091 	}
1092 
1093 	*type = kern_type;
1094 	*type_id = kern_type_id;
1095 	*vtype = kern_vtype;
1096 	*vtype_id = kern_vtype_id;
1097 	*data_member = kern_data_member;
1098 
1099 	return 0;
1100 }
1101 
1102 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1103 {
1104 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1105 }
1106 
1107 static bool is_valid_st_ops_program(struct bpf_object *obj,
1108 				    const struct bpf_program *prog)
1109 {
1110 	int i;
1111 
1112 	for (i = 0; i < obj->nr_programs; i++) {
1113 		if (&obj->programs[i] == prog)
1114 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1115 	}
1116 
1117 	return false;
1118 }
1119 
1120 /* For each struct_ops program P, referenced from some struct_ops map M,
1121  * enable P.autoload if there are Ms for which M.autocreate is true,
1122  * disable P.autoload if for all Ms M.autocreate is false.
1123  * Don't change P.autoload for programs that are not referenced from any maps.
1124  */
1125 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1126 {
1127 	struct bpf_program *prog, *slot_prog;
1128 	struct bpf_map *map;
1129 	int i, j, k, vlen;
1130 
1131 	for (i = 0; i < obj->nr_programs; ++i) {
1132 		int should_load = false;
1133 		int use_cnt = 0;
1134 
1135 		prog = &obj->programs[i];
1136 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1137 			continue;
1138 
1139 		for (j = 0; j < obj->nr_maps; ++j) {
1140 			const struct btf_type *type;
1141 
1142 			map = &obj->maps[j];
1143 			if (!bpf_map__is_struct_ops(map))
1144 				continue;
1145 
1146 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1147 			vlen = btf_vlen(type);
1148 			for (k = 0; k < vlen; ++k) {
1149 				slot_prog = map->st_ops->progs[k];
1150 				if (prog != slot_prog)
1151 					continue;
1152 
1153 				use_cnt++;
1154 				if (map->autocreate)
1155 					should_load = true;
1156 			}
1157 		}
1158 		if (use_cnt)
1159 			prog->autoload = should_load;
1160 	}
1161 
1162 	return 0;
1163 }
1164 
1165 /* Init the map's fields that depend on kern_btf */
1166 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1167 {
1168 	const struct btf_member *member, *kern_member, *kern_data_member;
1169 	const struct btf_type *type, *kern_type, *kern_vtype;
1170 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1171 	struct bpf_object *obj = map->obj;
1172 	const struct btf *btf = obj->btf;
1173 	struct bpf_struct_ops *st_ops;
1174 	const struct btf *kern_btf;
1175 	struct module_btf *mod_btf = NULL;
1176 	void *data, *kern_data;
1177 	const char *tname;
1178 	int err;
1179 
1180 	st_ops = map->st_ops;
1181 	type = btf__type_by_id(btf, st_ops->type_id);
1182 	tname = btf__name_by_offset(btf, type->name_off);
1183 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1184 					 &kern_type, &kern_type_id,
1185 					 &kern_vtype, &kern_vtype_id,
1186 					 &kern_data_member);
1187 	if (err)
1188 		return err;
1189 
1190 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1191 
1192 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1193 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1194 
1195 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1196 	map->def.value_size = kern_vtype->size;
1197 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1198 
1199 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1200 	if (!st_ops->kern_vdata)
1201 		return -ENOMEM;
1202 
1203 	data = st_ops->data;
1204 	kern_data_off = kern_data_member->offset / 8;
1205 	kern_data = st_ops->kern_vdata + kern_data_off;
1206 
1207 	member = btf_members(type);
1208 	for (i = 0; i < btf_vlen(type); i++, member++) {
1209 		const struct btf_type *mtype, *kern_mtype;
1210 		__u32 mtype_id, kern_mtype_id;
1211 		void *mdata, *kern_mdata;
1212 		struct bpf_program *prog;
1213 		__s64 msize, kern_msize;
1214 		__u32 moff, kern_moff;
1215 		__u32 kern_member_idx;
1216 		const char *mname;
1217 
1218 		mname = btf__name_by_offset(btf, member->name_off);
1219 		moff = member->offset / 8;
1220 		mdata = data + moff;
1221 		msize = btf__resolve_size(btf, member->type);
1222 		if (msize < 0) {
1223 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1224 				map->name, mname);
1225 			return msize;
1226 		}
1227 
1228 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1229 		if (!kern_member) {
1230 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1231 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1232 					map->name, mname);
1233 				return -ENOTSUP;
1234 			}
1235 
1236 			if (st_ops->progs[i]) {
1237 				/* If we had declaratively set struct_ops callback, we need to
1238 				 * force its autoload to false, because it doesn't have
1239 				 * a chance of succeeding from POV of the current struct_ops map.
1240 				 * If this program is still referenced somewhere else, though,
1241 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1242 				 * autoload accordingly.
1243 				 */
1244 				st_ops->progs[i]->autoload = false;
1245 				st_ops->progs[i] = NULL;
1246 			}
1247 
1248 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1249 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1250 				map->name, mname);
1251 			continue;
1252 		}
1253 
1254 		kern_member_idx = kern_member - btf_members(kern_type);
1255 		if (btf_member_bitfield_size(type, i) ||
1256 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1257 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1258 				map->name, mname);
1259 			return -ENOTSUP;
1260 		}
1261 
1262 		kern_moff = kern_member->offset / 8;
1263 		kern_mdata = kern_data + kern_moff;
1264 
1265 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1266 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1267 						    &kern_mtype_id);
1268 		if (BTF_INFO_KIND(mtype->info) !=
1269 		    BTF_INFO_KIND(kern_mtype->info)) {
1270 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1271 				map->name, mname, BTF_INFO_KIND(mtype->info),
1272 				BTF_INFO_KIND(kern_mtype->info));
1273 			return -ENOTSUP;
1274 		}
1275 
1276 		if (btf_is_ptr(mtype)) {
1277 			prog = *(void **)mdata;
1278 			/* just like for !kern_member case above, reset declaratively
1279 			 * set (at compile time) program's autload to false,
1280 			 * if user replaced it with another program or NULL
1281 			 */
1282 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1283 				st_ops->progs[i]->autoload = false;
1284 
1285 			/* Update the value from the shadow type */
1286 			st_ops->progs[i] = prog;
1287 			if (!prog)
1288 				continue;
1289 
1290 			if (!is_valid_st_ops_program(obj, prog)) {
1291 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1292 					map->name, mname);
1293 				return -ENOTSUP;
1294 			}
1295 
1296 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1297 							    kern_mtype->type,
1298 							    &kern_mtype_id);
1299 
1300 			/* mtype->type must be a func_proto which was
1301 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1302 			 * so only check kern_mtype for func_proto here.
1303 			 */
1304 			if (!btf_is_func_proto(kern_mtype)) {
1305 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1306 					map->name, mname);
1307 				return -ENOTSUP;
1308 			}
1309 
1310 			if (mod_btf)
1311 				prog->attach_btf_obj_fd = mod_btf->fd;
1312 
1313 			/* if we haven't yet processed this BPF program, record proper
1314 			 * attach_btf_id and member_idx
1315 			 */
1316 			if (!prog->attach_btf_id) {
1317 				prog->attach_btf_id = kern_type_id;
1318 				prog->expected_attach_type = kern_member_idx;
1319 			}
1320 
1321 			/* struct_ops BPF prog can be re-used between multiple
1322 			 * .struct_ops & .struct_ops.link as long as it's the
1323 			 * same struct_ops struct definition and the same
1324 			 * function pointer field
1325 			 */
1326 			if (prog->attach_btf_id != kern_type_id) {
1327 				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: attach_btf_id %u != kern_type_id %u\n",
1328 					map->name, mname, prog->name, prog->sec_name, prog->type,
1329 					prog->attach_btf_id, kern_type_id);
1330 				return -EINVAL;
1331 			}
1332 			if (prog->expected_attach_type != kern_member_idx) {
1333 				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: expected_attach_type %u != kern_member_idx %u\n",
1334 					map->name, mname, prog->name, prog->sec_name, prog->type,
1335 					prog->expected_attach_type, kern_member_idx);
1336 				return -EINVAL;
1337 			}
1338 
1339 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1340 
1341 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1342 				 map->name, mname, prog->name, moff,
1343 				 kern_moff);
1344 
1345 			continue;
1346 		}
1347 
1348 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1349 		if (kern_msize < 0 || msize != kern_msize) {
1350 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1351 				map->name, mname, (ssize_t)msize,
1352 				(ssize_t)kern_msize);
1353 			return -ENOTSUP;
1354 		}
1355 
1356 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1357 			 map->name, mname, (unsigned int)msize,
1358 			 moff, kern_moff);
1359 		memcpy(kern_mdata, mdata, msize);
1360 	}
1361 
1362 	return 0;
1363 }
1364 
1365 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1366 {
1367 	struct bpf_map *map;
1368 	size_t i;
1369 	int err;
1370 
1371 	for (i = 0; i < obj->nr_maps; i++) {
1372 		map = &obj->maps[i];
1373 
1374 		if (!bpf_map__is_struct_ops(map))
1375 			continue;
1376 
1377 		if (!map->autocreate)
1378 			continue;
1379 
1380 		err = bpf_map__init_kern_struct_ops(map);
1381 		if (err)
1382 			return err;
1383 	}
1384 
1385 	return 0;
1386 }
1387 
1388 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1389 				int shndx, Elf_Data *data)
1390 {
1391 	const struct btf_type *type, *datasec;
1392 	const struct btf_var_secinfo *vsi;
1393 	struct bpf_struct_ops *st_ops;
1394 	const char *tname, *var_name;
1395 	__s32 type_id, datasec_id;
1396 	const struct btf *btf;
1397 	struct bpf_map *map;
1398 	__u32 i;
1399 
1400 	if (shndx == -1)
1401 		return 0;
1402 
1403 	btf = obj->btf;
1404 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1405 					    BTF_KIND_DATASEC);
1406 	if (datasec_id < 0) {
1407 		pr_warn("struct_ops init: DATASEC %s not found\n",
1408 			sec_name);
1409 		return -EINVAL;
1410 	}
1411 
1412 	datasec = btf__type_by_id(btf, datasec_id);
1413 	vsi = btf_var_secinfos(datasec);
1414 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1415 		type = btf__type_by_id(obj->btf, vsi->type);
1416 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1417 
1418 		type_id = btf__resolve_type(obj->btf, vsi->type);
1419 		if (type_id < 0) {
1420 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1421 				vsi->type, sec_name);
1422 			return -EINVAL;
1423 		}
1424 
1425 		type = btf__type_by_id(obj->btf, type_id);
1426 		tname = btf__name_by_offset(obj->btf, type->name_off);
1427 		if (!tname[0]) {
1428 			pr_warn("struct_ops init: anonymous type is not supported\n");
1429 			return -ENOTSUP;
1430 		}
1431 		if (!btf_is_struct(type)) {
1432 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1433 			return -EINVAL;
1434 		}
1435 
1436 		map = bpf_object__add_map(obj);
1437 		if (IS_ERR(map))
1438 			return PTR_ERR(map);
1439 
1440 		map->sec_idx = shndx;
1441 		map->sec_offset = vsi->offset;
1442 		map->name = strdup(var_name);
1443 		if (!map->name)
1444 			return -ENOMEM;
1445 		map->btf_value_type_id = type_id;
1446 
1447 		/* Follow same convention as for programs autoload:
1448 		 * SEC("?.struct_ops") means map is not created by default.
1449 		 */
1450 		if (sec_name[0] == '?') {
1451 			map->autocreate = false;
1452 			/* from now on forget there was ? in section name */
1453 			sec_name++;
1454 		}
1455 
1456 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1457 		map->def.key_size = sizeof(int);
1458 		map->def.value_size = type->size;
1459 		map->def.max_entries = 1;
1460 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1461 		map->autoattach = true;
1462 
1463 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1464 		if (!map->st_ops)
1465 			return -ENOMEM;
1466 		st_ops = map->st_ops;
1467 		st_ops->data = malloc(type->size);
1468 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1469 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1470 					       sizeof(*st_ops->kern_func_off));
1471 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1472 			return -ENOMEM;
1473 
1474 		if (vsi->offset + type->size > data->d_size) {
1475 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1476 				var_name, sec_name);
1477 			return -EINVAL;
1478 		}
1479 
1480 		memcpy(st_ops->data,
1481 		       data->d_buf + vsi->offset,
1482 		       type->size);
1483 		st_ops->type_id = type_id;
1484 
1485 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1486 			 tname, type_id, var_name, vsi->offset);
1487 	}
1488 
1489 	return 0;
1490 }
1491 
1492 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1493 {
1494 	const char *sec_name;
1495 	int sec_idx, err;
1496 
1497 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1498 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1499 
1500 		if (desc->sec_type != SEC_ST_OPS)
1501 			continue;
1502 
1503 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1504 		if (!sec_name)
1505 			return -LIBBPF_ERRNO__FORMAT;
1506 
1507 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1508 		if (err)
1509 			return err;
1510 	}
1511 
1512 	return 0;
1513 }
1514 
1515 static struct bpf_object *bpf_object__new(const char *path,
1516 					  const void *obj_buf,
1517 					  size_t obj_buf_sz,
1518 					  const char *obj_name)
1519 {
1520 	struct bpf_object *obj;
1521 	char *end;
1522 
1523 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1524 	if (!obj) {
1525 		pr_warn("alloc memory failed for %s\n", path);
1526 		return ERR_PTR(-ENOMEM);
1527 	}
1528 
1529 	strcpy(obj->path, path);
1530 	if (obj_name) {
1531 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1532 	} else {
1533 		/* Using basename() GNU version which doesn't modify arg. */
1534 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1535 		end = strchr(obj->name, '.');
1536 		if (end)
1537 			*end = 0;
1538 	}
1539 
1540 	obj->efile.fd = -1;
1541 	/*
1542 	 * Caller of this function should also call
1543 	 * bpf_object__elf_finish() after data collection to return
1544 	 * obj_buf to user. If not, we should duplicate the buffer to
1545 	 * avoid user freeing them before elf finish.
1546 	 */
1547 	obj->efile.obj_buf = obj_buf;
1548 	obj->efile.obj_buf_sz = obj_buf_sz;
1549 	obj->efile.btf_maps_shndx = -1;
1550 	obj->kconfig_map_idx = -1;
1551 	obj->arena_map_idx = -1;
1552 
1553 	obj->kern_version = get_kernel_version();
1554 	obj->state  = OBJ_OPEN;
1555 
1556 	return obj;
1557 }
1558 
1559 static void bpf_object__elf_finish(struct bpf_object *obj)
1560 {
1561 	if (!obj->efile.elf)
1562 		return;
1563 
1564 	elf_end(obj->efile.elf);
1565 	obj->efile.elf = NULL;
1566 	obj->efile.ehdr = NULL;
1567 	obj->efile.symbols = NULL;
1568 	obj->efile.arena_data = NULL;
1569 
1570 	zfree(&obj->efile.secs);
1571 	obj->efile.sec_cnt = 0;
1572 	zclose(obj->efile.fd);
1573 	obj->efile.obj_buf = NULL;
1574 	obj->efile.obj_buf_sz = 0;
1575 }
1576 
1577 static int bpf_object__elf_init(struct bpf_object *obj)
1578 {
1579 	Elf64_Ehdr *ehdr;
1580 	int err = 0;
1581 	Elf *elf;
1582 
1583 	if (obj->efile.elf) {
1584 		pr_warn("elf: init internal error\n");
1585 		return -LIBBPF_ERRNO__LIBELF;
1586 	}
1587 
1588 	if (obj->efile.obj_buf_sz > 0) {
1589 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1590 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1591 	} else {
1592 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1593 		if (obj->efile.fd < 0) {
1594 			err = -errno;
1595 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1596 			return err;
1597 		}
1598 
1599 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1600 	}
1601 
1602 	if (!elf) {
1603 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1604 		err = -LIBBPF_ERRNO__LIBELF;
1605 		goto errout;
1606 	}
1607 
1608 	obj->efile.elf = elf;
1609 
1610 	if (elf_kind(elf) != ELF_K_ELF) {
1611 		err = -LIBBPF_ERRNO__FORMAT;
1612 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1613 		goto errout;
1614 	}
1615 
1616 	if (gelf_getclass(elf) != ELFCLASS64) {
1617 		err = -LIBBPF_ERRNO__FORMAT;
1618 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1619 		goto errout;
1620 	}
1621 
1622 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1623 	if (!obj->efile.ehdr) {
1624 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1625 		err = -LIBBPF_ERRNO__FORMAT;
1626 		goto errout;
1627 	}
1628 
1629 	/* Validate ELF object endianness... */
1630 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1631 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1632 		err = -LIBBPF_ERRNO__ENDIAN;
1633 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1634 		goto errout;
1635 	}
1636 	/* and save after bpf_object_open() frees ELF data */
1637 	obj->byteorder = ehdr->e_ident[EI_DATA];
1638 
1639 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1640 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1641 			obj->path, elf_errmsg(-1));
1642 		err = -LIBBPF_ERRNO__FORMAT;
1643 		goto errout;
1644 	}
1645 
1646 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1647 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1648 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1649 			obj->path, elf_errmsg(-1));
1650 		err = -LIBBPF_ERRNO__FORMAT;
1651 		goto errout;
1652 	}
1653 
1654 	/* Old LLVM set e_machine to EM_NONE */
1655 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1656 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1657 		err = -LIBBPF_ERRNO__FORMAT;
1658 		goto errout;
1659 	}
1660 
1661 	return 0;
1662 errout:
1663 	bpf_object__elf_finish(obj);
1664 	return err;
1665 }
1666 
1667 static bool is_native_endianness(struct bpf_object *obj)
1668 {
1669 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1670 	return obj->byteorder == ELFDATA2LSB;
1671 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1672 	return obj->byteorder == ELFDATA2MSB;
1673 #else
1674 # error "Unrecognized __BYTE_ORDER__"
1675 #endif
1676 }
1677 
1678 static int
1679 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1680 {
1681 	if (!data) {
1682 		pr_warn("invalid license section in %s\n", obj->path);
1683 		return -LIBBPF_ERRNO__FORMAT;
1684 	}
1685 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1686 	 * go over allowed ELF data section buffer
1687 	 */
1688 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1689 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1690 	return 0;
1691 }
1692 
1693 static int
1694 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1695 {
1696 	__u32 kver;
1697 
1698 	if (!data || size != sizeof(kver)) {
1699 		pr_warn("invalid kver section in %s\n", obj->path);
1700 		return -LIBBPF_ERRNO__FORMAT;
1701 	}
1702 	memcpy(&kver, data, sizeof(kver));
1703 	obj->kern_version = kver;
1704 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1705 	return 0;
1706 }
1707 
1708 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1709 {
1710 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1711 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1712 		return true;
1713 	return false;
1714 }
1715 
1716 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1717 {
1718 	Elf_Data *data;
1719 	Elf_Scn *scn;
1720 
1721 	if (!name)
1722 		return -EINVAL;
1723 
1724 	scn = elf_sec_by_name(obj, name);
1725 	data = elf_sec_data(obj, scn);
1726 	if (data) {
1727 		*size = data->d_size;
1728 		return 0; /* found it */
1729 	}
1730 
1731 	return -ENOENT;
1732 }
1733 
1734 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1735 {
1736 	Elf_Data *symbols = obj->efile.symbols;
1737 	const char *sname;
1738 	size_t si;
1739 
1740 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1741 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1742 
1743 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1744 			continue;
1745 
1746 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1747 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1748 			continue;
1749 
1750 		sname = elf_sym_str(obj, sym->st_name);
1751 		if (!sname) {
1752 			pr_warn("failed to get sym name string for var %s\n", name);
1753 			return ERR_PTR(-EIO);
1754 		}
1755 		if (strcmp(name, sname) == 0)
1756 			return sym;
1757 	}
1758 
1759 	return ERR_PTR(-ENOENT);
1760 }
1761 
1762 #ifndef MFD_CLOEXEC
1763 #define MFD_CLOEXEC 0x0001U
1764 #endif
1765 #ifndef MFD_NOEXEC_SEAL
1766 #define MFD_NOEXEC_SEAL 0x0008U
1767 #endif
1768 
1769 static int create_placeholder_fd(void)
1770 {
1771 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1772 	const char *name = "libbpf-placeholder-fd";
1773 	int fd;
1774 
1775 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1776 	if (fd >= 0)
1777 		return fd;
1778 	else if (errno != EINVAL)
1779 		return -errno;
1780 
1781 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1782 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1783 	if (fd < 0)
1784 		return -errno;
1785 	return fd;
1786 }
1787 
1788 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1789 {
1790 	struct bpf_map *map;
1791 	int err;
1792 
1793 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1794 				sizeof(*obj->maps), obj->nr_maps + 1);
1795 	if (err)
1796 		return ERR_PTR(err);
1797 
1798 	map = &obj->maps[obj->nr_maps++];
1799 	map->obj = obj;
1800 	/* Preallocate map FD without actually creating BPF map just yet.
1801 	 * These map FD "placeholders" will be reused later without changing
1802 	 * FD value when map is actually created in the kernel.
1803 	 *
1804 	 * This is useful to be able to perform BPF program relocations
1805 	 * without having to create BPF maps before that step. This allows us
1806 	 * to finalize and load BTF very late in BPF object's loading phase,
1807 	 * right before BPF maps have to be created and BPF programs have to
1808 	 * be loaded. By having these map FD placeholders we can perform all
1809 	 * the sanitizations, relocations, and any other adjustments before we
1810 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1811 	 */
1812 	map->fd = create_placeholder_fd();
1813 	if (map->fd < 0)
1814 		return ERR_PTR(map->fd);
1815 	map->inner_map_fd = -1;
1816 	map->autocreate = true;
1817 
1818 	return map;
1819 }
1820 
1821 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1822 {
1823 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1824 	size_t map_sz;
1825 
1826 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1827 	map_sz = roundup(map_sz, page_sz);
1828 	return map_sz;
1829 }
1830 
1831 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1832 {
1833 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1834 
1835 	switch (map->def.type) {
1836 	case BPF_MAP_TYPE_ARRAY:
1837 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1838 	case BPF_MAP_TYPE_ARENA:
1839 		return page_sz * map->def.max_entries;
1840 	default:
1841 		return 0; /* not supported */
1842 	}
1843 }
1844 
1845 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1846 {
1847 	void *mmaped;
1848 
1849 	if (!map->mmaped)
1850 		return -EINVAL;
1851 
1852 	if (old_sz == new_sz)
1853 		return 0;
1854 
1855 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1856 	if (mmaped == MAP_FAILED)
1857 		return -errno;
1858 
1859 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1860 	munmap(map->mmaped, old_sz);
1861 	map->mmaped = mmaped;
1862 	return 0;
1863 }
1864 
1865 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1866 {
1867 	char map_name[BPF_OBJ_NAME_LEN], *p;
1868 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1869 
1870 	/* This is one of the more confusing parts of libbpf for various
1871 	 * reasons, some of which are historical. The original idea for naming
1872 	 * internal names was to include as much of BPF object name prefix as
1873 	 * possible, so that it can be distinguished from similar internal
1874 	 * maps of a different BPF object.
1875 	 * As an example, let's say we have bpf_object named 'my_object_name'
1876 	 * and internal map corresponding to '.rodata' ELF section. The final
1877 	 * map name advertised to user and to the kernel will be
1878 	 * 'my_objec.rodata', taking first 8 characters of object name and
1879 	 * entire 7 characters of '.rodata'.
1880 	 * Somewhat confusingly, if internal map ELF section name is shorter
1881 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1882 	 * for the suffix, even though we only have 4 actual characters, and
1883 	 * resulting map will be called 'my_objec.bss', not even using all 15
1884 	 * characters allowed by the kernel. Oh well, at least the truncated
1885 	 * object name is somewhat consistent in this case. But if the map
1886 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1887 	 * (8 chars) and thus will be left with only first 7 characters of the
1888 	 * object name ('my_obje'). Happy guessing, user, that the final map
1889 	 * name will be "my_obje.kconfig".
1890 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1891 	 * and .data.* data sections, it's possible that ELF section name is
1892 	 * longer than allowed 15 chars, so we now need to be careful to take
1893 	 * only up to 15 first characters of ELF name, taking no BPF object
1894 	 * name characters at all. So '.rodata.abracadabra' will result in
1895 	 * '.rodata.abracad' kernel and user-visible name.
1896 	 * We need to keep this convoluted logic intact for .data, .bss and
1897 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1898 	 * maps we use their ELF names as is, not prepending bpf_object name
1899 	 * in front. We still need to truncate them to 15 characters for the
1900 	 * kernel. Full name can be recovered for such maps by using DATASEC
1901 	 * BTF type associated with such map's value type, though.
1902 	 */
1903 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1904 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1905 
1906 	/* if there are two or more dots in map name, it's a custom dot map */
1907 	if (strchr(real_name + 1, '.') != NULL)
1908 		pfx_len = 0;
1909 	else
1910 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1911 
1912 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1913 		 sfx_len, real_name);
1914 
1915 	/* sanities map name to characters allowed by kernel */
1916 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1917 		if (!isalnum(*p) && *p != '_' && *p != '.')
1918 			*p = '_';
1919 
1920 	return strdup(map_name);
1921 }
1922 
1923 static int
1924 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1925 
1926 /* Internal BPF map is mmap()'able only if at least one of corresponding
1927  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1928  * variable and it's not marked as __hidden (which turns it into, effectively,
1929  * a STATIC variable).
1930  */
1931 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1932 {
1933 	const struct btf_type *t, *vt;
1934 	struct btf_var_secinfo *vsi;
1935 	int i, n;
1936 
1937 	if (!map->btf_value_type_id)
1938 		return false;
1939 
1940 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1941 	if (!btf_is_datasec(t))
1942 		return false;
1943 
1944 	vsi = btf_var_secinfos(t);
1945 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1946 		vt = btf__type_by_id(obj->btf, vsi->type);
1947 		if (!btf_is_var(vt))
1948 			continue;
1949 
1950 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1951 			return true;
1952 	}
1953 
1954 	return false;
1955 }
1956 
1957 static int
1958 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1959 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1960 {
1961 	struct bpf_map_def *def;
1962 	struct bpf_map *map;
1963 	size_t mmap_sz;
1964 	int err;
1965 
1966 	map = bpf_object__add_map(obj);
1967 	if (IS_ERR(map))
1968 		return PTR_ERR(map);
1969 
1970 	map->libbpf_type = type;
1971 	map->sec_idx = sec_idx;
1972 	map->sec_offset = 0;
1973 	map->real_name = strdup(real_name);
1974 	map->name = internal_map_name(obj, real_name);
1975 	if (!map->real_name || !map->name) {
1976 		zfree(&map->real_name);
1977 		zfree(&map->name);
1978 		return -ENOMEM;
1979 	}
1980 
1981 	def = &map->def;
1982 	def->type = BPF_MAP_TYPE_ARRAY;
1983 	def->key_size = sizeof(int);
1984 	def->value_size = data_sz;
1985 	def->max_entries = 1;
1986 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1987 		? BPF_F_RDONLY_PROG : 0;
1988 
1989 	/* failures are fine because of maps like .rodata.str1.1 */
1990 	(void) map_fill_btf_type_info(obj, map);
1991 
1992 	if (map_is_mmapable(obj, map))
1993 		def->map_flags |= BPF_F_MMAPABLE;
1994 
1995 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1996 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1997 
1998 	mmap_sz = bpf_map_mmap_sz(map);
1999 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2000 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2001 	if (map->mmaped == MAP_FAILED) {
2002 		err = -errno;
2003 		map->mmaped = NULL;
2004 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2005 		zfree(&map->real_name);
2006 		zfree(&map->name);
2007 		return err;
2008 	}
2009 
2010 	if (data)
2011 		memcpy(map->mmaped, data, data_sz);
2012 
2013 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2014 	return 0;
2015 }
2016 
2017 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2018 {
2019 	struct elf_sec_desc *sec_desc;
2020 	const char *sec_name;
2021 	int err = 0, sec_idx;
2022 
2023 	/*
2024 	 * Populate obj->maps with libbpf internal maps.
2025 	 */
2026 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2027 		sec_desc = &obj->efile.secs[sec_idx];
2028 
2029 		/* Skip recognized sections with size 0. */
2030 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2031 			continue;
2032 
2033 		switch (sec_desc->sec_type) {
2034 		case SEC_DATA:
2035 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2036 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2037 							    sec_name, sec_idx,
2038 							    sec_desc->data->d_buf,
2039 							    sec_desc->data->d_size);
2040 			break;
2041 		case SEC_RODATA:
2042 			obj->has_rodata = true;
2043 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2044 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2045 							    sec_name, sec_idx,
2046 							    sec_desc->data->d_buf,
2047 							    sec_desc->data->d_size);
2048 			break;
2049 		case SEC_BSS:
2050 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2051 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2052 							    sec_name, sec_idx,
2053 							    NULL,
2054 							    sec_desc->data->d_size);
2055 			break;
2056 		default:
2057 			/* skip */
2058 			break;
2059 		}
2060 		if (err)
2061 			return err;
2062 	}
2063 	return 0;
2064 }
2065 
2066 
2067 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2068 					       const void *name)
2069 {
2070 	int i;
2071 
2072 	for (i = 0; i < obj->nr_extern; i++) {
2073 		if (strcmp(obj->externs[i].name, name) == 0)
2074 			return &obj->externs[i];
2075 	}
2076 	return NULL;
2077 }
2078 
2079 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2080 							const void *name, int len)
2081 {
2082 	const char *ext_name;
2083 	int i;
2084 
2085 	for (i = 0; i < obj->nr_extern; i++) {
2086 		ext_name = obj->externs[i].name;
2087 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2088 			return &obj->externs[i];
2089 	}
2090 	return NULL;
2091 }
2092 
2093 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2094 			      char value)
2095 {
2096 	switch (ext->kcfg.type) {
2097 	case KCFG_BOOL:
2098 		if (value == 'm') {
2099 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2100 				ext->name, value);
2101 			return -EINVAL;
2102 		}
2103 		*(bool *)ext_val = value == 'y' ? true : false;
2104 		break;
2105 	case KCFG_TRISTATE:
2106 		if (value == 'y')
2107 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2108 		else if (value == 'm')
2109 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2110 		else /* value == 'n' */
2111 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2112 		break;
2113 	case KCFG_CHAR:
2114 		*(char *)ext_val = value;
2115 		break;
2116 	case KCFG_UNKNOWN:
2117 	case KCFG_INT:
2118 	case KCFG_CHAR_ARR:
2119 	default:
2120 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2121 			ext->name, value);
2122 		return -EINVAL;
2123 	}
2124 	ext->is_set = true;
2125 	return 0;
2126 }
2127 
2128 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2129 			      const char *value)
2130 {
2131 	size_t len;
2132 
2133 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2134 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2135 			ext->name, value);
2136 		return -EINVAL;
2137 	}
2138 
2139 	len = strlen(value);
2140 	if (len < 2 || value[len - 1] != '"') {
2141 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2142 			ext->name, value);
2143 		return -EINVAL;
2144 	}
2145 
2146 	/* strip quotes */
2147 	len -= 2;
2148 	if (len >= ext->kcfg.sz) {
2149 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2150 			ext->name, value, len, ext->kcfg.sz - 1);
2151 		len = ext->kcfg.sz - 1;
2152 	}
2153 	memcpy(ext_val, value + 1, len);
2154 	ext_val[len] = '\0';
2155 	ext->is_set = true;
2156 	return 0;
2157 }
2158 
2159 static int parse_u64(const char *value, __u64 *res)
2160 {
2161 	char *value_end;
2162 	int err;
2163 
2164 	errno = 0;
2165 	*res = strtoull(value, &value_end, 0);
2166 	if (errno) {
2167 		err = -errno;
2168 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2169 		return err;
2170 	}
2171 	if (*value_end) {
2172 		pr_warn("failed to parse '%s' as integer completely\n", value);
2173 		return -EINVAL;
2174 	}
2175 	return 0;
2176 }
2177 
2178 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2179 {
2180 	int bit_sz = ext->kcfg.sz * 8;
2181 
2182 	if (ext->kcfg.sz == 8)
2183 		return true;
2184 
2185 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2186 	 * bytes size without any loss of information. If the target integer
2187 	 * is signed, we rely on the following limits of integer type of
2188 	 * Y bits and subsequent transformation:
2189 	 *
2190 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2191 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2192 	 *            0 <= X + 2^(Y-1) <  2^Y
2193 	 *
2194 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2195 	 *  zero.
2196 	 */
2197 	if (ext->kcfg.is_signed)
2198 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2199 	else
2200 		return (v >> bit_sz) == 0;
2201 }
2202 
2203 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2204 			      __u64 value)
2205 {
2206 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2207 	    ext->kcfg.type != KCFG_BOOL) {
2208 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2209 			ext->name, (unsigned long long)value);
2210 		return -EINVAL;
2211 	}
2212 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2213 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2214 			ext->name, (unsigned long long)value);
2215 		return -EINVAL;
2216 
2217 	}
2218 	if (!is_kcfg_value_in_range(ext, value)) {
2219 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2220 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2221 		return -ERANGE;
2222 	}
2223 	switch (ext->kcfg.sz) {
2224 	case 1:
2225 		*(__u8 *)ext_val = value;
2226 		break;
2227 	case 2:
2228 		*(__u16 *)ext_val = value;
2229 		break;
2230 	case 4:
2231 		*(__u32 *)ext_val = value;
2232 		break;
2233 	case 8:
2234 		*(__u64 *)ext_val = value;
2235 		break;
2236 	default:
2237 		return -EINVAL;
2238 	}
2239 	ext->is_set = true;
2240 	return 0;
2241 }
2242 
2243 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2244 					    char *buf, void *data)
2245 {
2246 	struct extern_desc *ext;
2247 	char *sep, *value;
2248 	int len, err = 0;
2249 	void *ext_val;
2250 	__u64 num;
2251 
2252 	if (!str_has_pfx(buf, "CONFIG_"))
2253 		return 0;
2254 
2255 	sep = strchr(buf, '=');
2256 	if (!sep) {
2257 		pr_warn("failed to parse '%s': no separator\n", buf);
2258 		return -EINVAL;
2259 	}
2260 
2261 	/* Trim ending '\n' */
2262 	len = strlen(buf);
2263 	if (buf[len - 1] == '\n')
2264 		buf[len - 1] = '\0';
2265 	/* Split on '=' and ensure that a value is present. */
2266 	*sep = '\0';
2267 	if (!sep[1]) {
2268 		*sep = '=';
2269 		pr_warn("failed to parse '%s': no value\n", buf);
2270 		return -EINVAL;
2271 	}
2272 
2273 	ext = find_extern_by_name(obj, buf);
2274 	if (!ext || ext->is_set)
2275 		return 0;
2276 
2277 	ext_val = data + ext->kcfg.data_off;
2278 	value = sep + 1;
2279 
2280 	switch (*value) {
2281 	case 'y': case 'n': case 'm':
2282 		err = set_kcfg_value_tri(ext, ext_val, *value);
2283 		break;
2284 	case '"':
2285 		err = set_kcfg_value_str(ext, ext_val, value);
2286 		break;
2287 	default:
2288 		/* assume integer */
2289 		err = parse_u64(value, &num);
2290 		if (err) {
2291 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2292 			return err;
2293 		}
2294 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2295 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2296 			return -EINVAL;
2297 		}
2298 		err = set_kcfg_value_num(ext, ext_val, num);
2299 		break;
2300 	}
2301 	if (err)
2302 		return err;
2303 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2304 	return 0;
2305 }
2306 
2307 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2308 {
2309 	char buf[PATH_MAX];
2310 	struct utsname uts;
2311 	int len, err = 0;
2312 	gzFile file;
2313 
2314 	uname(&uts);
2315 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2316 	if (len < 0)
2317 		return -EINVAL;
2318 	else if (len >= PATH_MAX)
2319 		return -ENAMETOOLONG;
2320 
2321 	/* gzopen also accepts uncompressed files. */
2322 	file = gzopen(buf, "re");
2323 	if (!file)
2324 		file = gzopen("/proc/config.gz", "re");
2325 
2326 	if (!file) {
2327 		pr_warn("failed to open system Kconfig\n");
2328 		return -ENOENT;
2329 	}
2330 
2331 	while (gzgets(file, buf, sizeof(buf))) {
2332 		err = bpf_object__process_kconfig_line(obj, buf, data);
2333 		if (err) {
2334 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2335 				buf, errstr(err));
2336 			goto out;
2337 		}
2338 	}
2339 
2340 out:
2341 	gzclose(file);
2342 	return err;
2343 }
2344 
2345 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2346 					const char *config, void *data)
2347 {
2348 	char buf[PATH_MAX];
2349 	int err = 0;
2350 	FILE *file;
2351 
2352 	file = fmemopen((void *)config, strlen(config), "r");
2353 	if (!file) {
2354 		err = -errno;
2355 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2356 		return err;
2357 	}
2358 
2359 	while (fgets(buf, sizeof(buf), file)) {
2360 		err = bpf_object__process_kconfig_line(obj, buf, data);
2361 		if (err) {
2362 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2363 				buf, errstr(err));
2364 			break;
2365 		}
2366 	}
2367 
2368 	fclose(file);
2369 	return err;
2370 }
2371 
2372 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2373 {
2374 	struct extern_desc *last_ext = NULL, *ext;
2375 	size_t map_sz;
2376 	int i, err;
2377 
2378 	for (i = 0; i < obj->nr_extern; i++) {
2379 		ext = &obj->externs[i];
2380 		if (ext->type == EXT_KCFG)
2381 			last_ext = ext;
2382 	}
2383 
2384 	if (!last_ext)
2385 		return 0;
2386 
2387 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2388 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2389 					    ".kconfig", obj->efile.symbols_shndx,
2390 					    NULL, map_sz);
2391 	if (err)
2392 		return err;
2393 
2394 	obj->kconfig_map_idx = obj->nr_maps - 1;
2395 
2396 	return 0;
2397 }
2398 
2399 const struct btf_type *
2400 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2401 {
2402 	const struct btf_type *t = btf__type_by_id(btf, id);
2403 
2404 	if (res_id)
2405 		*res_id = id;
2406 
2407 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2408 		if (res_id)
2409 			*res_id = t->type;
2410 		t = btf__type_by_id(btf, t->type);
2411 	}
2412 
2413 	return t;
2414 }
2415 
2416 static const struct btf_type *
2417 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2418 {
2419 	const struct btf_type *t;
2420 
2421 	t = skip_mods_and_typedefs(btf, id, NULL);
2422 	if (!btf_is_ptr(t))
2423 		return NULL;
2424 
2425 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2426 
2427 	return btf_is_func_proto(t) ? t : NULL;
2428 }
2429 
2430 static const char *__btf_kind_str(__u16 kind)
2431 {
2432 	switch (kind) {
2433 	case BTF_KIND_UNKN: return "void";
2434 	case BTF_KIND_INT: return "int";
2435 	case BTF_KIND_PTR: return "ptr";
2436 	case BTF_KIND_ARRAY: return "array";
2437 	case BTF_KIND_STRUCT: return "struct";
2438 	case BTF_KIND_UNION: return "union";
2439 	case BTF_KIND_ENUM: return "enum";
2440 	case BTF_KIND_FWD: return "fwd";
2441 	case BTF_KIND_TYPEDEF: return "typedef";
2442 	case BTF_KIND_VOLATILE: return "volatile";
2443 	case BTF_KIND_CONST: return "const";
2444 	case BTF_KIND_RESTRICT: return "restrict";
2445 	case BTF_KIND_FUNC: return "func";
2446 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2447 	case BTF_KIND_VAR: return "var";
2448 	case BTF_KIND_DATASEC: return "datasec";
2449 	case BTF_KIND_FLOAT: return "float";
2450 	case BTF_KIND_DECL_TAG: return "decl_tag";
2451 	case BTF_KIND_TYPE_TAG: return "type_tag";
2452 	case BTF_KIND_ENUM64: return "enum64";
2453 	default: return "unknown";
2454 	}
2455 }
2456 
2457 const char *btf_kind_str(const struct btf_type *t)
2458 {
2459 	return __btf_kind_str(btf_kind(t));
2460 }
2461 
2462 /*
2463  * Fetch integer attribute of BTF map definition. Such attributes are
2464  * represented using a pointer to an array, in which dimensionality of array
2465  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2466  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2467  * type definition, while using only sizeof(void *) space in ELF data section.
2468  */
2469 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2470 			      const struct btf_member *m, __u32 *res)
2471 {
2472 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2473 	const char *name = btf__name_by_offset(btf, m->name_off);
2474 	const struct btf_array *arr_info;
2475 	const struct btf_type *arr_t;
2476 
2477 	if (!btf_is_ptr(t)) {
2478 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2479 			map_name, name, btf_kind_str(t));
2480 		return false;
2481 	}
2482 
2483 	arr_t = btf__type_by_id(btf, t->type);
2484 	if (!arr_t) {
2485 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2486 			map_name, name, t->type);
2487 		return false;
2488 	}
2489 	if (!btf_is_array(arr_t)) {
2490 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2491 			map_name, name, btf_kind_str(arr_t));
2492 		return false;
2493 	}
2494 	arr_info = btf_array(arr_t);
2495 	*res = arr_info->nelems;
2496 	return true;
2497 }
2498 
2499 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2500 			       const struct btf_member *m, __u64 *res)
2501 {
2502 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2503 	const char *name = btf__name_by_offset(btf, m->name_off);
2504 
2505 	if (btf_is_ptr(t)) {
2506 		__u32 res32;
2507 		bool ret;
2508 
2509 		ret = get_map_field_int(map_name, btf, m, &res32);
2510 		if (ret)
2511 			*res = (__u64)res32;
2512 		return ret;
2513 	}
2514 
2515 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2516 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2517 			map_name, name, btf_kind_str(t));
2518 		return false;
2519 	}
2520 
2521 	if (btf_vlen(t) != 1) {
2522 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2523 			map_name, name);
2524 		return false;
2525 	}
2526 
2527 	if (btf_is_enum(t)) {
2528 		const struct btf_enum *e = btf_enum(t);
2529 
2530 		*res = e->val;
2531 	} else {
2532 		const struct btf_enum64 *e = btf_enum64(t);
2533 
2534 		*res = btf_enum64_value(e);
2535 	}
2536 	return true;
2537 }
2538 
2539 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2540 {
2541 	int len;
2542 
2543 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2544 	if (len < 0)
2545 		return -EINVAL;
2546 	if (len >= buf_sz)
2547 		return -ENAMETOOLONG;
2548 
2549 	return 0;
2550 }
2551 
2552 static int build_map_pin_path(struct bpf_map *map, const char *path)
2553 {
2554 	char buf[PATH_MAX];
2555 	int err;
2556 
2557 	if (!path)
2558 		path = BPF_FS_DEFAULT_PATH;
2559 
2560 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2561 	if (err)
2562 		return err;
2563 
2564 	return bpf_map__set_pin_path(map, buf);
2565 }
2566 
2567 /* should match definition in bpf_helpers.h */
2568 enum libbpf_pin_type {
2569 	LIBBPF_PIN_NONE,
2570 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2571 	LIBBPF_PIN_BY_NAME,
2572 };
2573 
2574 int parse_btf_map_def(const char *map_name, struct btf *btf,
2575 		      const struct btf_type *def_t, bool strict,
2576 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2577 {
2578 	const struct btf_type *t;
2579 	const struct btf_member *m;
2580 	bool is_inner = inner_def == NULL;
2581 	int vlen, i;
2582 
2583 	vlen = btf_vlen(def_t);
2584 	m = btf_members(def_t);
2585 	for (i = 0; i < vlen; i++, m++) {
2586 		const char *name = btf__name_by_offset(btf, m->name_off);
2587 
2588 		if (!name) {
2589 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2590 			return -EINVAL;
2591 		}
2592 		if (strcmp(name, "type") == 0) {
2593 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2594 				return -EINVAL;
2595 			map_def->parts |= MAP_DEF_MAP_TYPE;
2596 		} else if (strcmp(name, "max_entries") == 0) {
2597 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2598 				return -EINVAL;
2599 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2600 		} else if (strcmp(name, "map_flags") == 0) {
2601 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2602 				return -EINVAL;
2603 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2604 		} else if (strcmp(name, "numa_node") == 0) {
2605 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2606 				return -EINVAL;
2607 			map_def->parts |= MAP_DEF_NUMA_NODE;
2608 		} else if (strcmp(name, "key_size") == 0) {
2609 			__u32 sz;
2610 
2611 			if (!get_map_field_int(map_name, btf, m, &sz))
2612 				return -EINVAL;
2613 			if (map_def->key_size && map_def->key_size != sz) {
2614 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2615 					map_name, map_def->key_size, sz);
2616 				return -EINVAL;
2617 			}
2618 			map_def->key_size = sz;
2619 			map_def->parts |= MAP_DEF_KEY_SIZE;
2620 		} else if (strcmp(name, "key") == 0) {
2621 			__s64 sz;
2622 
2623 			t = btf__type_by_id(btf, m->type);
2624 			if (!t) {
2625 				pr_warn("map '%s': key type [%d] not found.\n",
2626 					map_name, m->type);
2627 				return -EINVAL;
2628 			}
2629 			if (!btf_is_ptr(t)) {
2630 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2631 					map_name, btf_kind_str(t));
2632 				return -EINVAL;
2633 			}
2634 			sz = btf__resolve_size(btf, t->type);
2635 			if (sz < 0) {
2636 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2637 					map_name, t->type, (ssize_t)sz);
2638 				return sz;
2639 			}
2640 			if (map_def->key_size && map_def->key_size != sz) {
2641 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2642 					map_name, map_def->key_size, (ssize_t)sz);
2643 				return -EINVAL;
2644 			}
2645 			map_def->key_size = sz;
2646 			map_def->key_type_id = t->type;
2647 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2648 		} else if (strcmp(name, "value_size") == 0) {
2649 			__u32 sz;
2650 
2651 			if (!get_map_field_int(map_name, btf, m, &sz))
2652 				return -EINVAL;
2653 			if (map_def->value_size && map_def->value_size != sz) {
2654 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2655 					map_name, map_def->value_size, sz);
2656 				return -EINVAL;
2657 			}
2658 			map_def->value_size = sz;
2659 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2660 		} else if (strcmp(name, "value") == 0) {
2661 			__s64 sz;
2662 
2663 			t = btf__type_by_id(btf, m->type);
2664 			if (!t) {
2665 				pr_warn("map '%s': value type [%d] not found.\n",
2666 					map_name, m->type);
2667 				return -EINVAL;
2668 			}
2669 			if (!btf_is_ptr(t)) {
2670 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2671 					map_name, btf_kind_str(t));
2672 				return -EINVAL;
2673 			}
2674 			sz = btf__resolve_size(btf, t->type);
2675 			if (sz < 0) {
2676 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2677 					map_name, t->type, (ssize_t)sz);
2678 				return sz;
2679 			}
2680 			if (map_def->value_size && map_def->value_size != sz) {
2681 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2682 					map_name, map_def->value_size, (ssize_t)sz);
2683 				return -EINVAL;
2684 			}
2685 			map_def->value_size = sz;
2686 			map_def->value_type_id = t->type;
2687 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2688 		}
2689 		else if (strcmp(name, "values") == 0) {
2690 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2691 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2692 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2693 			char inner_map_name[128];
2694 			int err;
2695 
2696 			if (is_inner) {
2697 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2698 					map_name);
2699 				return -ENOTSUP;
2700 			}
2701 			if (i != vlen - 1) {
2702 				pr_warn("map '%s': '%s' member should be last.\n",
2703 					map_name, name);
2704 				return -EINVAL;
2705 			}
2706 			if (!is_map_in_map && !is_prog_array) {
2707 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2708 					map_name);
2709 				return -ENOTSUP;
2710 			}
2711 			if (map_def->value_size && map_def->value_size != 4) {
2712 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2713 					map_name, map_def->value_size);
2714 				return -EINVAL;
2715 			}
2716 			map_def->value_size = 4;
2717 			t = btf__type_by_id(btf, m->type);
2718 			if (!t) {
2719 				pr_warn("map '%s': %s type [%d] not found.\n",
2720 					map_name, desc, m->type);
2721 				return -EINVAL;
2722 			}
2723 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2724 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2725 					map_name, desc);
2726 				return -EINVAL;
2727 			}
2728 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2729 			if (!btf_is_ptr(t)) {
2730 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2731 					map_name, desc, btf_kind_str(t));
2732 				return -EINVAL;
2733 			}
2734 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2735 			if (is_prog_array) {
2736 				if (!btf_is_func_proto(t)) {
2737 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2738 						map_name, btf_kind_str(t));
2739 					return -EINVAL;
2740 				}
2741 				continue;
2742 			}
2743 			if (!btf_is_struct(t)) {
2744 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2745 					map_name, btf_kind_str(t));
2746 				return -EINVAL;
2747 			}
2748 
2749 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2750 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2751 			if (err)
2752 				return err;
2753 
2754 			map_def->parts |= MAP_DEF_INNER_MAP;
2755 		} else if (strcmp(name, "pinning") == 0) {
2756 			__u32 val;
2757 
2758 			if (is_inner) {
2759 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2760 				return -EINVAL;
2761 			}
2762 			if (!get_map_field_int(map_name, btf, m, &val))
2763 				return -EINVAL;
2764 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2765 				pr_warn("map '%s': invalid pinning value %u.\n",
2766 					map_name, val);
2767 				return -EINVAL;
2768 			}
2769 			map_def->pinning = val;
2770 			map_def->parts |= MAP_DEF_PINNING;
2771 		} else if (strcmp(name, "map_extra") == 0) {
2772 			__u64 map_extra;
2773 
2774 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2775 				return -EINVAL;
2776 			map_def->map_extra = map_extra;
2777 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2778 		} else {
2779 			if (strict) {
2780 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2781 				return -ENOTSUP;
2782 			}
2783 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2784 		}
2785 	}
2786 
2787 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2788 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2789 		return -EINVAL;
2790 	}
2791 
2792 	return 0;
2793 }
2794 
2795 static size_t adjust_ringbuf_sz(size_t sz)
2796 {
2797 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2798 	__u32 mul;
2799 
2800 	/* if user forgot to set any size, make sure they see error */
2801 	if (sz == 0)
2802 		return 0;
2803 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2804 	 * a power-of-2 multiple of kernel's page size. If user diligently
2805 	 * satisified these conditions, pass the size through.
2806 	 */
2807 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2808 		return sz;
2809 
2810 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2811 	 * user-set size to satisfy both user size request and kernel
2812 	 * requirements and substitute correct max_entries for map creation.
2813 	 */
2814 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2815 		if (mul * page_sz > sz)
2816 			return mul * page_sz;
2817 	}
2818 
2819 	/* if it's impossible to satisfy the conditions (i.e., user size is
2820 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2821 	 * page_size) then just return original size and let kernel reject it
2822 	 */
2823 	return sz;
2824 }
2825 
2826 static bool map_is_ringbuf(const struct bpf_map *map)
2827 {
2828 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2829 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2830 }
2831 
2832 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2833 {
2834 	map->def.type = def->map_type;
2835 	map->def.key_size = def->key_size;
2836 	map->def.value_size = def->value_size;
2837 	map->def.max_entries = def->max_entries;
2838 	map->def.map_flags = def->map_flags;
2839 	map->map_extra = def->map_extra;
2840 
2841 	map->numa_node = def->numa_node;
2842 	map->btf_key_type_id = def->key_type_id;
2843 	map->btf_value_type_id = def->value_type_id;
2844 
2845 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2846 	if (map_is_ringbuf(map))
2847 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2848 
2849 	if (def->parts & MAP_DEF_MAP_TYPE)
2850 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2851 
2852 	if (def->parts & MAP_DEF_KEY_TYPE)
2853 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2854 			 map->name, def->key_type_id, def->key_size);
2855 	else if (def->parts & MAP_DEF_KEY_SIZE)
2856 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2857 
2858 	if (def->parts & MAP_DEF_VALUE_TYPE)
2859 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2860 			 map->name, def->value_type_id, def->value_size);
2861 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2862 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2863 
2864 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2865 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2866 	if (def->parts & MAP_DEF_MAP_FLAGS)
2867 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2868 	if (def->parts & MAP_DEF_MAP_EXTRA)
2869 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2870 			 (unsigned long long)def->map_extra);
2871 	if (def->parts & MAP_DEF_PINNING)
2872 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2873 	if (def->parts & MAP_DEF_NUMA_NODE)
2874 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2875 
2876 	if (def->parts & MAP_DEF_INNER_MAP)
2877 		pr_debug("map '%s': found inner map definition.\n", map->name);
2878 }
2879 
2880 static const char *btf_var_linkage_str(__u32 linkage)
2881 {
2882 	switch (linkage) {
2883 	case BTF_VAR_STATIC: return "static";
2884 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2885 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2886 	default: return "unknown";
2887 	}
2888 }
2889 
2890 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2891 					 const struct btf_type *sec,
2892 					 int var_idx, int sec_idx,
2893 					 const Elf_Data *data, bool strict,
2894 					 const char *pin_root_path)
2895 {
2896 	struct btf_map_def map_def = {}, inner_def = {};
2897 	const struct btf_type *var, *def;
2898 	const struct btf_var_secinfo *vi;
2899 	const struct btf_var *var_extra;
2900 	const char *map_name;
2901 	struct bpf_map *map;
2902 	int err;
2903 
2904 	vi = btf_var_secinfos(sec) + var_idx;
2905 	var = btf__type_by_id(obj->btf, vi->type);
2906 	var_extra = btf_var(var);
2907 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2908 
2909 	if (str_is_empty(map_name)) {
2910 		pr_warn("map #%d: empty name.\n", var_idx);
2911 		return -EINVAL;
2912 	}
2913 	if ((__u64)vi->offset + vi->size > data->d_size) {
2914 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2915 		return -EINVAL;
2916 	}
2917 	if (!btf_is_var(var)) {
2918 		pr_warn("map '%s': unexpected var kind %s.\n",
2919 			map_name, btf_kind_str(var));
2920 		return -EINVAL;
2921 	}
2922 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2923 		pr_warn("map '%s': unsupported map linkage %s.\n",
2924 			map_name, btf_var_linkage_str(var_extra->linkage));
2925 		return -EOPNOTSUPP;
2926 	}
2927 
2928 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2929 	if (!btf_is_struct(def)) {
2930 		pr_warn("map '%s': unexpected def kind %s.\n",
2931 			map_name, btf_kind_str(var));
2932 		return -EINVAL;
2933 	}
2934 	if (def->size > vi->size) {
2935 		pr_warn("map '%s': invalid def size.\n", map_name);
2936 		return -EINVAL;
2937 	}
2938 
2939 	map = bpf_object__add_map(obj);
2940 	if (IS_ERR(map))
2941 		return PTR_ERR(map);
2942 	map->name = strdup(map_name);
2943 	if (!map->name) {
2944 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2945 		return -ENOMEM;
2946 	}
2947 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2948 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2949 	map->sec_idx = sec_idx;
2950 	map->sec_offset = vi->offset;
2951 	map->btf_var_idx = var_idx;
2952 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2953 		 map_name, map->sec_idx, map->sec_offset);
2954 
2955 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2956 	if (err)
2957 		return err;
2958 
2959 	fill_map_from_def(map, &map_def);
2960 
2961 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2962 		err = build_map_pin_path(map, pin_root_path);
2963 		if (err) {
2964 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2965 			return err;
2966 		}
2967 	}
2968 
2969 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2970 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2971 		if (!map->inner_map)
2972 			return -ENOMEM;
2973 		map->inner_map->fd = create_placeholder_fd();
2974 		if (map->inner_map->fd < 0)
2975 			return map->inner_map->fd;
2976 		map->inner_map->sec_idx = sec_idx;
2977 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2978 		if (!map->inner_map->name)
2979 			return -ENOMEM;
2980 		sprintf(map->inner_map->name, "%s.inner", map_name);
2981 
2982 		fill_map_from_def(map->inner_map, &inner_def);
2983 	}
2984 
2985 	err = map_fill_btf_type_info(obj, map);
2986 	if (err)
2987 		return err;
2988 
2989 	return 0;
2990 }
2991 
2992 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2993 			       const char *sec_name, int sec_idx,
2994 			       void *data, size_t data_sz)
2995 {
2996 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2997 	const size_t data_alloc_sz = roundup(data_sz, page_sz);
2998 	size_t mmap_sz;
2999 
3000 	mmap_sz = bpf_map_mmap_sz(map);
3001 	if (data_alloc_sz > mmap_sz) {
3002 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
3003 			sec_name, mmap_sz, data_sz);
3004 		return -E2BIG;
3005 	}
3006 
3007 	obj->arena_data = malloc(data_sz);
3008 	if (!obj->arena_data)
3009 		return -ENOMEM;
3010 	memcpy(obj->arena_data, data, data_sz);
3011 	obj->arena_data_sz = data_sz;
3012 
3013 	/* make bpf_map__init_value() work for ARENA maps */
3014 	map->mmaped = obj->arena_data;
3015 
3016 	return 0;
3017 }
3018 
3019 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3020 					  const char *pin_root_path)
3021 {
3022 	const struct btf_type *sec = NULL;
3023 	int nr_types, i, vlen, err;
3024 	const struct btf_type *t;
3025 	const char *name;
3026 	Elf_Data *data;
3027 	Elf_Scn *scn;
3028 
3029 	if (obj->efile.btf_maps_shndx < 0)
3030 		return 0;
3031 
3032 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3033 	data = elf_sec_data(obj, scn);
3034 	if (!data) {
3035 		pr_warn("elf: failed to get %s map definitions for %s\n",
3036 			MAPS_ELF_SEC, obj->path);
3037 		return -EINVAL;
3038 	}
3039 
3040 	nr_types = btf__type_cnt(obj->btf);
3041 	for (i = 1; i < nr_types; i++) {
3042 		t = btf__type_by_id(obj->btf, i);
3043 		if (!btf_is_datasec(t))
3044 			continue;
3045 		name = btf__name_by_offset(obj->btf, t->name_off);
3046 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3047 			sec = t;
3048 			obj->efile.btf_maps_sec_btf_id = i;
3049 			break;
3050 		}
3051 	}
3052 
3053 	if (!sec) {
3054 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3055 		return -ENOENT;
3056 	}
3057 
3058 	vlen = btf_vlen(sec);
3059 	for (i = 0; i < vlen; i++) {
3060 		err = bpf_object__init_user_btf_map(obj, sec, i,
3061 						    obj->efile.btf_maps_shndx,
3062 						    data, strict,
3063 						    pin_root_path);
3064 		if (err)
3065 			return err;
3066 	}
3067 
3068 	for (i = 0; i < obj->nr_maps; i++) {
3069 		struct bpf_map *map = &obj->maps[i];
3070 
3071 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3072 			continue;
3073 
3074 		if (obj->arena_map_idx >= 0) {
3075 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3076 				map->name, obj->maps[obj->arena_map_idx].name);
3077 			return -EINVAL;
3078 		}
3079 		obj->arena_map_idx = i;
3080 
3081 		if (obj->efile.arena_data) {
3082 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3083 						  obj->efile.arena_data->d_buf,
3084 						  obj->efile.arena_data->d_size);
3085 			if (err)
3086 				return err;
3087 		}
3088 	}
3089 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3090 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3091 			ARENA_SEC);
3092 		return -ENOENT;
3093 	}
3094 
3095 	return 0;
3096 }
3097 
3098 static int bpf_object__init_maps(struct bpf_object *obj,
3099 				 const struct bpf_object_open_opts *opts)
3100 {
3101 	const char *pin_root_path;
3102 	bool strict;
3103 	int err = 0;
3104 
3105 	strict = !OPTS_GET(opts, relaxed_maps, false);
3106 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3107 
3108 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3109 	err = err ?: bpf_object__init_global_data_maps(obj);
3110 	err = err ?: bpf_object__init_kconfig_map(obj);
3111 	err = err ?: bpf_object_init_struct_ops(obj);
3112 
3113 	return err;
3114 }
3115 
3116 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3117 {
3118 	Elf64_Shdr *sh;
3119 
3120 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3121 	if (!sh)
3122 		return false;
3123 
3124 	return sh->sh_flags & SHF_EXECINSTR;
3125 }
3126 
3127 static bool starts_with_qmark(const char *s)
3128 {
3129 	return s && s[0] == '?';
3130 }
3131 
3132 static bool btf_needs_sanitization(struct bpf_object *obj)
3133 {
3134 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3135 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3136 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3137 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3138 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3139 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3140 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3141 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3142 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3143 
3144 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3145 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3146 	       !has_layout;
3147 }
3148 
3149 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3150 {
3151 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3152 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3153 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3154 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3155 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3156 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3157 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3158 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3159 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3160 	int enum64_placeholder_id = 0;
3161 	const struct btf_header *hdr;
3162 	struct btf *btf = NULL;
3163 	const void *raw_data;
3164 	struct btf_type *t;
3165 	int i, j, vlen;
3166 	__u32 sz;
3167 	int err;
3168 
3169 	/* clone BTF to sanitize a copy and leave the original intact */
3170 	raw_data = btf__raw_data(orig_btf, &sz);
3171 	if (!raw_data)
3172 		return ERR_PTR(-ENOMEM);
3173 	/* btf_header() gives us endian-safe header info */
3174 	hdr = btf_header(orig_btf);
3175 
3176 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3177 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3178 		const struct btf_header *old_hdr = raw_data;
3179 		struct btf_header *new_hdr;
3180 		void *new_raw_data;
3181 		__u32 new_str_off;
3182 
3183 		/*
3184 		 * Need to rewrite BTF to exclude layout information and
3185 		 * move string section to immediately after types.
3186 		 */
3187 		new_raw_data = malloc(sz);
3188 		if (!new_raw_data)
3189 			return ERR_PTR(-ENOMEM);
3190 
3191 		memcpy(new_raw_data, raw_data, sz);
3192 		new_hdr = new_raw_data;
3193 		new_hdr->layout_off = 0;
3194 		new_hdr->layout_len = 0;
3195 		new_str_off = hdr->type_off + hdr->type_len;
3196 		/* Handle swapped endian case */
3197 		if (old_hdr->magic != hdr->magic)
3198 			new_hdr->str_off = bswap_32(new_str_off);
3199 		else
3200 			new_hdr->str_off = new_str_off;
3201 
3202 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3203 			new_raw_data + hdr->hdr_len + hdr->str_off,
3204 			hdr->str_len);
3205 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3206 		btf = btf__new(new_raw_data, sz);
3207 		free(new_raw_data);
3208 	} else {
3209 		btf = btf__new(raw_data, sz);
3210 	}
3211 	err = libbpf_get_error(btf);
3212 	if (err)
3213 		return ERR_PTR(err);
3214 
3215 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3216 	btf__set_pointer_size(btf, 8);
3217 
3218 	for (i = 1; i < btf__type_cnt(btf); i++) {
3219 		t = (struct btf_type *)btf__type_by_id(btf, i);
3220 
3221 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3222 			/* replace VAR/DECL_TAG with INT */
3223 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3224 			/*
3225 			 * using size = 1 is the safest choice, 4 will be too
3226 			 * big and cause kernel BTF validation failure if
3227 			 * original variable took less than 4 bytes
3228 			 */
3229 			t->size = 1;
3230 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3231 		} else if (!has_datasec && btf_is_datasec(t)) {
3232 			/* replace DATASEC with STRUCT */
3233 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3234 			struct btf_member *m = btf_members(t);
3235 			struct btf_type *vt;
3236 			char *name;
3237 
3238 			name = (char *)btf__name_by_offset(btf, t->name_off);
3239 			while (*name) {
3240 				if (*name == '.' || *name == '?')
3241 					*name = '_';
3242 				name++;
3243 			}
3244 
3245 			vlen = btf_vlen(t);
3246 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3247 			for (j = 0; j < vlen; j++, v++, m++) {
3248 				/* order of field assignments is important */
3249 				m->offset = v->offset * 8;
3250 				m->type = v->type;
3251 				/* preserve variable name as member name */
3252 				vt = (void *)btf__type_by_id(btf, v->type);
3253 				m->name_off = vt->name_off;
3254 			}
3255 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3256 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3257 			/* replace '?' prefix with '_' for DATASEC names */
3258 			char *name;
3259 
3260 			name = (char *)btf__name_by_offset(btf, t->name_off);
3261 			if (name[0] == '?')
3262 				name[0] = '_';
3263 		} else if (!has_func && btf_is_func_proto(t)) {
3264 			/* replace FUNC_PROTO with ENUM */
3265 			vlen = btf_vlen(t);
3266 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3267 			t->size = sizeof(__u32); /* kernel enforced */
3268 		} else if (!has_func && btf_is_func(t)) {
3269 			/* replace FUNC with TYPEDEF */
3270 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3271 		} else if (!has_func_global && btf_is_func(t)) {
3272 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3273 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3274 		} else if (!has_float && btf_is_float(t)) {
3275 			/* replace FLOAT with an equally-sized empty STRUCT;
3276 			 * since C compilers do not accept e.g. "float" as a
3277 			 * valid struct name, make it anonymous
3278 			 */
3279 			t->name_off = 0;
3280 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3281 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3282 			/* replace TYPE_TAG with a CONST */
3283 			t->name_off = 0;
3284 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3285 		} else if (!has_enum64 && btf_is_enum(t)) {
3286 			/* clear the kflag */
3287 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3288 		} else if (!has_enum64 && btf_is_enum64(t)) {
3289 			/* replace ENUM64 with a union */
3290 			struct btf_member *m;
3291 
3292 			if (enum64_placeholder_id == 0) {
3293 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3294 				if (enum64_placeholder_id < 0) {
3295 					btf__free(btf);
3296 					return ERR_PTR(enum64_placeholder_id);
3297 				}
3298 				t = (struct btf_type *)btf__type_by_id(btf, i);
3299 			}
3300 
3301 			m = btf_members(t);
3302 			vlen = btf_vlen(t);
3303 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3304 			for (j = 0; j < vlen; j++, m++) {
3305 				m->type = enum64_placeholder_id;
3306 				m->offset = 0;
3307 			}
3308 		}
3309 	}
3310 
3311 	return btf;
3312 }
3313 
3314 static bool libbpf_needs_btf(const struct bpf_object *obj)
3315 {
3316 	return obj->efile.btf_maps_shndx >= 0 ||
3317 	       obj->efile.has_st_ops ||
3318 	       obj->nr_extern > 0;
3319 }
3320 
3321 static bool kernel_needs_btf(const struct bpf_object *obj)
3322 {
3323 	return obj->efile.has_st_ops;
3324 }
3325 
3326 static int bpf_object__init_btf(struct bpf_object *obj,
3327 				Elf_Data *btf_data,
3328 				Elf_Data *btf_ext_data)
3329 {
3330 	int err = -ENOENT;
3331 
3332 	if (btf_data) {
3333 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3334 		err = libbpf_get_error(obj->btf);
3335 		if (err) {
3336 			obj->btf = NULL;
3337 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3338 			goto out;
3339 		}
3340 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3341 		btf__set_pointer_size(obj->btf, 8);
3342 	}
3343 	if (btf_ext_data) {
3344 		struct btf_ext_info *ext_segs[3];
3345 		int seg_num, sec_num;
3346 
3347 		if (!obj->btf) {
3348 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3349 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3350 			goto out;
3351 		}
3352 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3353 		err = libbpf_get_error(obj->btf_ext);
3354 		if (err) {
3355 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3356 				BTF_EXT_ELF_SEC, errstr(err));
3357 			obj->btf_ext = NULL;
3358 			goto out;
3359 		}
3360 
3361 		/* setup .BTF.ext to ELF section mapping */
3362 		ext_segs[0] = &obj->btf_ext->func_info;
3363 		ext_segs[1] = &obj->btf_ext->line_info;
3364 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3365 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3366 			struct btf_ext_info *seg = ext_segs[seg_num];
3367 			const struct btf_ext_info_sec *sec;
3368 			const char *sec_name;
3369 			Elf_Scn *scn;
3370 
3371 			if (seg->sec_cnt == 0)
3372 				continue;
3373 
3374 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3375 			if (!seg->sec_idxs) {
3376 				err = -ENOMEM;
3377 				goto out;
3378 			}
3379 
3380 			sec_num = 0;
3381 			for_each_btf_ext_sec(seg, sec) {
3382 				/* preventively increment index to avoid doing
3383 				 * this before every continue below
3384 				 */
3385 				sec_num++;
3386 
3387 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3388 				if (str_is_empty(sec_name))
3389 					continue;
3390 				scn = elf_sec_by_name(obj, sec_name);
3391 				if (!scn)
3392 					continue;
3393 
3394 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3395 			}
3396 		}
3397 	}
3398 out:
3399 	if (err && libbpf_needs_btf(obj)) {
3400 		pr_warn("BTF is required, but is missing or corrupted.\n");
3401 		return err;
3402 	}
3403 	return 0;
3404 }
3405 
3406 static int compare_vsi_off(const void *_a, const void *_b)
3407 {
3408 	const struct btf_var_secinfo *a = _a;
3409 	const struct btf_var_secinfo *b = _b;
3410 
3411 	return a->offset - b->offset;
3412 }
3413 
3414 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3415 			     struct btf_type *t)
3416 {
3417 	__u32 size = 0, i, vars = btf_vlen(t);
3418 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3419 	struct btf_var_secinfo *vsi;
3420 	bool fixup_offsets = false;
3421 	int err;
3422 
3423 	if (!sec_name) {
3424 		pr_debug("No name found in string section for DATASEC kind.\n");
3425 		return -ENOENT;
3426 	}
3427 
3428 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3429 	 * variable offsets set at the previous step. Further, not every
3430 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3431 	 * all fixups altogether for such sections and go straight to sorting
3432 	 * VARs within their DATASEC.
3433 	 */
3434 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3435 		goto sort_vars;
3436 
3437 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3438 	 * fix this up. But BPF static linker already fixes this up and fills
3439 	 * all the sizes and offsets during static linking. So this step has
3440 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3441 	 * non-extern DATASEC, so the variable fixup loop below handles both
3442 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3443 	 * symbol matching just once.
3444 	 */
3445 	if (t->size == 0) {
3446 		err = find_elf_sec_sz(obj, sec_name, &size);
3447 		if (err || !size) {
3448 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3449 				 sec_name, size, errstr(err));
3450 			return -ENOENT;
3451 		}
3452 
3453 		t->size = size;
3454 		fixup_offsets = true;
3455 	}
3456 
3457 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3458 		const struct btf_type *t_var;
3459 		struct btf_var *var;
3460 		const char *var_name;
3461 		Elf64_Sym *sym;
3462 
3463 		t_var = btf__type_by_id(btf, vsi->type);
3464 		if (!t_var || !btf_is_var(t_var)) {
3465 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3466 			return -EINVAL;
3467 		}
3468 
3469 		var = btf_var(t_var);
3470 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3471 			continue;
3472 
3473 		var_name = btf__name_by_offset(btf, t_var->name_off);
3474 		if (!var_name) {
3475 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3476 				 sec_name, i);
3477 			return -ENOENT;
3478 		}
3479 
3480 		sym = find_elf_var_sym(obj, var_name);
3481 		if (IS_ERR(sym)) {
3482 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3483 				 sec_name, var_name);
3484 			return -ENOENT;
3485 		}
3486 
3487 		if (fixup_offsets)
3488 			vsi->offset = sym->st_value;
3489 
3490 		/* if variable is a global/weak symbol, but has restricted
3491 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3492 		 * as static. This follows similar logic for functions (BPF
3493 		 * subprogs) and influences libbpf's further decisions about
3494 		 * whether to make global data BPF array maps as
3495 		 * BPF_F_MMAPABLE.
3496 		 */
3497 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3498 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3499 			var->linkage = BTF_VAR_STATIC;
3500 	}
3501 
3502 sort_vars:
3503 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3504 	return 0;
3505 }
3506 
3507 static int bpf_object_fixup_btf(struct bpf_object *obj)
3508 {
3509 	int i, n, err = 0;
3510 
3511 	if (!obj->btf)
3512 		return 0;
3513 
3514 	n = btf__type_cnt(obj->btf);
3515 	for (i = 1; i < n; i++) {
3516 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3517 
3518 		/* Loader needs to fix up some of the things compiler
3519 		 * couldn't get its hands on while emitting BTF. This
3520 		 * is section size and global variable offset. We use
3521 		 * the info from the ELF itself for this purpose.
3522 		 */
3523 		if (btf_is_datasec(t)) {
3524 			err = btf_fixup_datasec(obj, obj->btf, t);
3525 			if (err)
3526 				return err;
3527 		}
3528 	}
3529 
3530 	return 0;
3531 }
3532 
3533 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3534 {
3535 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3536 	    prog->type == BPF_PROG_TYPE_LSM)
3537 		return true;
3538 
3539 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3540 	 * also need vmlinux BTF
3541 	 */
3542 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3543 		return true;
3544 
3545 	return false;
3546 }
3547 
3548 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3549 {
3550 	return bpf_map__is_struct_ops(map);
3551 }
3552 
3553 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3554 {
3555 	struct bpf_program *prog;
3556 	struct bpf_map *map;
3557 	int i;
3558 
3559 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3560 	 * is not specified
3561 	 */
3562 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3563 		return true;
3564 
3565 	/* Support for typed ksyms needs kernel BTF */
3566 	for (i = 0; i < obj->nr_extern; i++) {
3567 		const struct extern_desc *ext;
3568 
3569 		ext = &obj->externs[i];
3570 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3571 			return true;
3572 	}
3573 
3574 	bpf_object__for_each_program(prog, obj) {
3575 		if (!prog->autoload)
3576 			continue;
3577 		if (prog_needs_vmlinux_btf(prog))
3578 			return true;
3579 	}
3580 
3581 	bpf_object__for_each_map(map, obj) {
3582 		if (map_needs_vmlinux_btf(map))
3583 			return true;
3584 	}
3585 
3586 	return false;
3587 }
3588 
3589 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3590 {
3591 	int err;
3592 
3593 	/* btf_vmlinux could be loaded earlier */
3594 	if (obj->btf_vmlinux || obj->gen_loader)
3595 		return 0;
3596 
3597 	if (!force && !obj_needs_vmlinux_btf(obj))
3598 		return 0;
3599 
3600 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3601 	err = libbpf_get_error(obj->btf_vmlinux);
3602 	if (err) {
3603 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3604 		obj->btf_vmlinux = NULL;
3605 		return err;
3606 	}
3607 	return 0;
3608 }
3609 
3610 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3611 {
3612 	struct btf *kern_btf = obj->btf;
3613 	bool btf_mandatory, sanitize;
3614 	int i, err = 0;
3615 
3616 	if (!obj->btf)
3617 		return 0;
3618 
3619 	if (!kernel_supports(obj, FEAT_BTF)) {
3620 		if (kernel_needs_btf(obj)) {
3621 			err = -EOPNOTSUPP;
3622 			goto report;
3623 		}
3624 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3625 		return 0;
3626 	}
3627 
3628 	/* Even though some subprogs are global/weak, user might prefer more
3629 	 * permissive BPF verification process that BPF verifier performs for
3630 	 * static functions, taking into account more context from the caller
3631 	 * functions. In such case, they need to mark such subprogs with
3632 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3633 	 * corresponding FUNC BTF type to be marked as static and trigger more
3634 	 * involved BPF verification process.
3635 	 */
3636 	for (i = 0; i < obj->nr_programs; i++) {
3637 		struct bpf_program *prog = &obj->programs[i];
3638 		struct btf_type *t;
3639 		const char *name;
3640 		int j, n;
3641 
3642 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3643 			continue;
3644 
3645 		n = btf__type_cnt(obj->btf);
3646 		for (j = 1; j < n; j++) {
3647 			t = btf_type_by_id(obj->btf, j);
3648 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3649 				continue;
3650 
3651 			name = btf__str_by_offset(obj->btf, t->name_off);
3652 			if (strcmp(name, prog->name) != 0)
3653 				continue;
3654 
3655 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3656 			break;
3657 		}
3658 	}
3659 
3660 	sanitize = btf_needs_sanitization(obj);
3661 	if (sanitize) {
3662 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3663 		if (IS_ERR(kern_btf))
3664 			return PTR_ERR(kern_btf);
3665 	}
3666 
3667 	if (obj->gen_loader) {
3668 		__u32 raw_size = 0;
3669 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3670 
3671 		if (!raw_data)
3672 			return -ENOMEM;
3673 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3674 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3675 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3676 		 */
3677 		btf__set_fd(kern_btf, 0);
3678 	} else {
3679 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3680 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3681 					   obj->log_level ? 1 : 0, obj->token_fd);
3682 	}
3683 	if (sanitize) {
3684 		if (!err) {
3685 			/* move fd to libbpf's BTF */
3686 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3687 			btf__set_fd(kern_btf, -1);
3688 		}
3689 		btf__free(kern_btf);
3690 	}
3691 report:
3692 	if (err) {
3693 		btf_mandatory = kernel_needs_btf(obj);
3694 		if (btf_mandatory) {
3695 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3696 				errstr(err));
3697 		} else {
3698 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3699 				errstr(err));
3700 			err = 0;
3701 		}
3702 	}
3703 	return err;
3704 }
3705 
3706 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3707 {
3708 	const char *name;
3709 
3710 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3711 	if (!name) {
3712 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3713 			off, obj->path, elf_errmsg(-1));
3714 		return NULL;
3715 	}
3716 
3717 	return name;
3718 }
3719 
3720 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3721 {
3722 	const char *name;
3723 
3724 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3725 	if (!name) {
3726 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3727 			off, obj->path, elf_errmsg(-1));
3728 		return NULL;
3729 	}
3730 
3731 	return name;
3732 }
3733 
3734 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3735 {
3736 	Elf_Scn *scn;
3737 
3738 	scn = elf_getscn(obj->efile.elf, idx);
3739 	if (!scn) {
3740 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3741 			idx, obj->path, elf_errmsg(-1));
3742 		return NULL;
3743 	}
3744 	return scn;
3745 }
3746 
3747 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3748 {
3749 	Elf_Scn *scn = NULL;
3750 	Elf *elf = obj->efile.elf;
3751 	const char *sec_name;
3752 
3753 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3754 		sec_name = elf_sec_name(obj, scn);
3755 		if (!sec_name)
3756 			return NULL;
3757 
3758 		if (strcmp(sec_name, name) != 0)
3759 			continue;
3760 
3761 		return scn;
3762 	}
3763 	return NULL;
3764 }
3765 
3766 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3767 {
3768 	Elf64_Shdr *shdr;
3769 
3770 	if (!scn)
3771 		return NULL;
3772 
3773 	shdr = elf64_getshdr(scn);
3774 	if (!shdr) {
3775 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3776 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3777 		return NULL;
3778 	}
3779 
3780 	return shdr;
3781 }
3782 
3783 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3784 {
3785 	const char *name;
3786 	Elf64_Shdr *sh;
3787 
3788 	if (!scn)
3789 		return NULL;
3790 
3791 	sh = elf_sec_hdr(obj, scn);
3792 	if (!sh)
3793 		return NULL;
3794 
3795 	name = elf_sec_str(obj, sh->sh_name);
3796 	if (!name) {
3797 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3798 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3799 		return NULL;
3800 	}
3801 
3802 	return name;
3803 }
3804 
3805 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3806 {
3807 	Elf_Data *data;
3808 
3809 	if (!scn)
3810 		return NULL;
3811 
3812 	data = elf_getdata(scn, 0);
3813 	if (!data) {
3814 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3815 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3816 			obj->path, elf_errmsg(-1));
3817 		return NULL;
3818 	}
3819 
3820 	return data;
3821 }
3822 
3823 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3824 {
3825 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3826 		return NULL;
3827 
3828 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3829 }
3830 
3831 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3832 {
3833 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3834 		return NULL;
3835 
3836 	return (Elf64_Rel *)data->d_buf + idx;
3837 }
3838 
3839 static bool is_sec_name_dwarf(const char *name)
3840 {
3841 	/* approximation, but the actual list is too long */
3842 	return str_has_pfx(name, ".debug_");
3843 }
3844 
3845 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3846 {
3847 	/* no special handling of .strtab */
3848 	if (hdr->sh_type == SHT_STRTAB)
3849 		return true;
3850 
3851 	/* ignore .llvm_addrsig section as well */
3852 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3853 		return true;
3854 
3855 	/* no subprograms will lead to an empty .text section, ignore it */
3856 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3857 	    strcmp(name, ".text") == 0)
3858 		return true;
3859 
3860 	/* DWARF sections */
3861 	if (is_sec_name_dwarf(name))
3862 		return true;
3863 
3864 	if (str_has_pfx(name, ".rel")) {
3865 		name += sizeof(".rel") - 1;
3866 		/* DWARF section relocations */
3867 		if (is_sec_name_dwarf(name))
3868 			return true;
3869 
3870 		/* .BTF and .BTF.ext don't need relocations */
3871 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3872 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3873 			return true;
3874 	}
3875 
3876 	return false;
3877 }
3878 
3879 static int cmp_progs(const void *_a, const void *_b)
3880 {
3881 	const struct bpf_program *a = _a;
3882 	const struct bpf_program *b = _b;
3883 
3884 	if (a->sec_idx != b->sec_idx)
3885 		return a->sec_idx < b->sec_idx ? -1 : 1;
3886 
3887 	/* sec_insn_off can't be the same within the section */
3888 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3889 }
3890 
3891 static int bpf_object__elf_collect(struct bpf_object *obj)
3892 {
3893 	struct elf_sec_desc *sec_desc;
3894 	Elf *elf = obj->efile.elf;
3895 	Elf_Data *btf_ext_data = NULL;
3896 	Elf_Data *btf_data = NULL;
3897 	int idx = 0, err = 0;
3898 	const char *name;
3899 	Elf_Data *data;
3900 	Elf_Scn *scn;
3901 	Elf64_Shdr *sh;
3902 
3903 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3904 	 * section. Since section count retrieved by elf_getshdrnum() does
3905 	 * include sec #0, it is already the necessary size of an array to keep
3906 	 * all the sections.
3907 	 */
3908 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3909 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3910 			obj->path, elf_errmsg(-1));
3911 		return -LIBBPF_ERRNO__FORMAT;
3912 	}
3913 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3914 	if (!obj->efile.secs)
3915 		return -ENOMEM;
3916 
3917 	/* a bunch of ELF parsing functionality depends on processing symbols,
3918 	 * so do the first pass and find the symbol table
3919 	 */
3920 	scn = NULL;
3921 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3922 		sh = elf_sec_hdr(obj, scn);
3923 		if (!sh)
3924 			return -LIBBPF_ERRNO__FORMAT;
3925 
3926 		if (sh->sh_type == SHT_SYMTAB) {
3927 			if (obj->efile.symbols) {
3928 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3929 				return -LIBBPF_ERRNO__FORMAT;
3930 			}
3931 
3932 			data = elf_sec_data(obj, scn);
3933 			if (!data)
3934 				return -LIBBPF_ERRNO__FORMAT;
3935 
3936 			idx = elf_ndxscn(scn);
3937 
3938 			obj->efile.symbols = data;
3939 			obj->efile.symbols_shndx = idx;
3940 			obj->efile.strtabidx = sh->sh_link;
3941 		}
3942 	}
3943 
3944 	if (!obj->efile.symbols) {
3945 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3946 			obj->path);
3947 		return -ENOENT;
3948 	}
3949 
3950 	scn = NULL;
3951 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3952 		idx = elf_ndxscn(scn);
3953 		sec_desc = &obj->efile.secs[idx];
3954 
3955 		sh = elf_sec_hdr(obj, scn);
3956 		if (!sh)
3957 			return -LIBBPF_ERRNO__FORMAT;
3958 
3959 		name = elf_sec_str(obj, sh->sh_name);
3960 		if (!name)
3961 			return -LIBBPF_ERRNO__FORMAT;
3962 
3963 		if (ignore_elf_section(sh, name))
3964 			continue;
3965 
3966 		data = elf_sec_data(obj, scn);
3967 		if (!data)
3968 			return -LIBBPF_ERRNO__FORMAT;
3969 
3970 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3971 			 idx, name, (unsigned long)data->d_size,
3972 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3973 			 (int)sh->sh_type);
3974 
3975 		if (strcmp(name, "license") == 0) {
3976 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3977 			if (err)
3978 				return err;
3979 		} else if (strcmp(name, "version") == 0) {
3980 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3981 			if (err)
3982 				return err;
3983 		} else if (strcmp(name, "maps") == 0) {
3984 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3985 			return -ENOTSUP;
3986 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3987 			obj->efile.btf_maps_shndx = idx;
3988 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3989 			if (sh->sh_type != SHT_PROGBITS)
3990 				return -LIBBPF_ERRNO__FORMAT;
3991 			btf_data = data;
3992 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3993 			if (sh->sh_type != SHT_PROGBITS)
3994 				return -LIBBPF_ERRNO__FORMAT;
3995 			btf_ext_data = data;
3996 		} else if (sh->sh_type == SHT_SYMTAB) {
3997 			/* already processed during the first pass above */
3998 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3999 			if (sh->sh_flags & SHF_EXECINSTR) {
4000 				if (strcmp(name, ".text") == 0)
4001 					obj->efile.text_shndx = idx;
4002 				err = bpf_object__add_programs(obj, data, name, idx);
4003 				if (err)
4004 					return err;
4005 			} else if (strcmp(name, DATA_SEC) == 0 ||
4006 				   str_has_pfx(name, DATA_SEC ".")) {
4007 				sec_desc->sec_type = SEC_DATA;
4008 				sec_desc->shdr = sh;
4009 				sec_desc->data = data;
4010 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4011 				   str_has_pfx(name, RODATA_SEC ".")) {
4012 				sec_desc->sec_type = SEC_RODATA;
4013 				sec_desc->shdr = sh;
4014 				sec_desc->data = data;
4015 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4016 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4017 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4018 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4019 				sec_desc->sec_type = SEC_ST_OPS;
4020 				sec_desc->shdr = sh;
4021 				sec_desc->data = data;
4022 				obj->efile.has_st_ops = true;
4023 			} else if (strcmp(name, ARENA_SEC) == 0) {
4024 				obj->efile.arena_data = data;
4025 				obj->efile.arena_data_shndx = idx;
4026 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4027 				obj->jumptables_data = malloc(data->d_size);
4028 				if (!obj->jumptables_data)
4029 					return -ENOMEM;
4030 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4031 				obj->jumptables_data_sz = data->d_size;
4032 				obj->efile.jumptables_data_shndx = idx;
4033 			} else {
4034 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4035 					idx, name);
4036 			}
4037 		} else if (sh->sh_type == SHT_REL) {
4038 			int targ_sec_idx = sh->sh_info; /* points to other section */
4039 
4040 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4041 			    targ_sec_idx >= obj->efile.sec_cnt)
4042 				return -LIBBPF_ERRNO__FORMAT;
4043 
4044 			/* Only do relo for section with exec instructions */
4045 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4046 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4047 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4048 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4049 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4050 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4051 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4052 					idx, name, targ_sec_idx,
4053 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4054 				continue;
4055 			}
4056 
4057 			sec_desc->sec_type = SEC_RELO;
4058 			sec_desc->shdr = sh;
4059 			sec_desc->data = data;
4060 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4061 							 str_has_pfx(name, BSS_SEC "."))) {
4062 			sec_desc->sec_type = SEC_BSS;
4063 			sec_desc->shdr = sh;
4064 			sec_desc->data = data;
4065 		} else {
4066 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4067 				(size_t)sh->sh_size);
4068 		}
4069 	}
4070 
4071 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4072 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4073 		return -LIBBPF_ERRNO__FORMAT;
4074 	}
4075 
4076 	/* change BPF program insns to native endianness for introspection */
4077 	if (!is_native_endianness(obj))
4078 		bpf_object_bswap_progs(obj);
4079 
4080 	/* sort BPF programs by section name and in-section instruction offset
4081 	 * for faster search
4082 	 */
4083 	if (obj->nr_programs)
4084 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4085 
4086 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4087 }
4088 
4089 static bool sym_is_extern(const Elf64_Sym *sym)
4090 {
4091 	int bind = ELF64_ST_BIND(sym->st_info);
4092 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4093 	return sym->st_shndx == SHN_UNDEF &&
4094 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4095 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4096 }
4097 
4098 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4099 {
4100 	int bind = ELF64_ST_BIND(sym->st_info);
4101 	int type = ELF64_ST_TYPE(sym->st_info);
4102 
4103 	/* in .text section */
4104 	if (sym->st_shndx != text_shndx)
4105 		return false;
4106 
4107 	/* local function */
4108 	if (bind == STB_LOCAL && type == STT_SECTION)
4109 		return true;
4110 
4111 	/* global function */
4112 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4113 }
4114 
4115 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4116 {
4117 	const struct btf_type *t;
4118 	const char *tname;
4119 	int i, n;
4120 
4121 	if (!btf)
4122 		return -ESRCH;
4123 
4124 	n = btf__type_cnt(btf);
4125 	for (i = 1; i < n; i++) {
4126 		t = btf__type_by_id(btf, i);
4127 
4128 		if (!btf_is_var(t) && !btf_is_func(t))
4129 			continue;
4130 
4131 		tname = btf__name_by_offset(btf, t->name_off);
4132 		if (strcmp(tname, ext_name))
4133 			continue;
4134 
4135 		if (btf_is_var(t) &&
4136 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4137 			return -EINVAL;
4138 
4139 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4140 			return -EINVAL;
4141 
4142 		return i;
4143 	}
4144 
4145 	return -ENOENT;
4146 }
4147 
4148 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4149 	const struct btf_var_secinfo *vs;
4150 	const struct btf_type *t;
4151 	int i, j, n;
4152 
4153 	if (!btf)
4154 		return -ESRCH;
4155 
4156 	n = btf__type_cnt(btf);
4157 	for (i = 1; i < n; i++) {
4158 		t = btf__type_by_id(btf, i);
4159 
4160 		if (!btf_is_datasec(t))
4161 			continue;
4162 
4163 		vs = btf_var_secinfos(t);
4164 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4165 			if (vs->type == ext_btf_id)
4166 				return i;
4167 		}
4168 	}
4169 
4170 	return -ENOENT;
4171 }
4172 
4173 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4174 				     bool *is_signed)
4175 {
4176 	const struct btf_type *t;
4177 	const char *name;
4178 
4179 	t = skip_mods_and_typedefs(btf, id, NULL);
4180 	name = btf__name_by_offset(btf, t->name_off);
4181 
4182 	if (is_signed)
4183 		*is_signed = false;
4184 	switch (btf_kind(t)) {
4185 	case BTF_KIND_INT: {
4186 		int enc = btf_int_encoding(t);
4187 
4188 		if (enc & BTF_INT_BOOL)
4189 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4190 		if (is_signed)
4191 			*is_signed = enc & BTF_INT_SIGNED;
4192 		if (t->size == 1)
4193 			return KCFG_CHAR;
4194 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4195 			return KCFG_UNKNOWN;
4196 		return KCFG_INT;
4197 	}
4198 	case BTF_KIND_ENUM:
4199 		if (t->size != 4)
4200 			return KCFG_UNKNOWN;
4201 		if (strcmp(name, "libbpf_tristate"))
4202 			return KCFG_UNKNOWN;
4203 		return KCFG_TRISTATE;
4204 	case BTF_KIND_ENUM64:
4205 		if (strcmp(name, "libbpf_tristate"))
4206 			return KCFG_UNKNOWN;
4207 		return KCFG_TRISTATE;
4208 	case BTF_KIND_ARRAY:
4209 		if (btf_array(t)->nelems == 0)
4210 			return KCFG_UNKNOWN;
4211 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4212 			return KCFG_UNKNOWN;
4213 		return KCFG_CHAR_ARR;
4214 	default:
4215 		return KCFG_UNKNOWN;
4216 	}
4217 }
4218 
4219 static int cmp_externs(const void *_a, const void *_b)
4220 {
4221 	const struct extern_desc *a = _a;
4222 	const struct extern_desc *b = _b;
4223 
4224 	if (a->type != b->type)
4225 		return a->type < b->type ? -1 : 1;
4226 
4227 	if (a->type == EXT_KCFG) {
4228 		/* descending order by alignment requirements */
4229 		if (a->kcfg.align != b->kcfg.align)
4230 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4231 		/* ascending order by size, within same alignment class */
4232 		if (a->kcfg.sz != b->kcfg.sz)
4233 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4234 	}
4235 
4236 	/* resolve ties by name */
4237 	return strcmp(a->name, b->name);
4238 }
4239 
4240 static int find_int_btf_id(const struct btf *btf)
4241 {
4242 	const struct btf_type *t;
4243 	int i, n;
4244 
4245 	n = btf__type_cnt(btf);
4246 	for (i = 1; i < n; i++) {
4247 		t = btf__type_by_id(btf, i);
4248 
4249 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4250 			return i;
4251 	}
4252 
4253 	return 0;
4254 }
4255 
4256 static int add_dummy_ksym_var(struct btf *btf)
4257 {
4258 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4259 	const struct btf_var_secinfo *vs;
4260 	const struct btf_type *sec;
4261 
4262 	if (!btf)
4263 		return 0;
4264 
4265 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4266 					    BTF_KIND_DATASEC);
4267 	if (sec_btf_id < 0)
4268 		return 0;
4269 
4270 	sec = btf__type_by_id(btf, sec_btf_id);
4271 	vs = btf_var_secinfos(sec);
4272 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4273 		const struct btf_type *vt;
4274 
4275 		vt = btf__type_by_id(btf, vs->type);
4276 		if (btf_is_func(vt))
4277 			break;
4278 	}
4279 
4280 	/* No func in ksyms sec.  No need to add dummy var. */
4281 	if (i == btf_vlen(sec))
4282 		return 0;
4283 
4284 	int_btf_id = find_int_btf_id(btf);
4285 	dummy_var_btf_id = btf__add_var(btf,
4286 					"dummy_ksym",
4287 					BTF_VAR_GLOBAL_ALLOCATED,
4288 					int_btf_id);
4289 	if (dummy_var_btf_id < 0)
4290 		pr_warn("cannot create a dummy_ksym var\n");
4291 
4292 	return dummy_var_btf_id;
4293 }
4294 
4295 static int bpf_object__collect_externs(struct bpf_object *obj)
4296 {
4297 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4298 	const struct btf_type *t;
4299 	struct extern_desc *ext;
4300 	int i, n, off, dummy_var_btf_id;
4301 	const char *ext_name, *sec_name;
4302 	size_t ext_essent_len;
4303 	Elf_Scn *scn;
4304 	Elf64_Shdr *sh;
4305 
4306 	if (!obj->efile.symbols)
4307 		return 0;
4308 
4309 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4310 	sh = elf_sec_hdr(obj, scn);
4311 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4312 		return -LIBBPF_ERRNO__FORMAT;
4313 
4314 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4315 	if (dummy_var_btf_id < 0)
4316 		return dummy_var_btf_id;
4317 
4318 	n = sh->sh_size / sh->sh_entsize;
4319 	pr_debug("looking for externs among %d symbols...\n", n);
4320 
4321 	for (i = 0; i < n; i++) {
4322 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4323 
4324 		if (!sym)
4325 			return -LIBBPF_ERRNO__FORMAT;
4326 		if (!sym_is_extern(sym))
4327 			continue;
4328 		ext_name = elf_sym_str(obj, sym->st_name);
4329 		if (str_is_empty(ext_name))
4330 			continue;
4331 
4332 		ext = obj->externs;
4333 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4334 		if (!ext)
4335 			return -ENOMEM;
4336 		obj->externs = ext;
4337 		ext = &ext[obj->nr_extern];
4338 		memset(ext, 0, sizeof(*ext));
4339 		obj->nr_extern++;
4340 
4341 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4342 		if (ext->btf_id <= 0) {
4343 			pr_warn("failed to find BTF for extern '%s': %d\n",
4344 				ext_name, ext->btf_id);
4345 			return ext->btf_id;
4346 		}
4347 		t = btf__type_by_id(obj->btf, ext->btf_id);
4348 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4349 		if (!ext->name)
4350 			return -ENOMEM;
4351 		ext->sym_idx = i;
4352 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4353 
4354 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4355 		ext->essent_name = NULL;
4356 		if (ext_essent_len != strlen(ext->name)) {
4357 			ext->essent_name = strndup(ext->name, ext_essent_len);
4358 			if (!ext->essent_name)
4359 				return -ENOMEM;
4360 		}
4361 
4362 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4363 		if (ext->sec_btf_id <= 0) {
4364 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4365 				ext_name, ext->btf_id, ext->sec_btf_id);
4366 			return ext->sec_btf_id;
4367 		}
4368 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4369 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4370 
4371 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4372 			if (btf_is_func(t)) {
4373 				pr_warn("extern function %s is unsupported under %s section\n",
4374 					ext->name, KCONFIG_SEC);
4375 				return -ENOTSUP;
4376 			}
4377 			kcfg_sec = sec;
4378 			ext->type = EXT_KCFG;
4379 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4380 			if (ext->kcfg.sz <= 0) {
4381 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4382 					ext_name, ext->kcfg.sz);
4383 				return ext->kcfg.sz;
4384 			}
4385 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4386 			if (ext->kcfg.align <= 0) {
4387 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4388 					ext_name, ext->kcfg.align);
4389 				return -EINVAL;
4390 			}
4391 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4392 							&ext->kcfg.is_signed);
4393 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4394 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4395 				return -ENOTSUP;
4396 			}
4397 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4398 			ksym_sec = sec;
4399 			ext->type = EXT_KSYM;
4400 			skip_mods_and_typedefs(obj->btf, t->type,
4401 					       &ext->ksym.type_id);
4402 		} else {
4403 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4404 			return -ENOTSUP;
4405 		}
4406 	}
4407 	pr_debug("collected %d externs total\n", obj->nr_extern);
4408 
4409 	if (!obj->nr_extern)
4410 		return 0;
4411 
4412 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4413 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4414 
4415 	/* for .ksyms section, we need to turn all externs into allocated
4416 	 * variables in BTF to pass kernel verification; we do this by
4417 	 * pretending that each extern is a 8-byte variable
4418 	 */
4419 	if (ksym_sec) {
4420 		/* find existing 4-byte integer type in BTF to use for fake
4421 		 * extern variables in DATASEC
4422 		 */
4423 		int int_btf_id = find_int_btf_id(obj->btf);
4424 		/* For extern function, a dummy_var added earlier
4425 		 * will be used to replace the vs->type and
4426 		 * its name string will be used to refill
4427 		 * the missing param's name.
4428 		 */
4429 		const struct btf_type *dummy_var;
4430 
4431 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4432 		for (i = 0; i < obj->nr_extern; i++) {
4433 			ext = &obj->externs[i];
4434 			if (ext->type != EXT_KSYM)
4435 				continue;
4436 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4437 				 i, ext->sym_idx, ext->name);
4438 		}
4439 
4440 		sec = ksym_sec;
4441 		n = btf_vlen(sec);
4442 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4443 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4444 			struct btf_type *vt;
4445 
4446 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4447 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4448 			ext = find_extern_by_name(obj, ext_name);
4449 			if (!ext) {
4450 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4451 					btf_kind_str(vt), ext_name);
4452 				return -ESRCH;
4453 			}
4454 			if (btf_is_func(vt)) {
4455 				const struct btf_type *func_proto;
4456 				struct btf_param *param;
4457 				int j;
4458 
4459 				func_proto = btf__type_by_id(obj->btf,
4460 							     vt->type);
4461 				param = btf_params(func_proto);
4462 				/* Reuse the dummy_var string if the
4463 				 * func proto does not have param name.
4464 				 */
4465 				for (j = 0; j < btf_vlen(func_proto); j++)
4466 					if (param[j].type && !param[j].name_off)
4467 						param[j].name_off =
4468 							dummy_var->name_off;
4469 				vs->type = dummy_var_btf_id;
4470 				vt->info &= ~0xffff;
4471 				vt->info |= BTF_FUNC_GLOBAL;
4472 			} else {
4473 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4474 				vt->type = int_btf_id;
4475 			}
4476 			vs->offset = off;
4477 			vs->size = sizeof(int);
4478 		}
4479 		sec->size = off;
4480 	}
4481 
4482 	if (kcfg_sec) {
4483 		sec = kcfg_sec;
4484 		/* for kcfg externs calculate their offsets within a .kconfig map */
4485 		off = 0;
4486 		for (i = 0; i < obj->nr_extern; i++) {
4487 			ext = &obj->externs[i];
4488 			if (ext->type != EXT_KCFG)
4489 				continue;
4490 
4491 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4492 			off = ext->kcfg.data_off + ext->kcfg.sz;
4493 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4494 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4495 		}
4496 		sec->size = off;
4497 		n = btf_vlen(sec);
4498 		for (i = 0; i < n; i++) {
4499 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4500 
4501 			t = btf__type_by_id(obj->btf, vs->type);
4502 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4503 			ext = find_extern_by_name(obj, ext_name);
4504 			if (!ext) {
4505 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4506 					ext_name);
4507 				return -ESRCH;
4508 			}
4509 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4510 			vs->offset = ext->kcfg.data_off;
4511 		}
4512 	}
4513 	return 0;
4514 }
4515 
4516 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4517 {
4518 	return prog->sec_idx == obj->efile.text_shndx;
4519 }
4520 
4521 struct bpf_program *
4522 bpf_object__find_program_by_name(const struct bpf_object *obj,
4523 				 const char *name)
4524 {
4525 	struct bpf_program *prog;
4526 
4527 	bpf_object__for_each_program(prog, obj) {
4528 		if (prog_is_subprog(obj, prog))
4529 			continue;
4530 		if (!strcmp(prog->name, name))
4531 			return prog;
4532 	}
4533 	return errno = ENOENT, NULL;
4534 }
4535 
4536 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4537 				      int shndx)
4538 {
4539 	switch (obj->efile.secs[shndx].sec_type) {
4540 	case SEC_BSS:
4541 	case SEC_DATA:
4542 	case SEC_RODATA:
4543 		return true;
4544 	default:
4545 		return false;
4546 	}
4547 }
4548 
4549 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4550 				      int shndx)
4551 {
4552 	return shndx == obj->efile.btf_maps_shndx;
4553 }
4554 
4555 static enum libbpf_map_type
4556 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4557 {
4558 	if (shndx == obj->efile.symbols_shndx)
4559 		return LIBBPF_MAP_KCONFIG;
4560 
4561 	switch (obj->efile.secs[shndx].sec_type) {
4562 	case SEC_BSS:
4563 		return LIBBPF_MAP_BSS;
4564 	case SEC_DATA:
4565 		return LIBBPF_MAP_DATA;
4566 	case SEC_RODATA:
4567 		return LIBBPF_MAP_RODATA;
4568 	default:
4569 		return LIBBPF_MAP_UNSPEC;
4570 	}
4571 }
4572 
4573 static int bpf_prog_compute_hash(struct bpf_program *prog)
4574 {
4575 	struct bpf_insn *purged;
4576 	int i, err = 0;
4577 
4578 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4579 	if (!purged)
4580 		return -ENOMEM;
4581 
4582 	/* If relocations have been done, the map_fd needs to be
4583 	 * discarded for the digest calculation.
4584 	 */
4585 	for (i = 0; i < prog->insns_cnt; i++) {
4586 		purged[i] = prog->insns[i];
4587 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4588 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4589 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4590 			purged[i].imm = 0;
4591 			i++;
4592 			if (i >= prog->insns_cnt ||
4593 			    prog->insns[i].code != 0 ||
4594 			    prog->insns[i].dst_reg != 0 ||
4595 			    prog->insns[i].src_reg != 0 ||
4596 			    prog->insns[i].off != 0) {
4597 				err = -EINVAL;
4598 				goto out;
4599 			}
4600 			purged[i] = prog->insns[i];
4601 			purged[i].imm = 0;
4602 		}
4603 	}
4604 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4605 		      prog->hash);
4606 out:
4607 	free(purged);
4608 	return err;
4609 }
4610 
4611 static int bpf_program__record_reloc(struct bpf_program *prog,
4612 				     struct reloc_desc *reloc_desc,
4613 				     __u32 insn_idx, const char *sym_name,
4614 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4615 {
4616 	struct bpf_insn *insn = &prog->insns[insn_idx];
4617 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4618 	struct bpf_object *obj = prog->obj;
4619 	__u32 shdr_idx = sym->st_shndx;
4620 	enum libbpf_map_type type;
4621 	const char *sym_sec_name;
4622 	struct bpf_map *map;
4623 
4624 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4625 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4626 			prog->name, sym_name, insn_idx, insn->code);
4627 		return -LIBBPF_ERRNO__RELOC;
4628 	}
4629 
4630 	if (sym_is_extern(sym)) {
4631 		int sym_idx = ELF64_R_SYM(rel->r_info);
4632 		int i, n = obj->nr_extern;
4633 		struct extern_desc *ext;
4634 
4635 		for (i = 0; i < n; i++) {
4636 			ext = &obj->externs[i];
4637 			if (ext->sym_idx == sym_idx)
4638 				break;
4639 		}
4640 		if (i >= n) {
4641 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4642 				prog->name, sym_name, sym_idx);
4643 			return -LIBBPF_ERRNO__RELOC;
4644 		}
4645 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4646 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4647 		if (insn->code == (BPF_JMP | BPF_CALL))
4648 			reloc_desc->type = RELO_EXTERN_CALL;
4649 		else
4650 			reloc_desc->type = RELO_EXTERN_LD64;
4651 		reloc_desc->insn_idx = insn_idx;
4652 		reloc_desc->ext_idx = i;
4653 		return 0;
4654 	}
4655 
4656 	/* sub-program call relocation */
4657 	if (is_call_insn(insn)) {
4658 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4659 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4660 			return -LIBBPF_ERRNO__RELOC;
4661 		}
4662 		/* text_shndx can be 0, if no default "main" program exists */
4663 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4664 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4665 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4666 				prog->name, sym_name, sym_sec_name);
4667 			return -LIBBPF_ERRNO__RELOC;
4668 		}
4669 		if (sym->st_value % BPF_INSN_SZ) {
4670 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4671 				prog->name, sym_name, (size_t)sym->st_value);
4672 			return -LIBBPF_ERRNO__RELOC;
4673 		}
4674 		reloc_desc->type = RELO_CALL;
4675 		reloc_desc->insn_idx = insn_idx;
4676 		reloc_desc->sym_off = sym->st_value;
4677 		return 0;
4678 	}
4679 
4680 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4681 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4682 			prog->name, sym_name, shdr_idx);
4683 		return -LIBBPF_ERRNO__RELOC;
4684 	}
4685 
4686 	/* loading subprog addresses */
4687 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4688 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4689 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4690 		 */
4691 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4692 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4693 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4694 			return -LIBBPF_ERRNO__RELOC;
4695 		}
4696 
4697 		reloc_desc->type = RELO_SUBPROG_ADDR;
4698 		reloc_desc->insn_idx = insn_idx;
4699 		reloc_desc->sym_off = sym->st_value;
4700 		return 0;
4701 	}
4702 
4703 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4704 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4705 
4706 	/* arena data relocation */
4707 	if (shdr_idx == obj->efile.arena_data_shndx) {
4708 		if (obj->arena_map_idx < 0) {
4709 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4710 				prog->name, insn_idx);
4711 			return -LIBBPF_ERRNO__RELOC;
4712 		}
4713 		reloc_desc->type = RELO_DATA;
4714 		reloc_desc->insn_idx = insn_idx;
4715 		reloc_desc->map_idx = obj->arena_map_idx;
4716 		reloc_desc->sym_off = sym->st_value;
4717 
4718 		map = &obj->maps[obj->arena_map_idx];
4719 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4720 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4721 			 map->sec_offset, insn_idx);
4722 		return 0;
4723 	}
4724 
4725 	/* jump table data relocation */
4726 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4727 		reloc_desc->type = RELO_INSN_ARRAY;
4728 		reloc_desc->insn_idx = insn_idx;
4729 		reloc_desc->map_idx = -1;
4730 		reloc_desc->sym_off = sym->st_value;
4731 		reloc_desc->sym_size = sym->st_size;
4732 		return 0;
4733 	}
4734 
4735 	/* generic map reference relocation */
4736 	if (type == LIBBPF_MAP_UNSPEC) {
4737 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4738 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4739 				prog->name, sym_name, sym_sec_name);
4740 			return -LIBBPF_ERRNO__RELOC;
4741 		}
4742 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4743 			map = &obj->maps[map_idx];
4744 			if (map->libbpf_type != type ||
4745 			    map->sec_idx != sym->st_shndx ||
4746 			    map->sec_offset != sym->st_value)
4747 				continue;
4748 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4749 				 prog->name, map_idx, map->name, map->sec_idx,
4750 				 map->sec_offset, insn_idx);
4751 			break;
4752 		}
4753 		if (map_idx >= nr_maps) {
4754 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4755 				prog->name, sym_sec_name, (size_t)sym->st_value);
4756 			return -LIBBPF_ERRNO__RELOC;
4757 		}
4758 		reloc_desc->type = RELO_LD64;
4759 		reloc_desc->insn_idx = insn_idx;
4760 		reloc_desc->map_idx = map_idx;
4761 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4762 		return 0;
4763 	}
4764 
4765 	/* global data map relocation */
4766 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4767 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4768 			prog->name, sym_sec_name);
4769 		return -LIBBPF_ERRNO__RELOC;
4770 	}
4771 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4772 		map = &obj->maps[map_idx];
4773 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4774 			continue;
4775 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4776 			 prog->name, map_idx, map->name, map->sec_idx,
4777 			 map->sec_offset, insn_idx);
4778 		break;
4779 	}
4780 	if (map_idx >= nr_maps) {
4781 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4782 			prog->name, sym_sec_name);
4783 		return -LIBBPF_ERRNO__RELOC;
4784 	}
4785 
4786 	reloc_desc->type = RELO_DATA;
4787 	reloc_desc->insn_idx = insn_idx;
4788 	reloc_desc->map_idx = map_idx;
4789 	reloc_desc->sym_off = sym->st_value;
4790 	return 0;
4791 }
4792 
4793 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4794 {
4795 	return insn_idx >= prog->sec_insn_off &&
4796 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4797 }
4798 
4799 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4800 						 size_t sec_idx, size_t insn_idx)
4801 {
4802 	int l = 0, r = obj->nr_programs - 1, m;
4803 	struct bpf_program *prog;
4804 
4805 	if (!obj->nr_programs)
4806 		return NULL;
4807 
4808 	while (l < r) {
4809 		m = l + (r - l + 1) / 2;
4810 		prog = &obj->programs[m];
4811 
4812 		if (prog->sec_idx < sec_idx ||
4813 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4814 			l = m;
4815 		else
4816 			r = m - 1;
4817 	}
4818 	/* matching program could be at index l, but it still might be the
4819 	 * wrong one, so we need to double check conditions for the last time
4820 	 */
4821 	prog = &obj->programs[l];
4822 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4823 		return prog;
4824 	return NULL;
4825 }
4826 
4827 static int
4828 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4829 {
4830 	const char *relo_sec_name, *sec_name;
4831 	size_t sec_idx = shdr->sh_info, sym_idx;
4832 	struct bpf_program *prog;
4833 	struct reloc_desc *relos;
4834 	int err, i, nrels;
4835 	const char *sym_name;
4836 	__u32 insn_idx;
4837 	Elf_Scn *scn;
4838 	Elf_Data *scn_data;
4839 	Elf64_Sym *sym;
4840 	Elf64_Rel *rel;
4841 
4842 	if (sec_idx >= obj->efile.sec_cnt)
4843 		return -EINVAL;
4844 
4845 	scn = elf_sec_by_idx(obj, sec_idx);
4846 	scn_data = elf_sec_data(obj, scn);
4847 	if (!scn_data)
4848 		return -LIBBPF_ERRNO__FORMAT;
4849 
4850 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4851 	sec_name = elf_sec_name(obj, scn);
4852 	if (!relo_sec_name || !sec_name)
4853 		return -EINVAL;
4854 
4855 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4856 		 relo_sec_name, sec_idx, sec_name);
4857 	nrels = shdr->sh_size / shdr->sh_entsize;
4858 
4859 	for (i = 0; i < nrels; i++) {
4860 		rel = elf_rel_by_idx(data, i);
4861 		if (!rel) {
4862 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4863 			return -LIBBPF_ERRNO__FORMAT;
4864 		}
4865 
4866 		sym_idx = ELF64_R_SYM(rel->r_info);
4867 		sym = elf_sym_by_idx(obj, sym_idx);
4868 		if (!sym) {
4869 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4870 				relo_sec_name, sym_idx, i);
4871 			return -LIBBPF_ERRNO__FORMAT;
4872 		}
4873 
4874 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4875 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4876 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4877 			return -LIBBPF_ERRNO__FORMAT;
4878 		}
4879 
4880 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4881 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4882 				relo_sec_name, (size_t)rel->r_offset, i);
4883 			return -LIBBPF_ERRNO__FORMAT;
4884 		}
4885 
4886 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4887 		/* relocations against static functions are recorded as
4888 		 * relocations against the section that contains a function;
4889 		 * in such case, symbol will be STT_SECTION and sym.st_name
4890 		 * will point to empty string (0), so fetch section name
4891 		 * instead
4892 		 */
4893 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4894 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4895 		else
4896 			sym_name = elf_sym_str(obj, sym->st_name);
4897 		sym_name = sym_name ?: "<?";
4898 
4899 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4900 			 relo_sec_name, i, insn_idx, sym_name);
4901 
4902 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4903 		if (!prog) {
4904 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4905 				relo_sec_name, i, sec_name, insn_idx);
4906 			continue;
4907 		}
4908 
4909 		relos = libbpf_reallocarray(prog->reloc_desc,
4910 					    prog->nr_reloc + 1, sizeof(*relos));
4911 		if (!relos)
4912 			return -ENOMEM;
4913 		prog->reloc_desc = relos;
4914 
4915 		/* adjust insn_idx to local BPF program frame of reference */
4916 		insn_idx -= prog->sec_insn_off;
4917 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4918 						insn_idx, sym_name, sym, rel);
4919 		if (err)
4920 			return err;
4921 
4922 		prog->nr_reloc++;
4923 	}
4924 	return 0;
4925 }
4926 
4927 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4928 {
4929 	int id;
4930 
4931 	if (!obj->btf)
4932 		return -ENOENT;
4933 
4934 	/* if it's BTF-defined map, we don't need to search for type IDs.
4935 	 * For struct_ops map, it does not need btf_key_type_id and
4936 	 * btf_value_type_id.
4937 	 */
4938 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4939 		return 0;
4940 
4941 	/*
4942 	 * LLVM annotates global data differently in BTF, that is,
4943 	 * only as '.data', '.bss' or '.rodata'.
4944 	 */
4945 	if (!bpf_map__is_internal(map))
4946 		return -ENOENT;
4947 
4948 	id = btf__find_by_name(obj->btf, map->real_name);
4949 	if (id < 0)
4950 		return id;
4951 
4952 	map->btf_key_type_id = 0;
4953 	map->btf_value_type_id = id;
4954 	return 0;
4955 }
4956 
4957 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4958 {
4959 	char file[PATH_MAX], buff[4096];
4960 	FILE *fp;
4961 	__u32 val;
4962 	int err;
4963 
4964 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4965 	memset(info, 0, sizeof(*info));
4966 
4967 	fp = fopen(file, "re");
4968 	if (!fp) {
4969 		err = -errno;
4970 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4971 			errstr(err));
4972 		return err;
4973 	}
4974 
4975 	while (fgets(buff, sizeof(buff), fp)) {
4976 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4977 			info->type = val;
4978 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4979 			info->key_size = val;
4980 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4981 			info->value_size = val;
4982 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4983 			info->max_entries = val;
4984 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4985 			info->map_flags = val;
4986 	}
4987 
4988 	fclose(fp);
4989 
4990 	return 0;
4991 }
4992 
4993 static bool map_is_created(const struct bpf_map *map)
4994 {
4995 	return map->obj->state >= OBJ_PREPARED || map->reused;
4996 }
4997 
4998 bool bpf_map__autocreate(const struct bpf_map *map)
4999 {
5000 	return map->autocreate;
5001 }
5002 
5003 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5004 {
5005 	if (map_is_created(map))
5006 		return libbpf_err(-EBUSY);
5007 
5008 	map->autocreate = autocreate;
5009 	return 0;
5010 }
5011 
5012 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5013 {
5014 	if (!bpf_map__is_struct_ops(map))
5015 		return libbpf_err(-EINVAL);
5016 
5017 	map->autoattach = autoattach;
5018 	return 0;
5019 }
5020 
5021 bool bpf_map__autoattach(const struct bpf_map *map)
5022 {
5023 	return map->autoattach;
5024 }
5025 
5026 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5027 {
5028 	struct bpf_map_info info;
5029 	__u32 len = sizeof(info), name_len;
5030 	int new_fd, err;
5031 	char *new_name;
5032 
5033 	memset(&info, 0, len);
5034 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5035 	if (err && errno == EINVAL)
5036 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5037 	if (err)
5038 		return libbpf_err(err);
5039 
5040 	name_len = strlen(info.name);
5041 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5042 		new_name = strdup(map->name);
5043 	else
5044 		new_name = strdup(info.name);
5045 
5046 	if (!new_name)
5047 		return libbpf_err(-errno);
5048 
5049 	/*
5050 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5051 	 * This is similar to what we do in ensure_good_fd(), but without
5052 	 * closing original FD.
5053 	 */
5054 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5055 	if (new_fd < 0) {
5056 		err = -errno;
5057 		goto err_free_new_name;
5058 	}
5059 
5060 	err = reuse_fd(map->fd, new_fd);
5061 	if (err)
5062 		goto err_free_new_name;
5063 
5064 	free(map->name);
5065 
5066 	map->name = new_name;
5067 	map->def.type = info.type;
5068 	map->def.key_size = info.key_size;
5069 	map->def.value_size = info.value_size;
5070 	map->def.max_entries = info.max_entries;
5071 	map->def.map_flags = info.map_flags;
5072 	map->btf_key_type_id = info.btf_key_type_id;
5073 	map->btf_value_type_id = info.btf_value_type_id;
5074 	map->reused = true;
5075 	map->map_extra = info.map_extra;
5076 
5077 	return 0;
5078 
5079 err_free_new_name:
5080 	free(new_name);
5081 	return libbpf_err(err);
5082 }
5083 
5084 __u32 bpf_map__max_entries(const struct bpf_map *map)
5085 {
5086 	return map->def.max_entries;
5087 }
5088 
5089 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5090 {
5091 	if (!bpf_map_type__is_map_in_map(map->def.type))
5092 		return errno = EINVAL, NULL;
5093 
5094 	return map->inner_map;
5095 }
5096 
5097 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5098 {
5099 	if (map_is_created(map))
5100 		return libbpf_err(-EBUSY);
5101 
5102 	map->def.max_entries = max_entries;
5103 
5104 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5105 	if (map_is_ringbuf(map))
5106 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5107 
5108 	return 0;
5109 }
5110 
5111 static int bpf_object_prepare_token(struct bpf_object *obj)
5112 {
5113 	const char *bpffs_path;
5114 	int bpffs_fd = -1, token_fd, err;
5115 	bool mandatory;
5116 	enum libbpf_print_level level;
5117 
5118 	/* token is explicitly prevented */
5119 	if (obj->token_path && obj->token_path[0] == '\0') {
5120 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5121 		return 0;
5122 	}
5123 
5124 	mandatory = obj->token_path != NULL;
5125 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5126 
5127 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5128 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5129 	if (bpffs_fd < 0) {
5130 		err = -errno;
5131 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5132 		     obj->name, errstr(err), bpffs_path,
5133 		     mandatory ? "" : ", skipping optional step...");
5134 		return mandatory ? err : 0;
5135 	}
5136 
5137 	token_fd = bpf_token_create(bpffs_fd, 0);
5138 	close(bpffs_fd);
5139 	if (token_fd < 0) {
5140 		if (!mandatory && token_fd == -ENOENT) {
5141 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5142 				 obj->name, bpffs_path);
5143 			return 0;
5144 		}
5145 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5146 		     obj->name, token_fd, bpffs_path,
5147 		     mandatory ? "" : ", skipping optional step...");
5148 		return mandatory ? token_fd : 0;
5149 	}
5150 
5151 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5152 	if (!obj->feat_cache) {
5153 		close(token_fd);
5154 		return -ENOMEM;
5155 	}
5156 
5157 	obj->token_fd = token_fd;
5158 	obj->feat_cache->token_fd = token_fd;
5159 
5160 	return 0;
5161 }
5162 
5163 static int
5164 bpf_object__probe_loading(struct bpf_object *obj)
5165 {
5166 	struct bpf_insn insns[] = {
5167 		BPF_MOV64_IMM(BPF_REG_0, 0),
5168 		BPF_EXIT_INSN(),
5169 	};
5170 	int ret, insn_cnt = ARRAY_SIZE(insns);
5171 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5172 		.token_fd = obj->token_fd,
5173 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5174 	);
5175 
5176 	if (obj->gen_loader)
5177 		return 0;
5178 
5179 	ret = bump_rlimit_memlock();
5180 	if (ret)
5181 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5182 			errstr(ret));
5183 
5184 	/* make sure basic loading works */
5185 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5186 	if (ret < 0)
5187 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5188 	if (ret < 0) {
5189 		ret = errno;
5190 		pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
5191 			__func__, errstr(ret));
5192 		return -ret;
5193 	}
5194 	close(ret);
5195 
5196 	return 0;
5197 }
5198 
5199 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5200 {
5201 	if (obj->gen_loader)
5202 		/* To generate loader program assume the latest kernel
5203 		 * to avoid doing extra prog_load, map_create syscalls.
5204 		 */
5205 		return true;
5206 
5207 	if (obj->feat_cache)
5208 		return feat_supported(obj->feat_cache, feat_id);
5209 
5210 	return feat_supported(NULL, feat_id);
5211 }
5212 
5213 /* Used in testing to simulate missing features. */
5214 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5215 {
5216 	if (obj->feat_cache)
5217 		free(obj->feat_cache);
5218 	obj->feat_cache = cache;
5219 }
5220 
5221 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5222 {
5223 	struct bpf_map_info map_info;
5224 	__u32 map_info_len = sizeof(map_info);
5225 	int err;
5226 
5227 	memset(&map_info, 0, map_info_len);
5228 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5229 	if (err && errno == EINVAL)
5230 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5231 	if (err) {
5232 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5233 			errstr(err));
5234 		return false;
5235 	}
5236 
5237 	/*
5238 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5239 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5240 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5241 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5242 	 * existing DEVMAP.
5243 	 */
5244 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5245 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5246 
5247 	return (map_info.type == map->def.type &&
5248 		map_info.key_size == map->def.key_size &&
5249 		map_info.value_size == map->def.value_size &&
5250 		map_info.max_entries == map->def.max_entries &&
5251 		map_info.map_flags == map->def.map_flags &&
5252 		map_info.map_extra == map->map_extra);
5253 }
5254 
5255 static int
5256 bpf_object__reuse_map(struct bpf_map *map)
5257 {
5258 	int err, pin_fd;
5259 
5260 	pin_fd = bpf_obj_get(map->pin_path);
5261 	if (pin_fd < 0) {
5262 		err = -errno;
5263 		if (err == -ENOENT) {
5264 			pr_debug("found no pinned map to reuse at '%s'\n",
5265 				 map->pin_path);
5266 			return 0;
5267 		}
5268 
5269 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5270 			map->pin_path, errstr(err));
5271 		return err;
5272 	}
5273 
5274 	if (!map_is_reuse_compat(map, pin_fd)) {
5275 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5276 			map->pin_path);
5277 		close(pin_fd);
5278 		return -EINVAL;
5279 	}
5280 
5281 	err = bpf_map__reuse_fd(map, pin_fd);
5282 	close(pin_fd);
5283 	if (err)
5284 		return err;
5285 
5286 	map->pinned = true;
5287 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5288 
5289 	return 0;
5290 }
5291 
5292 static int
5293 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5294 {
5295 	enum libbpf_map_type map_type = map->libbpf_type;
5296 	int err, zero = 0;
5297 	size_t mmap_sz;
5298 
5299 	if (obj->gen_loader) {
5300 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5301 					 map->mmaped, map->def.value_size);
5302 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5303 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5304 		return 0;
5305 	}
5306 
5307 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5308 	if (err) {
5309 		err = -errno;
5310 		pr_warn("map '%s': failed to set initial contents: %s\n",
5311 			bpf_map__name(map), errstr(err));
5312 		return err;
5313 	}
5314 
5315 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5316 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5317 		err = bpf_map_freeze(map->fd);
5318 		if (err) {
5319 			err = -errno;
5320 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5321 				bpf_map__name(map), errstr(err));
5322 			return err;
5323 		}
5324 	}
5325 
5326 	/* Remap anonymous mmap()-ed "map initialization image" as
5327 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5328 	 * memory address. This will cause kernel to change process'
5329 	 * page table to point to a different piece of kernel memory,
5330 	 * but from userspace point of view memory address (and its
5331 	 * contents, being identical at this point) will stay the
5332 	 * same. This mapping will be released by bpf_object__close()
5333 	 * as per normal clean up procedure.
5334 	 */
5335 	mmap_sz = bpf_map_mmap_sz(map);
5336 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5337 		void *mmaped;
5338 		int prot;
5339 
5340 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5341 			prot = PROT_READ;
5342 		else
5343 			prot = PROT_READ | PROT_WRITE;
5344 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5345 		if (mmaped == MAP_FAILED) {
5346 			err = -errno;
5347 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5348 				bpf_map__name(map), errstr(err));
5349 			return err;
5350 		}
5351 		map->mmaped = mmaped;
5352 	} else if (map->mmaped) {
5353 		munmap(map->mmaped, mmap_sz);
5354 		map->mmaped = NULL;
5355 	}
5356 
5357 	return 0;
5358 }
5359 
5360 static void bpf_map__destroy(struct bpf_map *map);
5361 
5362 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5363 {
5364 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5365 	struct bpf_map_def *def = &map->def;
5366 	const char *map_name = NULL;
5367 	int err = 0, map_fd;
5368 
5369 	if (kernel_supports(obj, FEAT_PROG_NAME))
5370 		map_name = map->name;
5371 	create_attr.map_ifindex = map->map_ifindex;
5372 	create_attr.map_flags = def->map_flags;
5373 	create_attr.numa_node = map->numa_node;
5374 	create_attr.map_extra = map->map_extra;
5375 	create_attr.token_fd = obj->token_fd;
5376 	if (obj->token_fd)
5377 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5378 	if (map->excl_prog) {
5379 		err = bpf_prog_compute_hash(map->excl_prog);
5380 		if (err)
5381 			return err;
5382 
5383 		create_attr.excl_prog_hash = map->excl_prog->hash;
5384 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5385 	}
5386 
5387 	if (bpf_map__is_struct_ops(map)) {
5388 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5389 		if (map->mod_btf_fd >= 0) {
5390 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5391 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5392 		}
5393 	}
5394 
5395 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5396 		create_attr.btf_fd = btf__fd(obj->btf);
5397 		create_attr.btf_key_type_id = map->btf_key_type_id;
5398 		create_attr.btf_value_type_id = map->btf_value_type_id;
5399 	}
5400 
5401 	if (bpf_map_type__is_map_in_map(def->type)) {
5402 		if (map->inner_map) {
5403 			err = map_set_def_max_entries(map->inner_map);
5404 			if (err)
5405 				return err;
5406 			err = bpf_object__create_map(obj, map->inner_map, true);
5407 			if (err) {
5408 				pr_warn("map '%s': failed to create inner map: %s\n",
5409 					map->name, errstr(err));
5410 				return err;
5411 			}
5412 			map->inner_map_fd = map->inner_map->fd;
5413 		}
5414 		if (map->inner_map_fd >= 0)
5415 			create_attr.inner_map_fd = map->inner_map_fd;
5416 	}
5417 
5418 	switch (def->type) {
5419 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5420 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5421 	case BPF_MAP_TYPE_STACK_TRACE:
5422 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5423 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5424 	case BPF_MAP_TYPE_DEVMAP:
5425 	case BPF_MAP_TYPE_DEVMAP_HASH:
5426 	case BPF_MAP_TYPE_CPUMAP:
5427 	case BPF_MAP_TYPE_XSKMAP:
5428 	case BPF_MAP_TYPE_SOCKMAP:
5429 	case BPF_MAP_TYPE_SOCKHASH:
5430 	case BPF_MAP_TYPE_QUEUE:
5431 	case BPF_MAP_TYPE_STACK:
5432 	case BPF_MAP_TYPE_ARENA:
5433 		create_attr.btf_fd = 0;
5434 		create_attr.btf_key_type_id = 0;
5435 		create_attr.btf_value_type_id = 0;
5436 		map->btf_key_type_id = 0;
5437 		map->btf_value_type_id = 0;
5438 		break;
5439 	case BPF_MAP_TYPE_STRUCT_OPS:
5440 		create_attr.btf_value_type_id = 0;
5441 		break;
5442 	default:
5443 		break;
5444 	}
5445 
5446 	if (obj->gen_loader) {
5447 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5448 				    def->key_size, def->value_size, def->max_entries,
5449 				    &create_attr, is_inner ? -1 : map - obj->maps);
5450 		/* We keep pretenting we have valid FD to pass various fd >= 0
5451 		 * checks by just keeping original placeholder FDs in place.
5452 		 * See bpf_object__add_map() comment.
5453 		 * This placeholder fd will not be used with any syscall and
5454 		 * will be reset to -1 eventually.
5455 		 */
5456 		map_fd = map->fd;
5457 	} else {
5458 		map_fd = bpf_map_create(def->type, map_name,
5459 					def->key_size, def->value_size,
5460 					def->max_entries, &create_attr);
5461 	}
5462 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5463 		err = -errno;
5464 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5465 			map->name, errstr(err));
5466 		create_attr.btf_fd = 0;
5467 		create_attr.btf_key_type_id = 0;
5468 		create_attr.btf_value_type_id = 0;
5469 		map->btf_key_type_id = 0;
5470 		map->btf_value_type_id = 0;
5471 		map_fd = bpf_map_create(def->type, map_name,
5472 					def->key_size, def->value_size,
5473 					def->max_entries, &create_attr);
5474 	}
5475 
5476 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5477 		if (obj->gen_loader)
5478 			map->inner_map->fd = -1;
5479 		bpf_map__destroy(map->inner_map);
5480 		zfree(&map->inner_map);
5481 	}
5482 
5483 	if (map_fd < 0)
5484 		return map_fd;
5485 
5486 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5487 	if (map->fd == map_fd)
5488 		return 0;
5489 
5490 	/* Keep placeholder FD value but now point it to the BPF map object.
5491 	 * This way everything that relied on this map's FD (e.g., relocated
5492 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5493 	 * map->fd stays valid but now point to what map_fd points to.
5494 	 */
5495 	return reuse_fd(map->fd, map_fd);
5496 }
5497 
5498 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5499 {
5500 	const struct bpf_map *targ_map;
5501 	unsigned int i;
5502 	int fd, err = 0;
5503 
5504 	for (i = 0; i < map->init_slots_sz; i++) {
5505 		if (!map->init_slots[i])
5506 			continue;
5507 
5508 		targ_map = map->init_slots[i];
5509 		fd = targ_map->fd;
5510 
5511 		if (obj->gen_loader) {
5512 			bpf_gen__populate_outer_map(obj->gen_loader,
5513 						    map - obj->maps, i,
5514 						    targ_map - obj->maps);
5515 		} else {
5516 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5517 		}
5518 		if (err) {
5519 			err = -errno;
5520 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5521 				map->name, i, targ_map->name, fd, errstr(err));
5522 			return err;
5523 		}
5524 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5525 			 map->name, i, targ_map->name, fd);
5526 	}
5527 
5528 	zfree(&map->init_slots);
5529 	map->init_slots_sz = 0;
5530 
5531 	return 0;
5532 }
5533 
5534 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5535 {
5536 	const struct bpf_program *targ_prog;
5537 	unsigned int i;
5538 	int fd, err;
5539 
5540 	if (obj->gen_loader)
5541 		return -ENOTSUP;
5542 
5543 	for (i = 0; i < map->init_slots_sz; i++) {
5544 		if (!map->init_slots[i])
5545 			continue;
5546 
5547 		targ_prog = map->init_slots[i];
5548 		fd = bpf_program__fd(targ_prog);
5549 
5550 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5551 		if (err) {
5552 			err = -errno;
5553 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5554 				map->name, i, targ_prog->name, fd, errstr(err));
5555 			return err;
5556 		}
5557 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5558 			 map->name, i, targ_prog->name, fd);
5559 	}
5560 
5561 	zfree(&map->init_slots);
5562 	map->init_slots_sz = 0;
5563 
5564 	return 0;
5565 }
5566 
5567 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5568 {
5569 	struct bpf_map *map;
5570 	int i, err;
5571 
5572 	for (i = 0; i < obj->nr_maps; i++) {
5573 		map = &obj->maps[i];
5574 
5575 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5576 			continue;
5577 
5578 		err = init_prog_array_slots(obj, map);
5579 		if (err < 0)
5580 			return err;
5581 	}
5582 	return 0;
5583 }
5584 
5585 static int map_set_def_max_entries(struct bpf_map *map)
5586 {
5587 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5588 		int nr_cpus;
5589 
5590 		nr_cpus = libbpf_num_possible_cpus();
5591 		if (nr_cpus < 0) {
5592 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5593 				map->name, nr_cpus);
5594 			return nr_cpus;
5595 		}
5596 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5597 		map->def.max_entries = nr_cpus;
5598 	}
5599 
5600 	return 0;
5601 }
5602 
5603 static int
5604 bpf_object__create_maps(struct bpf_object *obj)
5605 {
5606 	struct bpf_map *map;
5607 	unsigned int i, j;
5608 	int err;
5609 	bool retried;
5610 
5611 	for (i = 0; i < obj->nr_maps; i++) {
5612 		map = &obj->maps[i];
5613 
5614 		/* To support old kernels, we skip creating global data maps
5615 		 * (.rodata, .data, .kconfig, etc); later on, during program
5616 		 * loading, if we detect that at least one of the to-be-loaded
5617 		 * programs is referencing any global data map, we'll error
5618 		 * out with program name and relocation index logged.
5619 		 * This approach allows to accommodate Clang emitting
5620 		 * unnecessary .rodata.str1.1 sections for string literals,
5621 		 * but also it allows to have CO-RE applications that use
5622 		 * global variables in some of BPF programs, but not others.
5623 		 * If those global variable-using programs are not loaded at
5624 		 * runtime due to bpf_program__set_autoload(prog, false),
5625 		 * bpf_object loading will succeed just fine even on old
5626 		 * kernels.
5627 		 */
5628 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5629 			map->autocreate = false;
5630 
5631 		if (!map->autocreate) {
5632 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5633 			continue;
5634 		}
5635 
5636 		err = map_set_def_max_entries(map);
5637 		if (err)
5638 			goto err_out;
5639 
5640 		retried = false;
5641 retry:
5642 		if (map->pin_path) {
5643 			err = bpf_object__reuse_map(map);
5644 			if (err) {
5645 				pr_warn("map '%s': error reusing pinned map\n",
5646 					map->name);
5647 				goto err_out;
5648 			}
5649 			if (retried && map->fd < 0) {
5650 				pr_warn("map '%s': cannot find pinned map\n",
5651 					map->name);
5652 				err = -ENOENT;
5653 				goto err_out;
5654 			}
5655 		}
5656 
5657 		if (map->reused) {
5658 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5659 				 map->name, map->fd);
5660 		} else {
5661 			err = bpf_object__create_map(obj, map, false);
5662 			if (err)
5663 				goto err_out;
5664 
5665 			pr_debug("map '%s': created successfully, fd=%d\n",
5666 				 map->name, map->fd);
5667 
5668 			if (bpf_map__is_internal(map)) {
5669 				err = bpf_object__populate_internal_map(obj, map);
5670 				if (err < 0)
5671 					goto err_out;
5672 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5673 				map->mmaped = mmap((void *)(long)map->map_extra,
5674 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5675 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5676 						   map->fd, 0);
5677 				if (map->mmaped == MAP_FAILED) {
5678 					err = -errno;
5679 					map->mmaped = NULL;
5680 					pr_warn("map '%s': failed to mmap arena: %s\n",
5681 						map->name, errstr(err));
5682 					return err;
5683 				}
5684 				if (obj->arena_data) {
5685 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5686 						obj->arena_data_sz);
5687 					zfree(&obj->arena_data);
5688 				}
5689 			}
5690 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5691 				err = init_map_in_map_slots(obj, map);
5692 				if (err < 0)
5693 					goto err_out;
5694 			}
5695 		}
5696 
5697 		if (map->pin_path && !map->pinned) {
5698 			err = bpf_map__pin(map, NULL);
5699 			if (err) {
5700 				if (!retried && err == -EEXIST) {
5701 					retried = true;
5702 					goto retry;
5703 				}
5704 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5705 					map->name, map->pin_path, errstr(err));
5706 				goto err_out;
5707 			}
5708 		}
5709 	}
5710 
5711 	return 0;
5712 
5713 err_out:
5714 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5715 	pr_perm_msg(err);
5716 	for (j = 0; j < i; j++)
5717 		zclose(obj->maps[j].fd);
5718 	return err;
5719 }
5720 
5721 static bool bpf_core_is_flavor_sep(const char *s)
5722 {
5723 	/* check X___Y name pattern, where X and Y are not underscores */
5724 	return s[0] != '_' &&				      /* X */
5725 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5726 	       s[4] != '_';				      /* Y */
5727 }
5728 
5729 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5730  * before last triple underscore. Struct name part after last triple
5731  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5732  */
5733 size_t bpf_core_essential_name_len(const char *name)
5734 {
5735 	size_t n = strlen(name);
5736 	int i;
5737 
5738 	for (i = n - 5; i >= 0; i--) {
5739 		if (bpf_core_is_flavor_sep(name + i))
5740 			return i + 1;
5741 	}
5742 	return n;
5743 }
5744 
5745 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5746 {
5747 	if (!cands)
5748 		return;
5749 
5750 	free(cands->cands);
5751 	free(cands);
5752 }
5753 
5754 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5755 		       size_t local_essent_len,
5756 		       const struct btf *targ_btf,
5757 		       const char *targ_btf_name,
5758 		       int targ_start_id,
5759 		       struct bpf_core_cand_list *cands)
5760 {
5761 	struct bpf_core_cand *new_cands, *cand;
5762 	const struct btf_type *t, *local_t;
5763 	const char *targ_name, *local_name;
5764 	size_t targ_essent_len;
5765 	int n, i;
5766 
5767 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5768 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5769 
5770 	n = btf__type_cnt(targ_btf);
5771 	for (i = targ_start_id; i < n; i++) {
5772 		t = btf__type_by_id(targ_btf, i);
5773 		if (!btf_kind_core_compat(t, local_t))
5774 			continue;
5775 
5776 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5777 		if (str_is_empty(targ_name))
5778 			continue;
5779 
5780 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5781 		if (targ_essent_len != local_essent_len)
5782 			continue;
5783 
5784 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5785 			continue;
5786 
5787 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5788 			 local_cand->id, btf_kind_str(local_t),
5789 			 local_name, i, btf_kind_str(t), targ_name,
5790 			 targ_btf_name);
5791 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5792 					      sizeof(*cands->cands));
5793 		if (!new_cands)
5794 			return -ENOMEM;
5795 
5796 		cand = &new_cands[cands->len];
5797 		cand->btf = targ_btf;
5798 		cand->id = i;
5799 
5800 		cands->cands = new_cands;
5801 		cands->len++;
5802 	}
5803 	return 0;
5804 }
5805 
5806 static int load_module_btfs(struct bpf_object *obj)
5807 {
5808 	struct bpf_btf_info info;
5809 	struct module_btf *mod_btf;
5810 	struct btf *btf;
5811 	char name[64];
5812 	__u32 id = 0, len;
5813 	int err, fd;
5814 
5815 	if (obj->btf_modules_loaded)
5816 		return 0;
5817 
5818 	if (obj->gen_loader)
5819 		return 0;
5820 
5821 	/* don't do this again, even if we find no module BTFs */
5822 	obj->btf_modules_loaded = true;
5823 
5824 	/* kernel too old to support module BTFs */
5825 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5826 		return 0;
5827 
5828 	while (true) {
5829 		err = bpf_btf_get_next_id(id, &id);
5830 		if (err && errno == ENOENT)
5831 			return 0;
5832 		if (err && errno == EPERM) {
5833 			pr_debug("skipping module BTFs loading, missing privileges\n");
5834 			return 0;
5835 		}
5836 		if (err) {
5837 			err = -errno;
5838 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5839 			return err;
5840 		}
5841 
5842 		fd = bpf_btf_get_fd_by_id(id);
5843 		if (fd < 0) {
5844 			if (errno == ENOENT)
5845 				continue; /* expected race: BTF was unloaded */
5846 			err = -errno;
5847 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5848 			return err;
5849 		}
5850 
5851 		len = sizeof(info);
5852 		memset(&info, 0, sizeof(info));
5853 		info.name = ptr_to_u64(name);
5854 		info.name_len = sizeof(name);
5855 
5856 		btf = NULL;
5857 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5858 		if (err) {
5859 			err = -errno;
5860 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5861 			break;
5862 		}
5863 
5864 		/* ignore non-module BTFs */
5865 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5866 			close(fd);
5867 			continue;
5868 		}
5869 
5870 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5871 		err = libbpf_get_error(btf);
5872 		if (err) {
5873 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5874 				name, id, errstr(err));
5875 			break;
5876 		}
5877 
5878 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5879 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5880 		if (err)
5881 			break;
5882 
5883 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
5884 
5885 		mod_btf->btf = btf;
5886 		mod_btf->id = id;
5887 		mod_btf->fd = fd;
5888 		mod_btf->name = strdup(name);
5889 		if (!mod_btf->name) {
5890 			err = -ENOMEM;
5891 			break;
5892 		}
5893 		obj->btf_module_cnt++;
5894 	}
5895 
5896 	if (err) {
5897 		btf__free(btf);
5898 		close(fd);
5899 	}
5900 	return err;
5901 }
5902 
5903 static struct bpf_core_cand_list *
5904 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5905 {
5906 	struct bpf_core_cand local_cand = {};
5907 	struct bpf_core_cand_list *cands;
5908 	const struct btf *main_btf;
5909 	const struct btf_type *local_t;
5910 	const char *local_name;
5911 	size_t local_essent_len;
5912 	int err, i;
5913 
5914 	local_cand.btf = local_btf;
5915 	local_cand.id = local_type_id;
5916 	local_t = btf__type_by_id(local_btf, local_type_id);
5917 	if (!local_t)
5918 		return ERR_PTR(-EINVAL);
5919 
5920 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5921 	if (str_is_empty(local_name))
5922 		return ERR_PTR(-EINVAL);
5923 	local_essent_len = bpf_core_essential_name_len(local_name);
5924 
5925 	cands = calloc(1, sizeof(*cands));
5926 	if (!cands)
5927 		return ERR_PTR(-ENOMEM);
5928 
5929 	/* Attempt to find target candidates in vmlinux BTF first */
5930 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5931 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5932 	if (err)
5933 		goto err_out;
5934 
5935 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5936 	if (cands->len)
5937 		return cands;
5938 
5939 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5940 	if (obj->btf_vmlinux_override)
5941 		return cands;
5942 
5943 	/* now look through module BTFs, trying to still find candidates */
5944 	err = load_module_btfs(obj);
5945 	if (err)
5946 		goto err_out;
5947 
5948 	for (i = 0; i < obj->btf_module_cnt; i++) {
5949 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5950 					 obj->btf_modules[i].btf,
5951 					 obj->btf_modules[i].name,
5952 					 btf__type_cnt(obj->btf_vmlinux),
5953 					 cands);
5954 		if (err)
5955 			goto err_out;
5956 	}
5957 
5958 	return cands;
5959 err_out:
5960 	bpf_core_free_cands(cands);
5961 	return ERR_PTR(err);
5962 }
5963 
5964 /* Check local and target types for compatibility. This check is used for
5965  * type-based CO-RE relocations and follow slightly different rules than
5966  * field-based relocations. This function assumes that root types were already
5967  * checked for name match. Beyond that initial root-level name check, names
5968  * are completely ignored. Compatibility rules are as follows:
5969  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5970  *     kind should match for local and target types (i.e., STRUCT is not
5971  *     compatible with UNION);
5972  *   - for ENUMs, the size is ignored;
5973  *   - for INT, size and signedness are ignored;
5974  *   - for ARRAY, dimensionality is ignored, element types are checked for
5975  *     compatibility recursively;
5976  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5977  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5978  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5979  *     number of input args and compatible return and argument types.
5980  * These rules are not set in stone and probably will be adjusted as we get
5981  * more experience with using BPF CO-RE relocations.
5982  */
5983 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5984 			      const struct btf *targ_btf, __u32 targ_id)
5985 {
5986 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5987 }
5988 
5989 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5990 			 const struct btf *targ_btf, __u32 targ_id)
5991 {
5992 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5993 }
5994 
5995 static size_t bpf_core_hash_fn(const long key, void *ctx)
5996 {
5997 	return key;
5998 }
5999 
6000 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6001 {
6002 	return k1 == k2;
6003 }
6004 
6005 static int record_relo_core(struct bpf_program *prog,
6006 			    const struct bpf_core_relo *core_relo, int insn_idx)
6007 {
6008 	struct reloc_desc *relos, *relo;
6009 
6010 	relos = libbpf_reallocarray(prog->reloc_desc,
6011 				    prog->nr_reloc + 1, sizeof(*relos));
6012 	if (!relos)
6013 		return -ENOMEM;
6014 	relo = &relos[prog->nr_reloc];
6015 	relo->type = RELO_CORE;
6016 	relo->insn_idx = insn_idx;
6017 	relo->core_relo = core_relo;
6018 	prog->reloc_desc = relos;
6019 	prog->nr_reloc++;
6020 	return 0;
6021 }
6022 
6023 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6024 {
6025 	struct reloc_desc *relo;
6026 	int i;
6027 
6028 	for (i = 0; i < prog->nr_reloc; i++) {
6029 		relo = &prog->reloc_desc[i];
6030 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6031 			continue;
6032 
6033 		return relo->core_relo;
6034 	}
6035 
6036 	return NULL;
6037 }
6038 
6039 static int bpf_core_resolve_relo(struct bpf_program *prog,
6040 				 const struct bpf_core_relo *relo,
6041 				 int relo_idx,
6042 				 const struct btf *local_btf,
6043 				 struct hashmap *cand_cache,
6044 				 struct bpf_core_relo_res *targ_res)
6045 {
6046 	struct bpf_core_spec specs_scratch[3] = {};
6047 	struct bpf_core_cand_list *cands = NULL;
6048 	const char *prog_name = prog->name;
6049 	const struct btf_type *local_type;
6050 	const char *local_name;
6051 	__u32 local_id = relo->type_id;
6052 	int err;
6053 
6054 	local_type = btf__type_by_id(local_btf, local_id);
6055 	if (!local_type)
6056 		return -EINVAL;
6057 
6058 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6059 	if (!local_name)
6060 		return -EINVAL;
6061 
6062 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6063 	    !hashmap__find(cand_cache, local_id, &cands)) {
6064 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6065 		if (IS_ERR(cands)) {
6066 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6067 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6068 				local_name, PTR_ERR(cands));
6069 			return PTR_ERR(cands);
6070 		}
6071 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6072 		if (err) {
6073 			bpf_core_free_cands(cands);
6074 			return err;
6075 		}
6076 	}
6077 
6078 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6079 				       targ_res);
6080 }
6081 
6082 static int
6083 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6084 {
6085 	const struct btf_ext_info_sec *sec;
6086 	struct bpf_core_relo_res targ_res;
6087 	const struct bpf_core_relo *rec;
6088 	const struct btf_ext_info *seg;
6089 	struct hashmap_entry *entry;
6090 	struct hashmap *cand_cache = NULL;
6091 	struct bpf_program *prog;
6092 	struct bpf_insn *insn;
6093 	const char *sec_name;
6094 	int i, err = 0, insn_idx, sec_idx, sec_num;
6095 
6096 	if (obj->btf_ext->core_relo_info.len == 0)
6097 		return 0;
6098 
6099 	if (targ_btf_path) {
6100 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6101 		err = libbpf_get_error(obj->btf_vmlinux_override);
6102 		if (err) {
6103 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6104 			return err;
6105 		}
6106 	}
6107 
6108 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6109 	if (IS_ERR(cand_cache)) {
6110 		err = PTR_ERR(cand_cache);
6111 		goto out;
6112 	}
6113 
6114 	seg = &obj->btf_ext->core_relo_info;
6115 	sec_num = 0;
6116 	for_each_btf_ext_sec(seg, sec) {
6117 		sec_idx = seg->sec_idxs[sec_num];
6118 		sec_num++;
6119 
6120 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6121 		if (str_is_empty(sec_name)) {
6122 			err = -EINVAL;
6123 			goto out;
6124 		}
6125 
6126 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6127 
6128 		for_each_btf_ext_rec(seg, sec, i, rec) {
6129 			if (rec->insn_off % BPF_INSN_SZ)
6130 				return -EINVAL;
6131 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6132 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6133 			if (!prog) {
6134 				/* When __weak subprog is "overridden" by another instance
6135 				 * of the subprog from a different object file, linker still
6136 				 * appends all the .BTF.ext info that used to belong to that
6137 				 * eliminated subprogram.
6138 				 * This is similar to what x86-64 linker does for relocations.
6139 				 * So just ignore such relocations just like we ignore
6140 				 * subprog instructions when discovering subprograms.
6141 				 */
6142 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6143 					 sec_name, i, insn_idx);
6144 				continue;
6145 			}
6146 			/* no need to apply CO-RE relocation if the program is
6147 			 * not going to be loaded
6148 			 */
6149 			if (!prog->autoload)
6150 				continue;
6151 
6152 			/* adjust insn_idx from section frame of reference to the local
6153 			 * program's frame of reference; (sub-)program code is not yet
6154 			 * relocated, so it's enough to just subtract in-section offset
6155 			 */
6156 			insn_idx = insn_idx - prog->sec_insn_off;
6157 			if (insn_idx >= prog->insns_cnt)
6158 				return -EINVAL;
6159 			insn = &prog->insns[insn_idx];
6160 
6161 			err = record_relo_core(prog, rec, insn_idx);
6162 			if (err) {
6163 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6164 					prog->name, i, errstr(err));
6165 				goto out;
6166 			}
6167 
6168 			if (prog->obj->gen_loader)
6169 				continue;
6170 
6171 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6172 			if (err) {
6173 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6174 					prog->name, i, errstr(err));
6175 				goto out;
6176 			}
6177 
6178 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6179 			if (err) {
6180 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6181 					prog->name, i, insn_idx, errstr(err));
6182 				goto out;
6183 			}
6184 		}
6185 	}
6186 
6187 out:
6188 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6189 	btf__free(obj->btf_vmlinux_override);
6190 	obj->btf_vmlinux_override = NULL;
6191 
6192 	if (!IS_ERR_OR_NULL(cand_cache)) {
6193 		hashmap__for_each_entry(cand_cache, entry, i) {
6194 			bpf_core_free_cands(entry->pvalue);
6195 		}
6196 		hashmap__free(cand_cache);
6197 	}
6198 	return err;
6199 }
6200 
6201 /* base map load ldimm64 special constant, used also for log fixup logic */
6202 #define POISON_LDIMM64_MAP_BASE 2001000000
6203 #define POISON_LDIMM64_MAP_PFX "200100"
6204 
6205 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6206 			       int insn_idx, struct bpf_insn *insn,
6207 			       int map_idx, const struct bpf_map *map)
6208 {
6209 	int i;
6210 
6211 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6212 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6213 
6214 	/* we turn single ldimm64 into two identical invalid calls */
6215 	for (i = 0; i < 2; i++) {
6216 		insn->code = BPF_JMP | BPF_CALL;
6217 		insn->dst_reg = 0;
6218 		insn->src_reg = 0;
6219 		insn->off = 0;
6220 		/* if this instruction is reachable (not a dead code),
6221 		 * verifier will complain with something like:
6222 		 * invalid func unknown#2001000123
6223 		 * where lower 123 is map index into obj->maps[] array
6224 		 */
6225 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6226 
6227 		insn++;
6228 	}
6229 }
6230 
6231 /* unresolved kfunc call special constant, used also for log fixup logic */
6232 #define POISON_CALL_KFUNC_BASE 2002000000
6233 #define POISON_CALL_KFUNC_PFX "2002"
6234 
6235 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6236 			      int insn_idx, struct bpf_insn *insn,
6237 			      int ext_idx, const struct extern_desc *ext)
6238 {
6239 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6240 		 prog->name, relo_idx, insn_idx, ext->name);
6241 
6242 	/* we turn kfunc call into invalid helper call with identifiable constant */
6243 	insn->code = BPF_JMP | BPF_CALL;
6244 	insn->dst_reg = 0;
6245 	insn->src_reg = 0;
6246 	insn->off = 0;
6247 	/* if this instruction is reachable (not a dead code),
6248 	 * verifier will complain with something like:
6249 	 * invalid func unknown#2001000123
6250 	 * where lower 123 is extern index into obj->externs[] array
6251 	 */
6252 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6253 }
6254 
6255 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6256 {
6257 	size_t i;
6258 
6259 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6260 		/*
6261 		 * This might happen that same offset is used for two different
6262 		 * programs (as jump tables can be the same). However, for
6263 		 * different programs different maps should be created.
6264 		 */
6265 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6266 		    obj->jumptable_maps[i].prog == prog)
6267 			return obj->jumptable_maps[i].fd;
6268 	}
6269 
6270 	return -ENOENT;
6271 }
6272 
6273 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6274 {
6275 	size_t cnt = obj->jumptable_map_cnt;
6276 	size_t size = sizeof(obj->jumptable_maps[0]);
6277 	void *tmp;
6278 
6279 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6280 	if (!tmp)
6281 		return -ENOMEM;
6282 
6283 	obj->jumptable_maps = tmp;
6284 	obj->jumptable_maps[cnt].prog = prog;
6285 	obj->jumptable_maps[cnt].sym_off = sym_off;
6286 	obj->jumptable_maps[cnt].fd = map_fd;
6287 	obj->jumptable_map_cnt++;
6288 
6289 	return 0;
6290 }
6291 
6292 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6293 {
6294 	int i;
6295 
6296 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6297 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6298 			return i;
6299 	}
6300 
6301 	return -1;
6302 }
6303 
6304 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6305 {
6306 	const __u32 jt_entry_size = 8;
6307 	unsigned int sym_off = relo->sym_off;
6308 	int jt_size = relo->sym_size;
6309 	__u32 max_entries = jt_size / jt_entry_size;
6310 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6311 	struct bpf_insn_array_value val = {};
6312 	int subprog_idx;
6313 	int map_fd, err;
6314 	__u64 insn_off;
6315 	__u64 *jt;
6316 	__u32 i;
6317 
6318 	map_fd = find_jt_map(obj, prog, sym_off);
6319 	if (map_fd >= 0)
6320 		return map_fd;
6321 
6322 	if (sym_off % jt_entry_size) {
6323 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6324 			sym_off, jt_entry_size);
6325 		return -EINVAL;
6326 	}
6327 
6328 	if (jt_size % jt_entry_size) {
6329 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6330 			jt_size, jt_entry_size);
6331 		return -EINVAL;
6332 	}
6333 
6334 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6335 				4, value_size, max_entries, NULL);
6336 	if (map_fd < 0)
6337 		return map_fd;
6338 
6339 	if (!obj->jumptables_data) {
6340 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6341 		err = -EINVAL;
6342 		goto err_close;
6343 	}
6344 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6345 		pr_warn("map '.jumptables': jumptables_data size is %zd, trying to access %d\n",
6346 			obj->jumptables_data_sz, sym_off + jt_size);
6347 		err = -EINVAL;
6348 		goto err_close;
6349 	}
6350 
6351 	subprog_idx = -1; /* main program */
6352 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6353 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6354 		err = -EINVAL;
6355 		goto err_close;
6356 	}
6357 	if (prog->subprogs)
6358 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6359 
6360 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6361 	for (i = 0; i < max_entries; i++) {
6362 		/*
6363 		 * The offset should be made to be relative to the beginning of
6364 		 * the main function, not the subfunction.
6365 		 */
6366 		insn_off = jt[i]/sizeof(struct bpf_insn);
6367 		if (subprog_idx >= 0) {
6368 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6369 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6370 		} else {
6371 			insn_off -= prog->sec_insn_off;
6372 		}
6373 
6374 		/*
6375 		 * LLVM-generated jump tables contain u64 records, however
6376 		 * should contain values that fit in u32.
6377 		 */
6378 		if (insn_off > UINT32_MAX) {
6379 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6380 				(long long)jt[i], sym_off + i * jt_entry_size);
6381 			err = -EINVAL;
6382 			goto err_close;
6383 		}
6384 
6385 		val.orig_off = insn_off;
6386 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6387 		if (err)
6388 			goto err_close;
6389 	}
6390 
6391 	err = bpf_map_freeze(map_fd);
6392 	if (err)
6393 		goto err_close;
6394 
6395 	err = add_jt_map(obj, prog, sym_off, map_fd);
6396 	if (err)
6397 		goto err_close;
6398 
6399 	return map_fd;
6400 
6401 err_close:
6402 	close(map_fd);
6403 	return err;
6404 }
6405 
6406 /* Relocate data references within program code:
6407  *  - map references;
6408  *  - global variable references;
6409  *  - extern references.
6410  */
6411 static int
6412 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6413 {
6414 	int i;
6415 
6416 	for (i = 0; i < prog->nr_reloc; i++) {
6417 		struct reloc_desc *relo = &prog->reloc_desc[i];
6418 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6419 		const struct bpf_map *map;
6420 		struct extern_desc *ext;
6421 
6422 		switch (relo->type) {
6423 		case RELO_LD64:
6424 			map = &obj->maps[relo->map_idx];
6425 			if (obj->gen_loader) {
6426 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6427 				insn[0].imm = relo->map_idx;
6428 			} else if (map->autocreate) {
6429 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6430 				insn[0].imm = map->fd;
6431 			} else {
6432 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6433 						   relo->map_idx, map);
6434 			}
6435 			break;
6436 		case RELO_DATA:
6437 			map = &obj->maps[relo->map_idx];
6438 			insn[1].imm = insn[0].imm + relo->sym_off;
6439 
6440 			if (relo->map_idx == obj->arena_map_idx)
6441 				insn[1].imm += obj->arena_data_off;
6442 
6443 			if (obj->gen_loader) {
6444 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6445 				insn[0].imm = relo->map_idx;
6446 			} else if (map->autocreate) {
6447 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6448 				insn[0].imm = map->fd;
6449 			} else {
6450 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6451 						   relo->map_idx, map);
6452 			}
6453 			break;
6454 		case RELO_EXTERN_LD64:
6455 			ext = &obj->externs[relo->ext_idx];
6456 			if (ext->type == EXT_KCFG) {
6457 				if (obj->gen_loader) {
6458 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6459 					insn[0].imm = obj->kconfig_map_idx;
6460 				} else {
6461 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6462 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6463 				}
6464 				insn[1].imm = ext->kcfg.data_off;
6465 			} else /* EXT_KSYM */ {
6466 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6467 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6468 					insn[0].imm = ext->ksym.kernel_btf_id;
6469 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6470 				} else { /* typeless ksyms or unresolved typed ksyms */
6471 					insn[0].imm = (__u32)ext->ksym.addr;
6472 					insn[1].imm = ext->ksym.addr >> 32;
6473 				}
6474 			}
6475 			break;
6476 		case RELO_EXTERN_CALL:
6477 			ext = &obj->externs[relo->ext_idx];
6478 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6479 			if (ext->is_set) {
6480 				insn[0].imm = ext->ksym.kernel_btf_id;
6481 				insn[0].off = ext->ksym.btf_fd_idx;
6482 			} else { /* unresolved weak kfunc call */
6483 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6484 						  relo->ext_idx, ext);
6485 			}
6486 			break;
6487 		case RELO_SUBPROG_ADDR:
6488 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6489 				pr_warn("prog '%s': relo #%d: bad insn\n",
6490 					prog->name, i);
6491 				return -EINVAL;
6492 			}
6493 			/* handled already */
6494 			break;
6495 		case RELO_CALL:
6496 			/* handled already */
6497 			break;
6498 		case RELO_CORE:
6499 			/* will be handled by bpf_program_record_relos() */
6500 			break;
6501 		case RELO_INSN_ARRAY: {
6502 			int map_fd;
6503 
6504 			map_fd = create_jt_map(obj, prog, relo);
6505 			if (map_fd < 0) {
6506 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6507 					prog->name, i, relo->sym_off);
6508 				return map_fd;
6509 			}
6510 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6511 			insn->imm = map_fd;
6512 			insn->off = 0;
6513 		}
6514 			break;
6515 		default:
6516 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6517 				prog->name, i, relo->type);
6518 			return -EINVAL;
6519 		}
6520 	}
6521 
6522 	return 0;
6523 }
6524 
6525 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6526 				    const struct bpf_program *prog,
6527 				    const struct btf_ext_info *ext_info,
6528 				    void **prog_info, __u32 *prog_rec_cnt,
6529 				    __u32 *prog_rec_sz)
6530 {
6531 	void *copy_start = NULL, *copy_end = NULL;
6532 	void *rec, *rec_end, *new_prog_info;
6533 	const struct btf_ext_info_sec *sec;
6534 	size_t old_sz, new_sz;
6535 	int i, sec_num, sec_idx, off_adj;
6536 
6537 	sec_num = 0;
6538 	for_each_btf_ext_sec(ext_info, sec) {
6539 		sec_idx = ext_info->sec_idxs[sec_num];
6540 		sec_num++;
6541 		if (prog->sec_idx != sec_idx)
6542 			continue;
6543 
6544 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6545 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6546 
6547 			if (insn_off < prog->sec_insn_off)
6548 				continue;
6549 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6550 				break;
6551 
6552 			if (!copy_start)
6553 				copy_start = rec;
6554 			copy_end = rec + ext_info->rec_size;
6555 		}
6556 
6557 		if (!copy_start)
6558 			return -ENOENT;
6559 
6560 		/* append func/line info of a given (sub-)program to the main
6561 		 * program func/line info
6562 		 */
6563 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6564 		new_sz = old_sz + (copy_end - copy_start);
6565 		new_prog_info = realloc(*prog_info, new_sz);
6566 		if (!new_prog_info)
6567 			return -ENOMEM;
6568 		*prog_info = new_prog_info;
6569 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6570 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6571 
6572 		/* Kernel instruction offsets are in units of 8-byte
6573 		 * instructions, while .BTF.ext instruction offsets generated
6574 		 * by Clang are in units of bytes. So convert Clang offsets
6575 		 * into kernel offsets and adjust offset according to program
6576 		 * relocated position.
6577 		 */
6578 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6579 		rec = new_prog_info + old_sz;
6580 		rec_end = new_prog_info + new_sz;
6581 		for (; rec < rec_end; rec += ext_info->rec_size) {
6582 			__u32 *insn_off = rec;
6583 
6584 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6585 		}
6586 		*prog_rec_sz = ext_info->rec_size;
6587 		return 0;
6588 	}
6589 
6590 	return -ENOENT;
6591 }
6592 
6593 static int
6594 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6595 			      struct bpf_program *main_prog,
6596 			      const struct bpf_program *prog)
6597 {
6598 	int err;
6599 
6600 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6601 	 * support func/line info
6602 	 */
6603 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6604 		return 0;
6605 
6606 	/* only attempt func info relocation if main program's func_info
6607 	 * relocation was successful
6608 	 */
6609 	if (main_prog != prog && !main_prog->func_info)
6610 		goto line_info;
6611 
6612 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6613 				       &main_prog->func_info,
6614 				       &main_prog->func_info_cnt,
6615 				       &main_prog->func_info_rec_size);
6616 	if (err) {
6617 		if (err != -ENOENT) {
6618 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6619 				prog->name, errstr(err));
6620 			return err;
6621 		}
6622 		if (main_prog->func_info) {
6623 			/*
6624 			 * Some info has already been found but has problem
6625 			 * in the last btf_ext reloc. Must have to error out.
6626 			 */
6627 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6628 			return err;
6629 		}
6630 		/* Have problem loading the very first info. Ignore the rest. */
6631 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6632 			prog->name);
6633 	}
6634 
6635 line_info:
6636 	/* don't relocate line info if main program's relocation failed */
6637 	if (main_prog != prog && !main_prog->line_info)
6638 		return 0;
6639 
6640 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6641 				       &main_prog->line_info,
6642 				       &main_prog->line_info_cnt,
6643 				       &main_prog->line_info_rec_size);
6644 	if (err) {
6645 		if (err != -ENOENT) {
6646 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6647 				prog->name, errstr(err));
6648 			return err;
6649 		}
6650 		if (main_prog->line_info) {
6651 			/*
6652 			 * Some info has already been found but has problem
6653 			 * in the last btf_ext reloc. Must have to error out.
6654 			 */
6655 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6656 			return err;
6657 		}
6658 		/* Have problem loading the very first info. Ignore the rest. */
6659 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6660 			prog->name);
6661 	}
6662 	return 0;
6663 }
6664 
6665 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6666 {
6667 	size_t insn_idx = *(const size_t *)key;
6668 	const struct reloc_desc *relo = elem;
6669 
6670 	if (insn_idx == relo->insn_idx)
6671 		return 0;
6672 	return insn_idx < relo->insn_idx ? -1 : 1;
6673 }
6674 
6675 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6676 {
6677 	if (!prog->nr_reloc)
6678 		return NULL;
6679 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6680 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6681 }
6682 
6683 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6684 {
6685 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6686 	struct reloc_desc *relos;
6687 	int i;
6688 
6689 	if (main_prog == subprog)
6690 		return 0;
6691 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6692 	/* if new count is zero, reallocarray can return a valid NULL result;
6693 	 * in this case the previous pointer will be freed, so we *have to*
6694 	 * reassign old pointer to the new value (even if it's NULL)
6695 	 */
6696 	if (!relos && new_cnt)
6697 		return -ENOMEM;
6698 	if (subprog->nr_reloc)
6699 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6700 		       sizeof(*relos) * subprog->nr_reloc);
6701 
6702 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6703 		relos[i].insn_idx += subprog->sub_insn_off;
6704 	/* After insn_idx adjustment the 'relos' array is still sorted
6705 	 * by insn_idx and doesn't break bsearch.
6706 	 */
6707 	main_prog->reloc_desc = relos;
6708 	main_prog->nr_reloc = new_cnt;
6709 	return 0;
6710 }
6711 
6712 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
6713 {
6714 	size_t size = sizeof(main_prog->subprogs[0]);
6715 	int cnt = main_prog->subprog_cnt;
6716 	void *tmp;
6717 
6718 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
6719 	if (!tmp)
6720 		return -ENOMEM;
6721 
6722 	main_prog->subprogs = tmp;
6723 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
6724 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
6725 	main_prog->subprog_cnt++;
6726 
6727 	return 0;
6728 }
6729 
6730 static int
6731 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6732 				struct bpf_program *subprog)
6733 {
6734 	struct bpf_insn *insns;
6735 	size_t new_cnt;
6736 	int err;
6737 
6738 	subprog->sub_insn_off = main_prog->insns_cnt;
6739 
6740 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6741 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6742 	if (!insns) {
6743 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6744 		return -ENOMEM;
6745 	}
6746 	main_prog->insns = insns;
6747 	main_prog->insns_cnt = new_cnt;
6748 
6749 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6750 	       subprog->insns_cnt * sizeof(*insns));
6751 
6752 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6753 		 main_prog->name, subprog->insns_cnt, subprog->name);
6754 
6755 	/* The subprog insns are now appended. Append its relos too. */
6756 	err = append_subprog_relos(main_prog, subprog);
6757 	if (err)
6758 		return err;
6759 
6760 	err = save_subprog_offsets(main_prog, subprog);
6761 	if (err) {
6762 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
6763 			main_prog->name, errstr(err));
6764 		return err;
6765 	}
6766 
6767 	return 0;
6768 }
6769 
6770 static int
6771 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6772 		       struct bpf_program *prog)
6773 {
6774 	size_t sub_insn_idx, insn_idx;
6775 	struct bpf_program *subprog;
6776 	struct reloc_desc *relo;
6777 	struct bpf_insn *insn;
6778 	int err;
6779 
6780 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6781 	if (err)
6782 		return err;
6783 
6784 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6785 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6786 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6787 			continue;
6788 
6789 		relo = find_prog_insn_relo(prog, insn_idx);
6790 		if (relo && relo->type == RELO_EXTERN_CALL)
6791 			/* kfunc relocations will be handled later
6792 			 * in bpf_object__relocate_data()
6793 			 */
6794 			continue;
6795 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6796 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6797 				prog->name, insn_idx, relo->type);
6798 			return -LIBBPF_ERRNO__RELOC;
6799 		}
6800 		if (relo) {
6801 			/* sub-program instruction index is a combination of
6802 			 * an offset of a symbol pointed to by relocation and
6803 			 * call instruction's imm field; for global functions,
6804 			 * call always has imm = -1, but for static functions
6805 			 * relocation is against STT_SECTION and insn->imm
6806 			 * points to a start of a static function
6807 			 *
6808 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6809 			 * the byte offset in the corresponding section.
6810 			 */
6811 			if (relo->type == RELO_CALL)
6812 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6813 			else
6814 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6815 		} else if (insn_is_pseudo_func(insn)) {
6816 			/*
6817 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6818 			 * functions are in the same section, so it shouldn't reach here.
6819 			 */
6820 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6821 				prog->name, insn_idx);
6822 			return -LIBBPF_ERRNO__RELOC;
6823 		} else {
6824 			/* if subprogram call is to a static function within
6825 			 * the same ELF section, there won't be any relocation
6826 			 * emitted, but it also means there is no additional
6827 			 * offset necessary, insns->imm is relative to
6828 			 * instruction's original position within the section
6829 			 */
6830 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6831 		}
6832 
6833 		/* we enforce that sub-programs should be in .text section */
6834 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6835 		if (!subprog) {
6836 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6837 				prog->name);
6838 			return -LIBBPF_ERRNO__RELOC;
6839 		}
6840 
6841 		/* if it's the first call instruction calling into this
6842 		 * subprogram (meaning this subprog hasn't been processed
6843 		 * yet) within the context of current main program:
6844 		 *   - append it at the end of main program's instructions blog;
6845 		 *   - process is recursively, while current program is put on hold;
6846 		 *   - if that subprogram calls some other not yet processes
6847 		 *   subprogram, same thing will happen recursively until
6848 		 *   there are no more unprocesses subprograms left to append
6849 		 *   and relocate.
6850 		 */
6851 		if (subprog->sub_insn_off == 0) {
6852 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6853 			if (err)
6854 				return err;
6855 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6856 			if (err)
6857 				return err;
6858 		}
6859 
6860 		/* main_prog->insns memory could have been re-allocated, so
6861 		 * calculate pointer again
6862 		 */
6863 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6864 		/* calculate correct instruction position within current main
6865 		 * prog; each main prog can have a different set of
6866 		 * subprograms appended (potentially in different order as
6867 		 * well), so position of any subprog can be different for
6868 		 * different main programs
6869 		 */
6870 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6871 
6872 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6873 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6874 	}
6875 
6876 	return 0;
6877 }
6878 
6879 /*
6880  * Relocate sub-program calls.
6881  *
6882  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6883  * main prog) is processed separately. For each subprog (non-entry functions,
6884  * that can be called from either entry progs or other subprogs) gets their
6885  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6886  * hasn't been yet appended and relocated within current main prog. Once its
6887  * relocated, sub_insn_off will point at the position within current main prog
6888  * where given subprog was appended. This will further be used to relocate all
6889  * the call instructions jumping into this subprog.
6890  *
6891  * We start with main program and process all call instructions. If the call
6892  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6893  * is zero), subprog instructions are appended at the end of main program's
6894  * instruction array. Then main program is "put on hold" while we recursively
6895  * process newly appended subprogram. If that subprogram calls into another
6896  * subprogram that hasn't been appended, new subprogram is appended again to
6897  * the *main* prog's instructions (subprog's instructions are always left
6898  * untouched, as they need to be in unmodified state for subsequent main progs
6899  * and subprog instructions are always sent only as part of a main prog) and
6900  * the process continues recursively. Once all the subprogs called from a main
6901  * prog or any of its subprogs are appended (and relocated), all their
6902  * positions within finalized instructions array are known, so it's easy to
6903  * rewrite call instructions with correct relative offsets, corresponding to
6904  * desired target subprog.
6905  *
6906  * Its important to realize that some subprogs might not be called from some
6907  * main prog and any of its called/used subprogs. Those will keep their
6908  * subprog->sub_insn_off as zero at all times and won't be appended to current
6909  * main prog and won't be relocated within the context of current main prog.
6910  * They might still be used from other main progs later.
6911  *
6912  * Visually this process can be shown as below. Suppose we have two main
6913  * programs mainA and mainB and BPF object contains three subprogs: subA,
6914  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6915  * subC both call subB:
6916  *
6917  *        +--------+ +-------+
6918  *        |        v v       |
6919  *     +--+---+ +--+-+-+ +---+--+
6920  *     | subA | | subB | | subC |
6921  *     +--+---+ +------+ +---+--+
6922  *        ^                  ^
6923  *        |                  |
6924  *    +---+-------+   +------+----+
6925  *    |   mainA   |   |   mainB   |
6926  *    +-----------+   +-----------+
6927  *
6928  * We'll start relocating mainA, will find subA, append it and start
6929  * processing sub A recursively:
6930  *
6931  *    +-----------+------+
6932  *    |   mainA   | subA |
6933  *    +-----------+------+
6934  *
6935  * At this point we notice that subB is used from subA, so we append it and
6936  * relocate (there are no further subcalls from subB):
6937  *
6938  *    +-----------+------+------+
6939  *    |   mainA   | subA | subB |
6940  *    +-----------+------+------+
6941  *
6942  * At this point, we relocate subA calls, then go one level up and finish with
6943  * relocatin mainA calls. mainA is done.
6944  *
6945  * For mainB process is similar but results in different order. We start with
6946  * mainB and skip subA and subB, as mainB never calls them (at least
6947  * directly), but we see subC is needed, so we append and start processing it:
6948  *
6949  *    +-----------+------+
6950  *    |   mainB   | subC |
6951  *    +-----------+------+
6952  * Now we see subC needs subB, so we go back to it, append and relocate it:
6953  *
6954  *    +-----------+------+------+
6955  *    |   mainB   | subC | subB |
6956  *    +-----------+------+------+
6957  *
6958  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6959  */
6960 static int
6961 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6962 {
6963 	struct bpf_program *subprog;
6964 	int i, err;
6965 
6966 	/* mark all subprogs as not relocated (yet) within the context of
6967 	 * current main program
6968 	 */
6969 	for (i = 0; i < obj->nr_programs; i++) {
6970 		subprog = &obj->programs[i];
6971 		if (!prog_is_subprog(obj, subprog))
6972 			continue;
6973 
6974 		subprog->sub_insn_off = 0;
6975 	}
6976 
6977 	err = bpf_object__reloc_code(obj, prog, prog);
6978 	if (err)
6979 		return err;
6980 
6981 	return 0;
6982 }
6983 
6984 static void
6985 bpf_object__free_relocs(struct bpf_object *obj)
6986 {
6987 	struct bpf_program *prog;
6988 	int i;
6989 
6990 	/* free up relocation descriptors */
6991 	for (i = 0; i < obj->nr_programs; i++) {
6992 		prog = &obj->programs[i];
6993 		zfree(&prog->reloc_desc);
6994 		prog->nr_reloc = 0;
6995 	}
6996 }
6997 
6998 static int cmp_relocs(const void *_a, const void *_b)
6999 {
7000 	const struct reloc_desc *a = _a;
7001 	const struct reloc_desc *b = _b;
7002 
7003 	if (a->insn_idx != b->insn_idx)
7004 		return a->insn_idx < b->insn_idx ? -1 : 1;
7005 
7006 	/* no two relocations should have the same insn_idx, but ... */
7007 	if (a->type != b->type)
7008 		return a->type < b->type ? -1 : 1;
7009 
7010 	return 0;
7011 }
7012 
7013 static void bpf_object__sort_relos(struct bpf_object *obj)
7014 {
7015 	int i;
7016 
7017 	for (i = 0; i < obj->nr_programs; i++) {
7018 		struct bpf_program *p = &obj->programs[i];
7019 
7020 		if (!p->nr_reloc)
7021 			continue;
7022 
7023 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7024 	}
7025 }
7026 
7027 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7028 {
7029 	const char *str = "exception_callback:";
7030 	size_t pfx_len = strlen(str);
7031 	int i, j, n;
7032 
7033 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7034 		return 0;
7035 
7036 	n = btf__type_cnt(obj->btf);
7037 	for (i = 1; i < n; i++) {
7038 		const char *name;
7039 		struct btf_type *t;
7040 
7041 		t = btf_type_by_id(obj->btf, i);
7042 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7043 			continue;
7044 
7045 		name = btf__str_by_offset(obj->btf, t->name_off);
7046 		if (strncmp(name, str, pfx_len) != 0)
7047 			continue;
7048 
7049 		t = btf_type_by_id(obj->btf, t->type);
7050 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7051 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7052 				prog->name);
7053 			return -EINVAL;
7054 		}
7055 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7056 			continue;
7057 		/* Multiple callbacks are specified for the same prog,
7058 		 * the verifier will eventually return an error for this
7059 		 * case, hence simply skip appending a subprog.
7060 		 */
7061 		if (prog->exception_cb_idx >= 0) {
7062 			prog->exception_cb_idx = -1;
7063 			break;
7064 		}
7065 
7066 		name += pfx_len;
7067 		if (str_is_empty(name)) {
7068 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7069 				prog->name);
7070 			return -EINVAL;
7071 		}
7072 
7073 		for (j = 0; j < obj->nr_programs; j++) {
7074 			struct bpf_program *subprog = &obj->programs[j];
7075 
7076 			if (!prog_is_subprog(obj, subprog))
7077 				continue;
7078 			if (strcmp(name, subprog->name) != 0)
7079 				continue;
7080 			/* Enforce non-hidden, as from verifier point of
7081 			 * view it expects global functions, whereas the
7082 			 * mark_btf_static fixes up linkage as static.
7083 			 */
7084 			if (!subprog->sym_global || subprog->mark_btf_static) {
7085 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7086 					prog->name, subprog->name);
7087 				return -EINVAL;
7088 			}
7089 			/* Let's see if we already saw a static exception callback with the same name */
7090 			if (prog->exception_cb_idx >= 0) {
7091 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7092 					prog->name, subprog->name);
7093 				return -EINVAL;
7094 			}
7095 			prog->exception_cb_idx = j;
7096 			break;
7097 		}
7098 
7099 		if (prog->exception_cb_idx >= 0)
7100 			continue;
7101 
7102 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7103 		return -ENOENT;
7104 	}
7105 
7106 	return 0;
7107 }
7108 
7109 static struct {
7110 	enum bpf_prog_type prog_type;
7111 	const char *ctx_name;
7112 } global_ctx_map[] = {
7113 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7114 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7115 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7116 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7117 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7118 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7119 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7120 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7121 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7122 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7123 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7124 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7125 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7126 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7127 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7128 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7129 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7130 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7131 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7132 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7133 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7134 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7135 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7136 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7137 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7138 	/* all other program types don't have "named" context structs */
7139 };
7140 
7141 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7142  * for below __builtin_types_compatible_p() checks;
7143  * with this approach we don't need any extra arch-specific #ifdef guards
7144  */
7145 struct pt_regs;
7146 struct user_pt_regs;
7147 struct user_regs_struct;
7148 
7149 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7150 				     const char *subprog_name, int arg_idx,
7151 				     int arg_type_id, const char *ctx_name)
7152 {
7153 	const struct btf_type *t;
7154 	const char *tname;
7155 
7156 	/* check if existing parameter already matches verifier expectations */
7157 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7158 	if (!btf_is_ptr(t))
7159 		goto out_warn;
7160 
7161 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7162 	 * and perf_event programs, so check this case early on and forget
7163 	 * about it for subsequent checks
7164 	 */
7165 	while (btf_is_mod(t))
7166 		t = btf__type_by_id(btf, t->type);
7167 	if (btf_is_typedef(t) &&
7168 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7169 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7170 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7171 			return false; /* canonical type for kprobe/perf_event */
7172 	}
7173 
7174 	/* now we can ignore typedefs moving forward */
7175 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7176 
7177 	/* if it's `void *`, definitely fix up BTF info */
7178 	if (btf_is_void(t))
7179 		return true;
7180 
7181 	/* if it's already proper canonical type, no need to fix up */
7182 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7183 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7184 		return false;
7185 
7186 	/* special cases */
7187 	switch (prog->type) {
7188 	case BPF_PROG_TYPE_KPROBE:
7189 		/* `struct pt_regs *` is expected, but we need to fix up */
7190 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7191 			return true;
7192 		break;
7193 	case BPF_PROG_TYPE_PERF_EVENT:
7194 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7195 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7196 			return true;
7197 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7198 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7199 			return true;
7200 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7201 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7202 			return true;
7203 		break;
7204 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7205 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7206 		/* allow u64* as ctx */
7207 		if (btf_is_int(t) && t->size == 8)
7208 			return true;
7209 		break;
7210 	default:
7211 		break;
7212 	}
7213 
7214 out_warn:
7215 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7216 		prog->name, subprog_name, arg_idx, ctx_name);
7217 	return false;
7218 }
7219 
7220 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7221 {
7222 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7223 	int i, err, arg_cnt, fn_name_off, linkage;
7224 	struct btf_type *fn_t, *fn_proto_t, *t;
7225 	struct btf_param *p;
7226 
7227 	/* caller already validated FUNC -> FUNC_PROTO validity */
7228 	fn_t = btf_type_by_id(btf, orig_fn_id);
7229 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7230 
7231 	/* Note that each btf__add_xxx() operation invalidates
7232 	 * all btf_type and string pointers, so we need to be
7233 	 * very careful when cloning BTF types. BTF type
7234 	 * pointers have to be always refetched. And to avoid
7235 	 * problems with invalidated string pointers, we
7236 	 * add empty strings initially, then just fix up
7237 	 * name_off offsets in place. Offsets are stable for
7238 	 * existing strings, so that works out.
7239 	 */
7240 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7241 	linkage = btf_func_linkage(fn_t);
7242 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7243 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7244 	arg_cnt = btf_vlen(fn_proto_t);
7245 
7246 	/* clone FUNC_PROTO and its params */
7247 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7248 	if (fn_proto_id < 0)
7249 		return -EINVAL;
7250 
7251 	for (i = 0; i < arg_cnt; i++) {
7252 		int name_off;
7253 
7254 		/* copy original parameter data */
7255 		t = btf_type_by_id(btf, orig_proto_id);
7256 		p = &btf_params(t)[i];
7257 		name_off = p->name_off;
7258 
7259 		err = btf__add_func_param(btf, "", p->type);
7260 		if (err)
7261 			return err;
7262 
7263 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7264 		p = &btf_params(fn_proto_t)[i];
7265 		p->name_off = name_off; /* use remembered str offset */
7266 	}
7267 
7268 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7269 	 * entry program's name as a placeholder, which we replace immediately
7270 	 * with original name_off
7271 	 */
7272 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7273 	if (fn_id < 0)
7274 		return -EINVAL;
7275 
7276 	fn_t = btf_type_by_id(btf, fn_id);
7277 	fn_t->name_off = fn_name_off; /* reuse original string */
7278 
7279 	return fn_id;
7280 }
7281 
7282 /* Check if main program or global subprog's function prototype has `arg:ctx`
7283  * argument tags, and, if necessary, substitute correct type to match what BPF
7284  * verifier would expect, taking into account specific program type. This
7285  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7286  * have a native support for it in the verifier, making user's life much
7287  * easier.
7288  */
7289 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7290 {
7291 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7292 	struct bpf_func_info_min *func_rec;
7293 	struct btf_type *fn_t, *fn_proto_t;
7294 	struct btf *btf = obj->btf;
7295 	const struct btf_type *t;
7296 	struct btf_param *p;
7297 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7298 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7299 	int *orig_ids;
7300 
7301 	/* no .BTF.ext, no problem */
7302 	if (!obj->btf_ext || !prog->func_info)
7303 		return 0;
7304 
7305 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7306 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7307 		return 0;
7308 
7309 	/* some BPF program types just don't have named context structs, so
7310 	 * this fallback mechanism doesn't work for them
7311 	 */
7312 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7313 		if (global_ctx_map[i].prog_type != prog->type)
7314 			continue;
7315 		ctx_name = global_ctx_map[i].ctx_name;
7316 		break;
7317 	}
7318 	if (!ctx_name)
7319 		return 0;
7320 
7321 	/* remember original func BTF IDs to detect if we already cloned them */
7322 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7323 	if (!orig_ids)
7324 		return -ENOMEM;
7325 	for (i = 0; i < prog->func_info_cnt; i++) {
7326 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7327 		orig_ids[i] = func_rec->type_id;
7328 	}
7329 
7330 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7331 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7332 	 * clone and adjust FUNC -> FUNC_PROTO combo
7333 	 */
7334 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7335 		/* only DECL_TAG with "arg:ctx" value are interesting */
7336 		t = btf__type_by_id(btf, i);
7337 		if (!btf_is_decl_tag(t))
7338 			continue;
7339 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7340 			continue;
7341 
7342 		/* only global funcs need adjustment, if at all */
7343 		orig_fn_id = t->type;
7344 		fn_t = btf_type_by_id(btf, orig_fn_id);
7345 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7346 			continue;
7347 
7348 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7349 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7350 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7351 			continue;
7352 
7353 		/* find corresponding func_info record */
7354 		func_rec = NULL;
7355 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7356 			if (orig_ids[rec_idx] == t->type) {
7357 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7358 				break;
7359 			}
7360 		}
7361 		/* current main program doesn't call into this subprog */
7362 		if (!func_rec)
7363 			continue;
7364 
7365 		/* some more sanity checking of DECL_TAG */
7366 		arg_cnt = btf_vlen(fn_proto_t);
7367 		arg_idx = btf_decl_tag(t)->component_idx;
7368 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7369 			continue;
7370 
7371 		/* check if we should fix up argument type */
7372 		p = &btf_params(fn_proto_t)[arg_idx];
7373 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7374 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7375 			continue;
7376 
7377 		/* clone fn/fn_proto, unless we already did it for another arg */
7378 		if (func_rec->type_id == orig_fn_id) {
7379 			int fn_id;
7380 
7381 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7382 			if (fn_id < 0) {
7383 				err = fn_id;
7384 				goto err_out;
7385 			}
7386 
7387 			/* point func_info record to a cloned FUNC type */
7388 			func_rec->type_id = fn_id;
7389 		}
7390 
7391 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7392 		 * we do it just once per main BPF program, as all global
7393 		 * funcs share the same program type, so need only PTR ->
7394 		 * STRUCT type chain
7395 		 */
7396 		if (ptr_id == 0) {
7397 			struct_id = btf__add_struct(btf, ctx_name, 0);
7398 			ptr_id = btf__add_ptr(btf, struct_id);
7399 			if (ptr_id < 0 || struct_id < 0) {
7400 				err = -EINVAL;
7401 				goto err_out;
7402 			}
7403 		}
7404 
7405 		/* for completeness, clone DECL_TAG and point it to cloned param */
7406 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7407 		if (tag_id < 0) {
7408 			err = -EINVAL;
7409 			goto err_out;
7410 		}
7411 
7412 		/* all the BTF manipulations invalidated pointers, refetch them */
7413 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7414 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7415 
7416 		/* fix up type ID pointed to by param */
7417 		p = &btf_params(fn_proto_t)[arg_idx];
7418 		p->type = ptr_id;
7419 	}
7420 
7421 	free(orig_ids);
7422 	return 0;
7423 err_out:
7424 	free(orig_ids);
7425 	return err;
7426 }
7427 
7428 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7429 {
7430 	struct bpf_program *prog;
7431 	size_t i, j;
7432 	int err;
7433 
7434 	if (obj->btf_ext) {
7435 		err = bpf_object__relocate_core(obj, targ_btf_path);
7436 		if (err) {
7437 			pr_warn("failed to perform CO-RE relocations: %s\n",
7438 				errstr(err));
7439 			return err;
7440 		}
7441 		bpf_object__sort_relos(obj);
7442 	}
7443 
7444 	/* place globals at the end of the arena (if supported) */
7445 	if (obj->arena_map_idx >= 0 && kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF)) {
7446 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7447 
7448 		obj->arena_data_off = bpf_map_mmap_sz(arena_map) -
7449 				      roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7450 	}
7451 
7452 	/* Before relocating calls pre-process relocations and mark
7453 	 * few ld_imm64 instructions that points to subprogs.
7454 	 * Otherwise bpf_object__reloc_code() later would have to consider
7455 	 * all ld_imm64 insns as relocation candidates. That would
7456 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7457 	 * would increase and most of them will fail to find a relo.
7458 	 */
7459 	for (i = 0; i < obj->nr_programs; i++) {
7460 		prog = &obj->programs[i];
7461 		for (j = 0; j < prog->nr_reloc; j++) {
7462 			struct reloc_desc *relo = &prog->reloc_desc[j];
7463 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7464 
7465 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7466 			if (relo->type == RELO_SUBPROG_ADDR)
7467 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7468 		}
7469 	}
7470 
7471 	/* relocate subprogram calls and append used subprograms to main
7472 	 * programs; each copy of subprogram code needs to be relocated
7473 	 * differently for each main program, because its code location might
7474 	 * have changed.
7475 	 * Append subprog relos to main programs to allow data relos to be
7476 	 * processed after text is completely relocated.
7477 	 */
7478 	for (i = 0; i < obj->nr_programs; i++) {
7479 		prog = &obj->programs[i];
7480 		/* sub-program's sub-calls are relocated within the context of
7481 		 * its main program only
7482 		 */
7483 		if (prog_is_subprog(obj, prog))
7484 			continue;
7485 		if (!prog->autoload)
7486 			continue;
7487 
7488 		err = bpf_object__relocate_calls(obj, prog);
7489 		if (err) {
7490 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7491 				prog->name, errstr(err));
7492 			return err;
7493 		}
7494 
7495 		err = bpf_prog_assign_exc_cb(obj, prog);
7496 		if (err)
7497 			return err;
7498 		/* Now, also append exception callback if it has not been done already. */
7499 		if (prog->exception_cb_idx >= 0) {
7500 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7501 
7502 			/* Calling exception callback directly is disallowed, which the
7503 			 * verifier will reject later. In case it was processed already,
7504 			 * we can skip this step, otherwise for all other valid cases we
7505 			 * have to append exception callback now.
7506 			 */
7507 			if (subprog->sub_insn_off == 0) {
7508 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7509 				if (err)
7510 					return err;
7511 				err = bpf_object__reloc_code(obj, prog, subprog);
7512 				if (err)
7513 					return err;
7514 			}
7515 		}
7516 	}
7517 	for (i = 0; i < obj->nr_programs; i++) {
7518 		prog = &obj->programs[i];
7519 		if (prog_is_subprog(obj, prog))
7520 			continue;
7521 		if (!prog->autoload)
7522 			continue;
7523 
7524 		/* Process data relos for main programs */
7525 		err = bpf_object__relocate_data(obj, prog);
7526 		if (err) {
7527 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7528 				prog->name, errstr(err));
7529 			return err;
7530 		}
7531 
7532 		/* Fix up .BTF.ext information, if necessary */
7533 		err = bpf_program_fixup_func_info(obj, prog);
7534 		if (err) {
7535 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7536 				prog->name, errstr(err));
7537 			return err;
7538 		}
7539 	}
7540 
7541 	return 0;
7542 }
7543 
7544 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7545 					    Elf64_Shdr *shdr, Elf_Data *data);
7546 
7547 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7548 					 Elf64_Shdr *shdr, Elf_Data *data)
7549 {
7550 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7551 	int i, j, nrels, new_sz;
7552 	const struct btf_var_secinfo *vi = NULL;
7553 	const struct btf_type *sec, *var, *def;
7554 	struct bpf_map *map = NULL, *targ_map = NULL;
7555 	struct bpf_program *targ_prog = NULL;
7556 	bool is_prog_array, is_map_in_map;
7557 	const struct btf_member *member;
7558 	const char *name, *mname, *type;
7559 	unsigned int moff;
7560 	Elf64_Sym *sym;
7561 	Elf64_Rel *rel;
7562 	void *tmp;
7563 
7564 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7565 		return -EINVAL;
7566 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7567 	if (!sec)
7568 		return -EINVAL;
7569 
7570 	nrels = shdr->sh_size / shdr->sh_entsize;
7571 	for (i = 0; i < nrels; i++) {
7572 		rel = elf_rel_by_idx(data, i);
7573 		if (!rel) {
7574 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7575 			return -LIBBPF_ERRNO__FORMAT;
7576 		}
7577 
7578 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7579 		if (!sym) {
7580 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7581 				i, (size_t)ELF64_R_SYM(rel->r_info));
7582 			return -LIBBPF_ERRNO__FORMAT;
7583 		}
7584 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7585 
7586 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7587 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7588 			 (size_t)rel->r_offset, sym->st_name, name);
7589 
7590 		for (j = 0; j < obj->nr_maps; j++) {
7591 			map = &obj->maps[j];
7592 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7593 				continue;
7594 
7595 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7596 			if (vi->offset <= rel->r_offset &&
7597 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7598 				break;
7599 		}
7600 		if (j == obj->nr_maps) {
7601 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7602 				i, name, (size_t)rel->r_offset);
7603 			return -EINVAL;
7604 		}
7605 
7606 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7607 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7608 		type = is_map_in_map ? "map" : "prog";
7609 		if (is_map_in_map) {
7610 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7611 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7612 					i, name);
7613 				return -LIBBPF_ERRNO__RELOC;
7614 			}
7615 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7616 			    map->def.key_size != sizeof(int)) {
7617 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7618 					i, map->name, sizeof(int));
7619 				return -EINVAL;
7620 			}
7621 			targ_map = bpf_object__find_map_by_name(obj, name);
7622 			if (!targ_map) {
7623 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7624 					i, name);
7625 				return -ESRCH;
7626 			}
7627 		} else if (is_prog_array) {
7628 			targ_prog = bpf_object__find_program_by_name(obj, name);
7629 			if (!targ_prog) {
7630 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7631 					i, name);
7632 				return -ESRCH;
7633 			}
7634 			if (targ_prog->sec_idx != sym->st_shndx ||
7635 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7636 			    prog_is_subprog(obj, targ_prog)) {
7637 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7638 					i, name);
7639 				return -LIBBPF_ERRNO__RELOC;
7640 			}
7641 		} else {
7642 			return -EINVAL;
7643 		}
7644 
7645 		var = btf__type_by_id(obj->btf, vi->type);
7646 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7647 		if (btf_vlen(def) == 0)
7648 			return -EINVAL;
7649 		member = btf_members(def) + btf_vlen(def) - 1;
7650 		mname = btf__name_by_offset(obj->btf, member->name_off);
7651 		if (strcmp(mname, "values"))
7652 			return -EINVAL;
7653 
7654 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7655 		if (rel->r_offset - vi->offset < moff)
7656 			return -EINVAL;
7657 
7658 		moff = rel->r_offset - vi->offset - moff;
7659 		/* here we use BPF pointer size, which is always 64 bit, as we
7660 		 * are parsing ELF that was built for BPF target
7661 		 */
7662 		if (moff % bpf_ptr_sz)
7663 			return -EINVAL;
7664 		moff /= bpf_ptr_sz;
7665 		if (moff >= map->init_slots_sz) {
7666 			new_sz = moff + 1;
7667 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7668 			if (!tmp)
7669 				return -ENOMEM;
7670 			map->init_slots = tmp;
7671 			memset(map->init_slots + map->init_slots_sz, 0,
7672 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7673 			map->init_slots_sz = new_sz;
7674 		}
7675 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7676 
7677 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7678 			 i, map->name, moff, type, name);
7679 	}
7680 
7681 	return 0;
7682 }
7683 
7684 static int bpf_object__collect_relos(struct bpf_object *obj)
7685 {
7686 	int i, err;
7687 
7688 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7689 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7690 		Elf64_Shdr *shdr;
7691 		Elf_Data *data;
7692 		int idx;
7693 
7694 		if (sec_desc->sec_type != SEC_RELO)
7695 			continue;
7696 
7697 		shdr = sec_desc->shdr;
7698 		data = sec_desc->data;
7699 		idx = shdr->sh_info;
7700 
7701 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7702 			pr_warn("internal error at %d\n", __LINE__);
7703 			return -LIBBPF_ERRNO__INTERNAL;
7704 		}
7705 
7706 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7707 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7708 		else if (idx == obj->efile.btf_maps_shndx)
7709 			err = bpf_object__collect_map_relos(obj, shdr, data);
7710 		else
7711 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7712 		if (err)
7713 			return err;
7714 	}
7715 
7716 	bpf_object__sort_relos(obj);
7717 	return 0;
7718 }
7719 
7720 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7721 {
7722 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7723 	    BPF_OP(insn->code) == BPF_CALL &&
7724 	    BPF_SRC(insn->code) == BPF_K &&
7725 	    insn->src_reg == 0 &&
7726 	    insn->dst_reg == 0) {
7727 		    *func_id = insn->imm;
7728 		    return true;
7729 	}
7730 	return false;
7731 }
7732 
7733 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7734 {
7735 	struct bpf_insn *insn = prog->insns;
7736 	enum bpf_func_id func_id;
7737 	int i;
7738 
7739 	if (obj->gen_loader)
7740 		return 0;
7741 
7742 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7743 		if (!insn_is_helper_call(insn, &func_id))
7744 			continue;
7745 
7746 		/* on kernels that don't yet support
7747 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7748 		 * to bpf_probe_read() which works well for old kernels
7749 		 */
7750 		switch (func_id) {
7751 		case BPF_FUNC_probe_read_kernel:
7752 		case BPF_FUNC_probe_read_user:
7753 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7754 				insn->imm = BPF_FUNC_probe_read;
7755 			break;
7756 		case BPF_FUNC_probe_read_kernel_str:
7757 		case BPF_FUNC_probe_read_user_str:
7758 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7759 				insn->imm = BPF_FUNC_probe_read_str;
7760 			break;
7761 		default:
7762 			break;
7763 		}
7764 	}
7765 	return 0;
7766 }
7767 
7768 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7769 				     int *btf_obj_fd, int *btf_type_id);
7770 
7771 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7772 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7773 				    struct bpf_prog_load_opts *opts, long cookie)
7774 {
7775 	enum sec_def_flags def = cookie;
7776 
7777 	/* old kernels might not support specifying expected_attach_type */
7778 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7779 		opts->expected_attach_type = 0;
7780 
7781 	if (def & SEC_SLEEPABLE)
7782 		opts->prog_flags |= BPF_F_SLEEPABLE;
7783 
7784 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7785 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7786 
7787 	/* special check for usdt to use uprobe_multi link */
7788 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7789 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7790 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7791 		 * update both.
7792 		 */
7793 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7794 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7795 	}
7796 
7797 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7798 		int btf_obj_fd = 0, btf_type_id = 0, err;
7799 		const char *attach_name;
7800 
7801 		attach_name = strchr(prog->sec_name, '/');
7802 		if (!attach_name) {
7803 			/* if BPF program is annotated with just SEC("fentry")
7804 			 * (or similar) without declaratively specifying
7805 			 * target, then it is expected that target will be
7806 			 * specified with bpf_program__set_attach_target() at
7807 			 * runtime before BPF object load step. If not, then
7808 			 * there is nothing to load into the kernel as BPF
7809 			 * verifier won't be able to validate BPF program
7810 			 * correctness anyways.
7811 			 */
7812 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7813 				prog->name);
7814 			return -EINVAL;
7815 		}
7816 		attach_name++; /* skip over / */
7817 
7818 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7819 		if (err)
7820 			return err;
7821 
7822 		/* cache resolved BTF FD and BTF type ID in the prog */
7823 		prog->attach_btf_obj_fd = btf_obj_fd;
7824 		prog->attach_btf_id = btf_type_id;
7825 
7826 		/* but by now libbpf common logic is not utilizing
7827 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7828 		 * this callback is called after opts were populated by
7829 		 * libbpf, so this callback has to update opts explicitly here
7830 		 */
7831 		opts->attach_btf_obj_fd = btf_obj_fd;
7832 		opts->attach_btf_id = btf_type_id;
7833 	}
7834 	return 0;
7835 }
7836 
7837 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7838 
7839 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7840 				struct bpf_insn *insns, int insns_cnt,
7841 				const char *license, __u32 kern_version, int *prog_fd)
7842 {
7843 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7844 	const char *prog_name = NULL;
7845 	size_t log_buf_size = 0;
7846 	char *log_buf = NULL, *tmp;
7847 	bool own_log_buf = true;
7848 	__u32 log_level = prog->log_level;
7849 	int ret, err;
7850 
7851 	/* Be more helpful by rejecting programs that can't be validated early
7852 	 * with more meaningful and actionable error message.
7853 	 */
7854 	switch (prog->type) {
7855 	case BPF_PROG_TYPE_UNSPEC:
7856 		/*
7857 		 * The program type must be set.  Most likely we couldn't find a proper
7858 		 * section definition at load time, and thus we didn't infer the type.
7859 		 */
7860 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7861 			prog->name, prog->sec_name);
7862 		return -EINVAL;
7863 	case BPF_PROG_TYPE_STRUCT_OPS:
7864 		if (prog->attach_btf_id == 0) {
7865 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7866 				prog->name);
7867 			return -EINVAL;
7868 		}
7869 		break;
7870 	default:
7871 		break;
7872 	}
7873 
7874 	if (!insns || !insns_cnt)
7875 		return -EINVAL;
7876 
7877 	if (kernel_supports(obj, FEAT_PROG_NAME))
7878 		prog_name = prog->name;
7879 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7880 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7881 	load_attr.attach_btf_id = prog->attach_btf_id;
7882 	load_attr.kern_version = kern_version;
7883 	load_attr.prog_ifindex = prog->prog_ifindex;
7884 	load_attr.expected_attach_type = prog->expected_attach_type;
7885 
7886 	/* specify func_info/line_info only if kernel supports them */
7887 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7888 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7889 		load_attr.func_info = prog->func_info;
7890 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7891 		load_attr.func_info_cnt = prog->func_info_cnt;
7892 		load_attr.line_info = prog->line_info;
7893 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7894 		load_attr.line_info_cnt = prog->line_info_cnt;
7895 	}
7896 	load_attr.log_level = log_level;
7897 	load_attr.prog_flags = prog->prog_flags;
7898 	load_attr.fd_array = obj->fd_array;
7899 
7900 	load_attr.token_fd = obj->token_fd;
7901 	if (obj->token_fd)
7902 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7903 
7904 	/* adjust load_attr if sec_def provides custom preload callback */
7905 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7906 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7907 		if (err < 0) {
7908 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7909 				prog->name, errstr(err));
7910 			return err;
7911 		}
7912 		insns = prog->insns;
7913 		insns_cnt = prog->insns_cnt;
7914 	}
7915 
7916 	if (obj->gen_loader) {
7917 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7918 				   license, insns, insns_cnt, &load_attr,
7919 				   prog - obj->programs);
7920 		*prog_fd = -1;
7921 		return 0;
7922 	}
7923 
7924 retry_load:
7925 	/* if log_level is zero, we don't request logs initially even if
7926 	 * custom log_buf is specified; if the program load fails, then we'll
7927 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7928 	 * our own and retry the load to get details on what failed
7929 	 */
7930 	if (log_level) {
7931 		if (prog->log_buf) {
7932 			log_buf = prog->log_buf;
7933 			log_buf_size = prog->log_size;
7934 			own_log_buf = false;
7935 		} else if (obj->log_buf) {
7936 			log_buf = obj->log_buf;
7937 			log_buf_size = obj->log_size;
7938 			own_log_buf = false;
7939 		} else {
7940 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7941 			tmp = realloc(log_buf, log_buf_size);
7942 			if (!tmp) {
7943 				ret = -ENOMEM;
7944 				goto out;
7945 			}
7946 			log_buf = tmp;
7947 			log_buf[0] = '\0';
7948 			own_log_buf = true;
7949 		}
7950 	}
7951 
7952 	load_attr.log_buf = log_buf;
7953 	load_attr.log_size = log_buf_size;
7954 	load_attr.log_level = log_level;
7955 
7956 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7957 	if (ret >= 0) {
7958 		if (log_level && own_log_buf) {
7959 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7960 				 prog->name, log_buf);
7961 		}
7962 
7963 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7964 			struct bpf_map *map;
7965 			int i;
7966 
7967 			for (i = 0; i < obj->nr_maps; i++) {
7968 				map = &prog->obj->maps[i];
7969 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7970 					continue;
7971 
7972 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7973 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7974 						prog->name, map->real_name, errstr(errno));
7975 					/* Don't fail hard if can't bind rodata. */
7976 				}
7977 			}
7978 		}
7979 
7980 		*prog_fd = ret;
7981 		ret = 0;
7982 		goto out;
7983 	}
7984 
7985 	if (log_level == 0) {
7986 		log_level = 1;
7987 		goto retry_load;
7988 	}
7989 	/* On ENOSPC, increase log buffer size and retry, unless custom
7990 	 * log_buf is specified.
7991 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7992 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7993 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7994 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7995 	 */
7996 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7997 		goto retry_load;
7998 
7999 	ret = -errno;
8000 
8001 	/* post-process verifier log to improve error descriptions */
8002 	fixup_verifier_log(prog, log_buf, log_buf_size);
8003 
8004 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8005 	pr_perm_msg(ret);
8006 
8007 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8008 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8009 			prog->name, log_buf);
8010 	}
8011 
8012 out:
8013 	if (own_log_buf)
8014 		free(log_buf);
8015 	return ret;
8016 }
8017 
8018 static char *find_prev_line(char *buf, char *cur)
8019 {
8020 	char *p;
8021 
8022 	if (cur == buf) /* end of a log buf */
8023 		return NULL;
8024 
8025 	p = cur - 1;
8026 	while (p - 1 >= buf && *(p - 1) != '\n')
8027 		p--;
8028 
8029 	return p;
8030 }
8031 
8032 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8033 		      char *orig, size_t orig_sz, const char *patch)
8034 {
8035 	/* size of the remaining log content to the right from the to-be-replaced part */
8036 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8037 	size_t patch_sz = strlen(patch);
8038 
8039 	if (patch_sz != orig_sz) {
8040 		/* If patch line(s) are longer than original piece of verifier log,
8041 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8042 		 * starting from after to-be-replaced part of the log.
8043 		 *
8044 		 * If patch line(s) are shorter than original piece of verifier log,
8045 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8046 		 * starting from after to-be-replaced part of the log
8047 		 *
8048 		 * We need to be careful about not overflowing available
8049 		 * buf_sz capacity. If that's the case, we'll truncate the end
8050 		 * of the original log, as necessary.
8051 		 */
8052 		if (patch_sz > orig_sz) {
8053 			if (orig + patch_sz >= buf + buf_sz) {
8054 				/* patch is big enough to cover remaining space completely */
8055 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8056 				rem_sz = 0;
8057 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8058 				/* patch causes part of remaining log to be truncated */
8059 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8060 			}
8061 		}
8062 		/* shift remaining log to the right by calculated amount */
8063 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8064 	}
8065 
8066 	memcpy(orig, patch, patch_sz);
8067 }
8068 
8069 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8070 				       char *buf, size_t buf_sz, size_t log_sz,
8071 				       char *line1, char *line2, char *line3)
8072 {
8073 	/* Expected log for failed and not properly guarded CO-RE relocation:
8074 	 * line1 -> 123: (85) call unknown#195896080
8075 	 * line2 -> invalid func unknown#195896080
8076 	 * line3 -> <anything else or end of buffer>
8077 	 *
8078 	 * "123" is the index of the instruction that was poisoned. We extract
8079 	 * instruction index to find corresponding CO-RE relocation and
8080 	 * replace this part of the log with more relevant information about
8081 	 * failed CO-RE relocation.
8082 	 */
8083 	const struct bpf_core_relo *relo;
8084 	struct bpf_core_spec spec;
8085 	char patch[512], spec_buf[256];
8086 	int insn_idx, err, spec_len;
8087 
8088 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8089 		return;
8090 
8091 	relo = find_relo_core(prog, insn_idx);
8092 	if (!relo)
8093 		return;
8094 
8095 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8096 	if (err)
8097 		return;
8098 
8099 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8100 	snprintf(patch, sizeof(patch),
8101 		 "%d: <invalid CO-RE relocation>\n"
8102 		 "failed to resolve CO-RE relocation %s%s\n",
8103 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8104 
8105 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8106 }
8107 
8108 static void fixup_log_missing_map_load(struct bpf_program *prog,
8109 				       char *buf, size_t buf_sz, size_t log_sz,
8110 				       char *line1, char *line2, char *line3)
8111 {
8112 	/* Expected log for failed and not properly guarded map reference:
8113 	 * line1 -> 123: (85) call unknown#2001000345
8114 	 * line2 -> invalid func unknown#2001000345
8115 	 * line3 -> <anything else or end of buffer>
8116 	 *
8117 	 * "123" is the index of the instruction that was poisoned.
8118 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8119 	 */
8120 	struct bpf_object *obj = prog->obj;
8121 	const struct bpf_map *map;
8122 	int insn_idx, map_idx;
8123 	char patch[128];
8124 
8125 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8126 		return;
8127 
8128 	map_idx -= POISON_LDIMM64_MAP_BASE;
8129 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8130 		return;
8131 	map = &obj->maps[map_idx];
8132 
8133 	snprintf(patch, sizeof(patch),
8134 		 "%d: <invalid BPF map reference>\n"
8135 		 "BPF map '%s' is referenced but wasn't created\n",
8136 		 insn_idx, map->name);
8137 
8138 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8139 }
8140 
8141 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8142 					 char *buf, size_t buf_sz, size_t log_sz,
8143 					 char *line1, char *line2, char *line3)
8144 {
8145 	/* Expected log for failed and not properly guarded kfunc call:
8146 	 * line1 -> 123: (85) call unknown#2002000345
8147 	 * line2 -> invalid func unknown#2002000345
8148 	 * line3 -> <anything else or end of buffer>
8149 	 *
8150 	 * "123" is the index of the instruction that was poisoned.
8151 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8152 	 */
8153 	struct bpf_object *obj = prog->obj;
8154 	const struct extern_desc *ext;
8155 	int insn_idx, ext_idx;
8156 	char patch[128];
8157 
8158 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8159 		return;
8160 
8161 	ext_idx -= POISON_CALL_KFUNC_BASE;
8162 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8163 		return;
8164 	ext = &obj->externs[ext_idx];
8165 
8166 	snprintf(patch, sizeof(patch),
8167 		 "%d: <invalid kfunc call>\n"
8168 		 "kfunc '%s' is referenced but wasn't resolved\n",
8169 		 insn_idx, ext->name);
8170 
8171 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8172 }
8173 
8174 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8175 {
8176 	/* look for familiar error patterns in last N lines of the log */
8177 	const size_t max_last_line_cnt = 10;
8178 	char *prev_line, *cur_line, *next_line;
8179 	size_t log_sz;
8180 	int i;
8181 
8182 	if (!buf)
8183 		return;
8184 
8185 	log_sz = strlen(buf) + 1;
8186 	next_line = buf + log_sz - 1;
8187 
8188 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8189 		cur_line = find_prev_line(buf, next_line);
8190 		if (!cur_line)
8191 			return;
8192 
8193 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8194 			prev_line = find_prev_line(buf, cur_line);
8195 			if (!prev_line)
8196 				continue;
8197 
8198 			/* failed CO-RE relocation case */
8199 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8200 						   prev_line, cur_line, next_line);
8201 			return;
8202 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8203 			prev_line = find_prev_line(buf, cur_line);
8204 			if (!prev_line)
8205 				continue;
8206 
8207 			/* reference to uncreated BPF map */
8208 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8209 						   prev_line, cur_line, next_line);
8210 			return;
8211 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8212 			prev_line = find_prev_line(buf, cur_line);
8213 			if (!prev_line)
8214 				continue;
8215 
8216 			/* reference to unresolved kfunc */
8217 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8218 						     prev_line, cur_line, next_line);
8219 			return;
8220 		}
8221 	}
8222 }
8223 
8224 static int bpf_program_record_relos(struct bpf_program *prog)
8225 {
8226 	struct bpf_object *obj = prog->obj;
8227 	int i;
8228 
8229 	for (i = 0; i < prog->nr_reloc; i++) {
8230 		struct reloc_desc *relo = &prog->reloc_desc[i];
8231 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8232 		int kind;
8233 
8234 		switch (relo->type) {
8235 		case RELO_EXTERN_LD64:
8236 			if (ext->type != EXT_KSYM)
8237 				continue;
8238 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8239 				BTF_KIND_VAR : BTF_KIND_FUNC;
8240 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8241 					       ext->is_weak, !ext->ksym.type_id,
8242 					       true, kind, relo->insn_idx);
8243 			break;
8244 		case RELO_EXTERN_CALL:
8245 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8246 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8247 					       relo->insn_idx);
8248 			break;
8249 		case RELO_CORE: {
8250 			struct bpf_core_relo cr = {
8251 				.insn_off = relo->insn_idx * 8,
8252 				.type_id = relo->core_relo->type_id,
8253 				.access_str_off = relo->core_relo->access_str_off,
8254 				.kind = relo->core_relo->kind,
8255 			};
8256 
8257 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8258 			break;
8259 		}
8260 		default:
8261 			continue;
8262 		}
8263 	}
8264 	return 0;
8265 }
8266 
8267 static int
8268 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8269 {
8270 	struct bpf_program *prog;
8271 	size_t i;
8272 	int err;
8273 
8274 	for (i = 0; i < obj->nr_programs; i++) {
8275 		prog = &obj->programs[i];
8276 		if (prog_is_subprog(obj, prog))
8277 			continue;
8278 		if (!prog->autoload) {
8279 			pr_debug("prog '%s': skipped loading\n", prog->name);
8280 			continue;
8281 		}
8282 		prog->log_level |= log_level;
8283 
8284 		if (obj->gen_loader)
8285 			bpf_program_record_relos(prog);
8286 
8287 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8288 					   obj->license, obj->kern_version, &prog->fd);
8289 		if (err) {
8290 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8291 			return err;
8292 		}
8293 	}
8294 
8295 	bpf_object__free_relocs(obj);
8296 	return 0;
8297 }
8298 
8299 static int bpf_object_prepare_progs(struct bpf_object *obj)
8300 {
8301 	struct bpf_program *prog;
8302 	size_t i;
8303 	int err;
8304 
8305 	for (i = 0; i < obj->nr_programs; i++) {
8306 		prog = &obj->programs[i];
8307 		err = bpf_object__sanitize_prog(obj, prog);
8308 		if (err)
8309 			return err;
8310 	}
8311 	return 0;
8312 }
8313 
8314 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8315 
8316 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8317 {
8318 	struct bpf_program *prog;
8319 	int err;
8320 
8321 	bpf_object__for_each_program(prog, obj) {
8322 		prog->sec_def = find_sec_def(prog->sec_name);
8323 		if (!prog->sec_def) {
8324 			/* couldn't guess, but user might manually specify */
8325 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8326 				prog->name, prog->sec_name);
8327 			continue;
8328 		}
8329 
8330 		prog->type = prog->sec_def->prog_type;
8331 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8332 
8333 		/* sec_def can have custom callback which should be called
8334 		 * after bpf_program is initialized to adjust its properties
8335 		 */
8336 		if (prog->sec_def->prog_setup_fn) {
8337 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8338 			if (err < 0) {
8339 				pr_warn("prog '%s': failed to initialize: %s\n",
8340 					prog->name, errstr(err));
8341 				return err;
8342 			}
8343 		}
8344 	}
8345 
8346 	return 0;
8347 }
8348 
8349 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8350 					  const char *obj_name,
8351 					  const struct bpf_object_open_opts *opts)
8352 {
8353 	const char *kconfig, *btf_tmp_path, *token_path;
8354 	struct bpf_object *obj;
8355 	int err;
8356 	char *log_buf;
8357 	size_t log_size;
8358 	__u32 log_level;
8359 
8360 	if (obj_buf && !obj_name)
8361 		return ERR_PTR(-EINVAL);
8362 
8363 	if (elf_version(EV_CURRENT) == EV_NONE) {
8364 		pr_warn("failed to init libelf for %s\n",
8365 			path ? : "(mem buf)");
8366 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8367 	}
8368 
8369 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8370 		return ERR_PTR(-EINVAL);
8371 
8372 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8373 	if (obj_buf) {
8374 		path = obj_name;
8375 		pr_debug("loading object '%s' from buffer\n", obj_name);
8376 	} else {
8377 		pr_debug("loading object from %s\n", path);
8378 	}
8379 
8380 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8381 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8382 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8383 	if (log_size > UINT_MAX)
8384 		return ERR_PTR(-EINVAL);
8385 	if (log_size && !log_buf)
8386 		return ERR_PTR(-EINVAL);
8387 
8388 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8389 	/* if user didn't specify bpf_token_path explicitly, check if
8390 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8391 	 * option
8392 	 */
8393 	if (!token_path)
8394 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8395 	if (token_path && strlen(token_path) >= PATH_MAX)
8396 		return ERR_PTR(-ENAMETOOLONG);
8397 
8398 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8399 	if (IS_ERR(obj))
8400 		return obj;
8401 
8402 	obj->log_buf = log_buf;
8403 	obj->log_size = log_size;
8404 	obj->log_level = log_level;
8405 
8406 	if (token_path) {
8407 		obj->token_path = strdup(token_path);
8408 		if (!obj->token_path) {
8409 			err = -ENOMEM;
8410 			goto out;
8411 		}
8412 	}
8413 
8414 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8415 	if (btf_tmp_path) {
8416 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8417 			err = -ENAMETOOLONG;
8418 			goto out;
8419 		}
8420 		obj->btf_custom_path = strdup(btf_tmp_path);
8421 		if (!obj->btf_custom_path) {
8422 			err = -ENOMEM;
8423 			goto out;
8424 		}
8425 	}
8426 
8427 	kconfig = OPTS_GET(opts, kconfig, NULL);
8428 	if (kconfig) {
8429 		obj->kconfig = strdup(kconfig);
8430 		if (!obj->kconfig) {
8431 			err = -ENOMEM;
8432 			goto out;
8433 		}
8434 	}
8435 
8436 	err = bpf_object__elf_init(obj);
8437 	err = err ? : bpf_object__elf_collect(obj);
8438 	err = err ? : bpf_object__collect_externs(obj);
8439 	err = err ? : bpf_object_fixup_btf(obj);
8440 	err = err ? : bpf_object__init_maps(obj, opts);
8441 	err = err ? : bpf_object_init_progs(obj, opts);
8442 	err = err ? : bpf_object__collect_relos(obj);
8443 	if (err)
8444 		goto out;
8445 
8446 	bpf_object__elf_finish(obj);
8447 
8448 	return obj;
8449 out:
8450 	bpf_object__close(obj);
8451 	return ERR_PTR(err);
8452 }
8453 
8454 struct bpf_object *
8455 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8456 {
8457 	if (!path)
8458 		return libbpf_err_ptr(-EINVAL);
8459 
8460 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8461 }
8462 
8463 struct bpf_object *bpf_object__open(const char *path)
8464 {
8465 	return bpf_object__open_file(path, NULL);
8466 }
8467 
8468 struct bpf_object *
8469 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8470 		     const struct bpf_object_open_opts *opts)
8471 {
8472 	char tmp_name[64];
8473 
8474 	if (!obj_buf || obj_buf_sz == 0)
8475 		return libbpf_err_ptr(-EINVAL);
8476 
8477 	/* create a (quite useless) default "name" for this memory buffer object */
8478 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8479 
8480 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8481 }
8482 
8483 static int bpf_object_unload(struct bpf_object *obj)
8484 {
8485 	size_t i;
8486 
8487 	if (!obj)
8488 		return libbpf_err(-EINVAL);
8489 
8490 	for (i = 0; i < obj->nr_maps; i++) {
8491 		zclose(obj->maps[i].fd);
8492 		if (obj->maps[i].st_ops)
8493 			zfree(&obj->maps[i].st_ops->kern_vdata);
8494 	}
8495 
8496 	for (i = 0; i < obj->nr_programs; i++)
8497 		bpf_program__unload(&obj->programs[i]);
8498 
8499 	return 0;
8500 }
8501 
8502 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8503 {
8504 	struct bpf_map *m;
8505 
8506 	bpf_object__for_each_map(m, obj) {
8507 		if (!bpf_map__is_internal(m))
8508 			continue;
8509 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8510 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8511 	}
8512 
8513 	return 0;
8514 }
8515 
8516 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8517 			     const char *sym_name, void *ctx);
8518 
8519 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8520 {
8521 	char sym_type, sym_name[500];
8522 	unsigned long long sym_addr;
8523 	int ret, err = 0;
8524 	FILE *f;
8525 
8526 	f = fopen("/proc/kallsyms", "re");
8527 	if (!f) {
8528 		err = -errno;
8529 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8530 		return err;
8531 	}
8532 
8533 	while (true) {
8534 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8535 			     &sym_addr, &sym_type, sym_name);
8536 		if (ret == EOF && feof(f))
8537 			break;
8538 		if (ret != 3) {
8539 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8540 			err = -EINVAL;
8541 			break;
8542 		}
8543 
8544 		err = cb(sym_addr, sym_type, sym_name, ctx);
8545 		if (err)
8546 			break;
8547 	}
8548 
8549 	fclose(f);
8550 	return err;
8551 }
8552 
8553 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8554 		       const char *sym_name, void *ctx)
8555 {
8556 	struct bpf_object *obj = ctx;
8557 	const struct btf_type *t;
8558 	struct extern_desc *ext;
8559 	const char *res;
8560 
8561 	res = strstr(sym_name, ".llvm.");
8562 	if (sym_type == 'd' && res)
8563 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8564 	else
8565 		ext = find_extern_by_name(obj, sym_name);
8566 	if (!ext || ext->type != EXT_KSYM)
8567 		return 0;
8568 
8569 	t = btf__type_by_id(obj->btf, ext->btf_id);
8570 	if (!btf_is_var(t))
8571 		return 0;
8572 
8573 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8574 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8575 			sym_name, ext->ksym.addr, sym_addr);
8576 		return -EINVAL;
8577 	}
8578 	if (!ext->is_set) {
8579 		ext->is_set = true;
8580 		ext->ksym.addr = sym_addr;
8581 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8582 	}
8583 	return 0;
8584 }
8585 
8586 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8587 {
8588 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8589 }
8590 
8591 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8592 			    __u16 kind, struct btf **res_btf,
8593 			    struct module_btf **res_mod_btf)
8594 {
8595 	struct module_btf *mod_btf;
8596 	struct btf *btf;
8597 	int i, id, err;
8598 
8599 	btf = obj->btf_vmlinux;
8600 	mod_btf = NULL;
8601 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8602 
8603 	if (id == -ENOENT) {
8604 		err = load_module_btfs(obj);
8605 		if (err)
8606 			return err;
8607 
8608 		for (i = 0; i < obj->btf_module_cnt; i++) {
8609 			/* we assume module_btf's BTF FD is always >0 */
8610 			mod_btf = &obj->btf_modules[i];
8611 			btf = mod_btf->btf;
8612 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8613 			if (id != -ENOENT)
8614 				break;
8615 		}
8616 	}
8617 	if (id <= 0)
8618 		return -ESRCH;
8619 
8620 	*res_btf = btf;
8621 	*res_mod_btf = mod_btf;
8622 	return id;
8623 }
8624 
8625 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8626 					       struct extern_desc *ext)
8627 {
8628 	const struct btf_type *targ_var, *targ_type;
8629 	__u32 targ_type_id, local_type_id;
8630 	struct module_btf *mod_btf = NULL;
8631 	const char *targ_var_name;
8632 	struct btf *btf = NULL;
8633 	int id, err;
8634 
8635 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8636 	if (id < 0) {
8637 		if (id == -ESRCH && ext->is_weak)
8638 			return 0;
8639 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8640 			ext->name);
8641 		return id;
8642 	}
8643 
8644 	/* find local type_id */
8645 	local_type_id = ext->ksym.type_id;
8646 
8647 	/* find target type_id */
8648 	targ_var = btf__type_by_id(btf, id);
8649 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8650 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8651 
8652 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8653 					btf, targ_type_id);
8654 	if (err <= 0) {
8655 		const struct btf_type *local_type;
8656 		const char *targ_name, *local_name;
8657 
8658 		local_type = btf__type_by_id(obj->btf, local_type_id);
8659 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8660 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8661 
8662 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8663 			ext->name, local_type_id,
8664 			btf_kind_str(local_type), local_name, targ_type_id,
8665 			btf_kind_str(targ_type), targ_name);
8666 		return -EINVAL;
8667 	}
8668 
8669 	ext->is_set = true;
8670 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8671 	ext->ksym.kernel_btf_id = id;
8672 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8673 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8674 
8675 	return 0;
8676 }
8677 
8678 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8679 						struct extern_desc *ext)
8680 {
8681 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8682 	struct module_btf *mod_btf = NULL;
8683 	const struct btf_type *kern_func;
8684 	struct btf *kern_btf = NULL;
8685 	int ret;
8686 
8687 	local_func_proto_id = ext->ksym.type_id;
8688 
8689 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8690 				    &mod_btf);
8691 	if (kfunc_id < 0) {
8692 		if (kfunc_id == -ESRCH && ext->is_weak)
8693 			return 0;
8694 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8695 			ext->name);
8696 		return kfunc_id;
8697 	}
8698 
8699 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8700 	kfunc_proto_id = kern_func->type;
8701 
8702 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8703 					kern_btf, kfunc_proto_id);
8704 	if (ret <= 0) {
8705 		if (ext->is_weak)
8706 			return 0;
8707 
8708 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8709 			ext->name, local_func_proto_id,
8710 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8711 		return -EINVAL;
8712 	}
8713 
8714 	/* set index for module BTF fd in fd_array, if unset */
8715 	if (mod_btf && !mod_btf->fd_array_idx) {
8716 		/* insn->off is s16 */
8717 		if (obj->fd_array_cnt == INT16_MAX) {
8718 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8719 				ext->name, mod_btf->fd_array_idx);
8720 			return -E2BIG;
8721 		}
8722 		/* Cannot use index 0 for module BTF fd */
8723 		if (!obj->fd_array_cnt)
8724 			obj->fd_array_cnt = 1;
8725 
8726 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8727 					obj->fd_array_cnt + 1);
8728 		if (ret)
8729 			return ret;
8730 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8731 		/* we assume module BTF FD is always >0 */
8732 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8733 	}
8734 
8735 	ext->is_set = true;
8736 	ext->ksym.kernel_btf_id = kfunc_id;
8737 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8738 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8739 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8740 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8741 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8742 	 */
8743 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8744 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8745 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8746 
8747 	return 0;
8748 }
8749 
8750 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8751 {
8752 	const struct btf_type *t;
8753 	struct extern_desc *ext;
8754 	int i, err;
8755 
8756 	for (i = 0; i < obj->nr_extern; i++) {
8757 		ext = &obj->externs[i];
8758 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8759 			continue;
8760 
8761 		if (obj->gen_loader) {
8762 			ext->is_set = true;
8763 			ext->ksym.kernel_btf_obj_fd = 0;
8764 			ext->ksym.kernel_btf_id = 0;
8765 			continue;
8766 		}
8767 		t = btf__type_by_id(obj->btf, ext->btf_id);
8768 		if (btf_is_var(t))
8769 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8770 		else
8771 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8772 		if (err)
8773 			return err;
8774 	}
8775 	return 0;
8776 }
8777 
8778 static int bpf_object__resolve_externs(struct bpf_object *obj,
8779 				       const char *extra_kconfig)
8780 {
8781 	bool need_config = false, need_kallsyms = false;
8782 	bool need_vmlinux_btf = false;
8783 	struct extern_desc *ext;
8784 	void *kcfg_data = NULL;
8785 	int err, i;
8786 
8787 	if (obj->nr_extern == 0)
8788 		return 0;
8789 
8790 	if (obj->kconfig_map_idx >= 0)
8791 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8792 
8793 	for (i = 0; i < obj->nr_extern; i++) {
8794 		ext = &obj->externs[i];
8795 
8796 		if (ext->type == EXT_KSYM) {
8797 			if (ext->ksym.type_id)
8798 				need_vmlinux_btf = true;
8799 			else
8800 				need_kallsyms = true;
8801 			continue;
8802 		} else if (ext->type == EXT_KCFG) {
8803 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8804 			__u64 value = 0;
8805 
8806 			/* Kconfig externs need actual /proc/config.gz */
8807 			if (str_has_pfx(ext->name, "CONFIG_")) {
8808 				need_config = true;
8809 				continue;
8810 			}
8811 
8812 			/* Virtual kcfg externs are customly handled by libbpf */
8813 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8814 				value = get_kernel_version();
8815 				if (!value) {
8816 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8817 					return -EINVAL;
8818 				}
8819 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8820 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8821 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8822 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8823 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8824 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8825 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8826 				 * customly by libbpf (their values don't come from Kconfig).
8827 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8828 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8829 				 * externs.
8830 				 */
8831 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8832 				return -EINVAL;
8833 			}
8834 
8835 			err = set_kcfg_value_num(ext, ext_ptr, value);
8836 			if (err)
8837 				return err;
8838 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8839 				 ext->name, (long long)value);
8840 		} else {
8841 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8842 			return -EINVAL;
8843 		}
8844 	}
8845 	if (need_config && extra_kconfig) {
8846 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8847 		if (err)
8848 			return -EINVAL;
8849 		need_config = false;
8850 		for (i = 0; i < obj->nr_extern; i++) {
8851 			ext = &obj->externs[i];
8852 			if (ext->type == EXT_KCFG && !ext->is_set) {
8853 				need_config = true;
8854 				break;
8855 			}
8856 		}
8857 	}
8858 	if (need_config) {
8859 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8860 		if (err)
8861 			return -EINVAL;
8862 	}
8863 	if (need_kallsyms) {
8864 		err = bpf_object__read_kallsyms_file(obj);
8865 		if (err)
8866 			return -EINVAL;
8867 	}
8868 	if (need_vmlinux_btf) {
8869 		err = bpf_object__resolve_ksyms_btf_id(obj);
8870 		if (err)
8871 			return -EINVAL;
8872 	}
8873 	for (i = 0; i < obj->nr_extern; i++) {
8874 		ext = &obj->externs[i];
8875 
8876 		if (!ext->is_set && !ext->is_weak) {
8877 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8878 			return -ESRCH;
8879 		} else if (!ext->is_set) {
8880 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8881 				 ext->name);
8882 		}
8883 	}
8884 
8885 	return 0;
8886 }
8887 
8888 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8889 {
8890 	const struct btf_type *type;
8891 	struct bpf_struct_ops *st_ops;
8892 	__u32 i;
8893 
8894 	st_ops = map->st_ops;
8895 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8896 	for (i = 0; i < btf_vlen(type); i++) {
8897 		struct bpf_program *prog = st_ops->progs[i];
8898 		void *kern_data;
8899 		int prog_fd;
8900 
8901 		if (!prog)
8902 			continue;
8903 
8904 		prog_fd = bpf_program__fd(prog);
8905 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8906 		*(unsigned long *)kern_data = prog_fd;
8907 	}
8908 }
8909 
8910 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8911 {
8912 	struct bpf_map *map;
8913 	int i;
8914 
8915 	for (i = 0; i < obj->nr_maps; i++) {
8916 		map = &obj->maps[i];
8917 
8918 		if (!bpf_map__is_struct_ops(map))
8919 			continue;
8920 
8921 		if (!map->autocreate)
8922 			continue;
8923 
8924 		bpf_map_prepare_vdata(map);
8925 	}
8926 
8927 	return 0;
8928 }
8929 
8930 static void bpf_object_unpin(struct bpf_object *obj)
8931 {
8932 	int i;
8933 
8934 	/* unpin any maps that were auto-pinned during load */
8935 	for (i = 0; i < obj->nr_maps; i++)
8936 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8937 			bpf_map__unpin(&obj->maps[i], NULL);
8938 }
8939 
8940 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8941 {
8942 	int i;
8943 
8944 	/* clean up fd_array */
8945 	zfree(&obj->fd_array);
8946 
8947 	/* clean up module BTFs */
8948 	for (i = 0; i < obj->btf_module_cnt; i++) {
8949 		close(obj->btf_modules[i].fd);
8950 		btf__free(obj->btf_modules[i].btf);
8951 		free(obj->btf_modules[i].name);
8952 	}
8953 	obj->btf_module_cnt = 0;
8954 	zfree(&obj->btf_modules);
8955 
8956 	/* clean up vmlinux BTF */
8957 	btf__free(obj->btf_vmlinux);
8958 	obj->btf_vmlinux = NULL;
8959 }
8960 
8961 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8962 {
8963 	int err;
8964 
8965 	if (obj->state >= OBJ_PREPARED) {
8966 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8967 		return -EINVAL;
8968 	}
8969 
8970 	err = bpf_object_prepare_token(obj);
8971 	err = err ? : bpf_object__probe_loading(obj);
8972 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8973 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8974 	err = err ? : bpf_object__sanitize_maps(obj);
8975 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8976 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8977 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8978 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8979 	err = err ? : bpf_object__create_maps(obj);
8980 	err = err ? : bpf_object_prepare_progs(obj);
8981 
8982 	if (err) {
8983 		bpf_object_unpin(obj);
8984 		bpf_object_unload(obj);
8985 		obj->state = OBJ_LOADED;
8986 		return err;
8987 	}
8988 
8989 	obj->state = OBJ_PREPARED;
8990 	return 0;
8991 }
8992 
8993 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8994 {
8995 	int err;
8996 
8997 	if (!obj)
8998 		return libbpf_err(-EINVAL);
8999 
9000 	if (obj->state >= OBJ_LOADED) {
9001 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9002 		return libbpf_err(-EINVAL);
9003 	}
9004 
9005 	/* Disallow kernel loading programs of non-native endianness but
9006 	 * permit cross-endian creation of "light skeleton".
9007 	 */
9008 	if (obj->gen_loader) {
9009 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
9010 	} else if (!is_native_endianness(obj)) {
9011 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9012 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9013 	}
9014 
9015 	if (obj->state < OBJ_PREPARED) {
9016 		err = bpf_object_prepare(obj, target_btf_path);
9017 		if (err)
9018 			return libbpf_err(err);
9019 	}
9020 	err = bpf_object__load_progs(obj, extra_log_level);
9021 	err = err ? : bpf_object_init_prog_arrays(obj);
9022 	err = err ? : bpf_object_prepare_struct_ops(obj);
9023 
9024 	if (obj->gen_loader) {
9025 		/* reset FDs */
9026 		if (obj->btf)
9027 			btf__set_fd(obj->btf, -1);
9028 		if (!err)
9029 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9030 	}
9031 
9032 	bpf_object_post_load_cleanup(obj);
9033 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9034 
9035 	if (err) {
9036 		bpf_object_unpin(obj);
9037 		bpf_object_unload(obj);
9038 		pr_warn("failed to load object '%s'\n", obj->path);
9039 		return libbpf_err(err);
9040 	}
9041 
9042 	return 0;
9043 }
9044 
9045 int bpf_object__prepare(struct bpf_object *obj)
9046 {
9047 	return libbpf_err(bpf_object_prepare(obj, NULL));
9048 }
9049 
9050 int bpf_object__load(struct bpf_object *obj)
9051 {
9052 	return bpf_object_load(obj, 0, NULL);
9053 }
9054 
9055 static int make_parent_dir(const char *path)
9056 {
9057 	char *dname, *dir;
9058 	int err = 0;
9059 
9060 	dname = strdup(path);
9061 	if (dname == NULL)
9062 		return -ENOMEM;
9063 
9064 	dir = dirname(dname);
9065 	if (mkdir(dir, 0700) && errno != EEXIST)
9066 		err = -errno;
9067 
9068 	free(dname);
9069 	if (err) {
9070 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9071 	}
9072 	return err;
9073 }
9074 
9075 static int check_path(const char *path)
9076 {
9077 	struct statfs st_fs;
9078 	char *dname, *dir;
9079 	int err = 0;
9080 
9081 	if (path == NULL)
9082 		return -EINVAL;
9083 
9084 	dname = strdup(path);
9085 	if (dname == NULL)
9086 		return -ENOMEM;
9087 
9088 	dir = dirname(dname);
9089 	if (statfs(dir, &st_fs)) {
9090 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9091 		err = -errno;
9092 	}
9093 	free(dname);
9094 
9095 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9096 		pr_warn("specified path %s is not on BPF FS\n", path);
9097 		err = -EINVAL;
9098 	}
9099 
9100 	return err;
9101 }
9102 
9103 int bpf_program__pin(struct bpf_program *prog, const char *path)
9104 {
9105 	int err;
9106 
9107 	if (prog->fd < 0) {
9108 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9109 		return libbpf_err(-EINVAL);
9110 	}
9111 
9112 	err = make_parent_dir(path);
9113 	if (err)
9114 		return libbpf_err(err);
9115 
9116 	err = check_path(path);
9117 	if (err)
9118 		return libbpf_err(err);
9119 
9120 	if (bpf_obj_pin(prog->fd, path)) {
9121 		err = -errno;
9122 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9123 		return libbpf_err(err);
9124 	}
9125 
9126 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9127 	return 0;
9128 }
9129 
9130 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9131 {
9132 	int err;
9133 
9134 	if (prog->fd < 0) {
9135 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9136 		return libbpf_err(-EINVAL);
9137 	}
9138 
9139 	err = check_path(path);
9140 	if (err)
9141 		return libbpf_err(err);
9142 
9143 	err = unlink(path);
9144 	if (err)
9145 		return libbpf_err(-errno);
9146 
9147 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9148 	return 0;
9149 }
9150 
9151 int bpf_map__pin(struct bpf_map *map, const char *path)
9152 {
9153 	int err;
9154 
9155 	if (map == NULL) {
9156 		pr_warn("invalid map pointer\n");
9157 		return libbpf_err(-EINVAL);
9158 	}
9159 
9160 	if (map->fd < 0) {
9161 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9162 		return libbpf_err(-EINVAL);
9163 	}
9164 
9165 	if (map->pin_path) {
9166 		if (path && strcmp(path, map->pin_path)) {
9167 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9168 				bpf_map__name(map), map->pin_path, path);
9169 			return libbpf_err(-EINVAL);
9170 		} else if (map->pinned) {
9171 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9172 				 bpf_map__name(map), map->pin_path);
9173 			return 0;
9174 		}
9175 	} else {
9176 		if (!path) {
9177 			pr_warn("missing a path to pin map '%s' at\n",
9178 				bpf_map__name(map));
9179 			return libbpf_err(-EINVAL);
9180 		} else if (map->pinned) {
9181 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9182 			return libbpf_err(-EEXIST);
9183 		}
9184 
9185 		map->pin_path = strdup(path);
9186 		if (!map->pin_path) {
9187 			err = -errno;
9188 			goto out_err;
9189 		}
9190 	}
9191 
9192 	err = make_parent_dir(map->pin_path);
9193 	if (err)
9194 		return libbpf_err(err);
9195 
9196 	err = check_path(map->pin_path);
9197 	if (err)
9198 		return libbpf_err(err);
9199 
9200 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9201 		err = -errno;
9202 		goto out_err;
9203 	}
9204 
9205 	map->pinned = true;
9206 	pr_debug("pinned map '%s'\n", map->pin_path);
9207 
9208 	return 0;
9209 
9210 out_err:
9211 	pr_warn("failed to pin map: %s\n", errstr(err));
9212 	return libbpf_err(err);
9213 }
9214 
9215 int bpf_map__unpin(struct bpf_map *map, const char *path)
9216 {
9217 	int err;
9218 
9219 	if (map == NULL) {
9220 		pr_warn("invalid map pointer\n");
9221 		return libbpf_err(-EINVAL);
9222 	}
9223 
9224 	if (map->pin_path) {
9225 		if (path && strcmp(path, map->pin_path)) {
9226 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9227 				bpf_map__name(map), map->pin_path, path);
9228 			return libbpf_err(-EINVAL);
9229 		}
9230 		path = map->pin_path;
9231 	} else if (!path) {
9232 		pr_warn("no path to unpin map '%s' from\n",
9233 			bpf_map__name(map));
9234 		return libbpf_err(-EINVAL);
9235 	}
9236 
9237 	err = check_path(path);
9238 	if (err)
9239 		return libbpf_err(err);
9240 
9241 	err = unlink(path);
9242 	if (err != 0)
9243 		return libbpf_err(-errno);
9244 
9245 	map->pinned = false;
9246 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9247 
9248 	return 0;
9249 }
9250 
9251 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9252 {
9253 	char *new = NULL;
9254 
9255 	if (path) {
9256 		new = strdup(path);
9257 		if (!new)
9258 			return libbpf_err(-errno);
9259 	}
9260 
9261 	free(map->pin_path);
9262 	map->pin_path = new;
9263 	return 0;
9264 }
9265 
9266 __alias(bpf_map__pin_path)
9267 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9268 
9269 const char *bpf_map__pin_path(const struct bpf_map *map)
9270 {
9271 	return map->pin_path;
9272 }
9273 
9274 bool bpf_map__is_pinned(const struct bpf_map *map)
9275 {
9276 	return map->pinned;
9277 }
9278 
9279 static void sanitize_pin_path(char *s)
9280 {
9281 	/* bpffs disallows periods in path names */
9282 	while (*s) {
9283 		if (*s == '.')
9284 			*s = '_';
9285 		s++;
9286 	}
9287 }
9288 
9289 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9290 {
9291 	struct bpf_map *map;
9292 	int err;
9293 
9294 	if (!obj)
9295 		return libbpf_err(-ENOENT);
9296 
9297 	if (obj->state < OBJ_PREPARED) {
9298 		pr_warn("object not yet loaded; load it first\n");
9299 		return libbpf_err(-ENOENT);
9300 	}
9301 
9302 	bpf_object__for_each_map(map, obj) {
9303 		char *pin_path = NULL;
9304 		char buf[PATH_MAX];
9305 
9306 		if (!map->autocreate)
9307 			continue;
9308 
9309 		if (path) {
9310 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9311 			if (err)
9312 				goto err_unpin_maps;
9313 			sanitize_pin_path(buf);
9314 			pin_path = buf;
9315 		} else if (!map->pin_path) {
9316 			continue;
9317 		}
9318 
9319 		err = bpf_map__pin(map, pin_path);
9320 		if (err)
9321 			goto err_unpin_maps;
9322 	}
9323 
9324 	return 0;
9325 
9326 err_unpin_maps:
9327 	while ((map = bpf_object__prev_map(obj, map))) {
9328 		if (!map->pin_path)
9329 			continue;
9330 
9331 		bpf_map__unpin(map, NULL);
9332 	}
9333 
9334 	return libbpf_err(err);
9335 }
9336 
9337 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9338 {
9339 	struct bpf_map *map;
9340 	int err;
9341 
9342 	if (!obj)
9343 		return libbpf_err(-ENOENT);
9344 
9345 	bpf_object__for_each_map(map, obj) {
9346 		char *pin_path = NULL;
9347 		char buf[PATH_MAX];
9348 
9349 		if (path) {
9350 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9351 			if (err)
9352 				return libbpf_err(err);
9353 			sanitize_pin_path(buf);
9354 			pin_path = buf;
9355 		} else if (!map->pin_path) {
9356 			continue;
9357 		}
9358 
9359 		err = bpf_map__unpin(map, pin_path);
9360 		if (err)
9361 			return libbpf_err(err);
9362 	}
9363 
9364 	return 0;
9365 }
9366 
9367 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9368 {
9369 	struct bpf_program *prog;
9370 	char buf[PATH_MAX];
9371 	int err;
9372 
9373 	if (!obj)
9374 		return libbpf_err(-ENOENT);
9375 
9376 	if (obj->state < OBJ_LOADED) {
9377 		pr_warn("object not yet loaded; load it first\n");
9378 		return libbpf_err(-ENOENT);
9379 	}
9380 
9381 	bpf_object__for_each_program(prog, obj) {
9382 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9383 		if (err)
9384 			goto err_unpin_programs;
9385 
9386 		err = bpf_program__pin(prog, buf);
9387 		if (err)
9388 			goto err_unpin_programs;
9389 	}
9390 
9391 	return 0;
9392 
9393 err_unpin_programs:
9394 	while ((prog = bpf_object__prev_program(obj, prog))) {
9395 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9396 			continue;
9397 
9398 		bpf_program__unpin(prog, buf);
9399 	}
9400 
9401 	return libbpf_err(err);
9402 }
9403 
9404 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9405 {
9406 	struct bpf_program *prog;
9407 	int err;
9408 
9409 	if (!obj)
9410 		return libbpf_err(-ENOENT);
9411 
9412 	bpf_object__for_each_program(prog, obj) {
9413 		char buf[PATH_MAX];
9414 
9415 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9416 		if (err)
9417 			return libbpf_err(err);
9418 
9419 		err = bpf_program__unpin(prog, buf);
9420 		if (err)
9421 			return libbpf_err(err);
9422 	}
9423 
9424 	return 0;
9425 }
9426 
9427 int bpf_object__pin(struct bpf_object *obj, const char *path)
9428 {
9429 	int err;
9430 
9431 	err = bpf_object__pin_maps(obj, path);
9432 	if (err)
9433 		return libbpf_err(err);
9434 
9435 	err = bpf_object__pin_programs(obj, path);
9436 	if (err) {
9437 		bpf_object__unpin_maps(obj, path);
9438 		return libbpf_err(err);
9439 	}
9440 
9441 	return 0;
9442 }
9443 
9444 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9445 {
9446 	int err;
9447 
9448 	err = bpf_object__unpin_programs(obj, path);
9449 	if (err)
9450 		return libbpf_err(err);
9451 
9452 	err = bpf_object__unpin_maps(obj, path);
9453 	if (err)
9454 		return libbpf_err(err);
9455 
9456 	return 0;
9457 }
9458 
9459 static void bpf_map__destroy(struct bpf_map *map)
9460 {
9461 	if (map->inner_map) {
9462 		bpf_map__destroy(map->inner_map);
9463 		zfree(&map->inner_map);
9464 	}
9465 
9466 	zfree(&map->init_slots);
9467 	map->init_slots_sz = 0;
9468 
9469 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9470 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9471 	map->mmaped = NULL;
9472 
9473 	if (map->st_ops) {
9474 		zfree(&map->st_ops->data);
9475 		zfree(&map->st_ops->progs);
9476 		zfree(&map->st_ops->kern_func_off);
9477 		zfree(&map->st_ops);
9478 	}
9479 
9480 	zfree(&map->name);
9481 	zfree(&map->real_name);
9482 	zfree(&map->pin_path);
9483 
9484 	if (map->fd >= 0)
9485 		zclose(map->fd);
9486 }
9487 
9488 void bpf_object__close(struct bpf_object *obj)
9489 {
9490 	size_t i;
9491 
9492 	if (IS_ERR_OR_NULL(obj))
9493 		return;
9494 
9495 	/*
9496 	 * if user called bpf_object__prepare() without ever getting to
9497 	 * bpf_object__load(), we need to clean up stuff that is normally
9498 	 * cleaned up at the end of loading step
9499 	 */
9500 	bpf_object_post_load_cleanup(obj);
9501 
9502 	usdt_manager_free(obj->usdt_man);
9503 	obj->usdt_man = NULL;
9504 
9505 	bpf_gen__free(obj->gen_loader);
9506 	bpf_object__elf_finish(obj);
9507 	bpf_object_unload(obj);
9508 	btf__free(obj->btf);
9509 	btf__free(obj->btf_vmlinux);
9510 	btf_ext__free(obj->btf_ext);
9511 
9512 	for (i = 0; i < obj->nr_maps; i++)
9513 		bpf_map__destroy(&obj->maps[i]);
9514 
9515 	zfree(&obj->btf_custom_path);
9516 	zfree(&obj->kconfig);
9517 
9518 	for (i = 0; i < obj->nr_extern; i++) {
9519 		zfree(&obj->externs[i].name);
9520 		zfree(&obj->externs[i].essent_name);
9521 	}
9522 
9523 	zfree(&obj->externs);
9524 	obj->nr_extern = 0;
9525 
9526 	zfree(&obj->maps);
9527 	obj->nr_maps = 0;
9528 
9529 	if (obj->programs && obj->nr_programs) {
9530 		for (i = 0; i < obj->nr_programs; i++)
9531 			bpf_program__exit(&obj->programs[i]);
9532 	}
9533 	zfree(&obj->programs);
9534 
9535 	zfree(&obj->feat_cache);
9536 	zfree(&obj->token_path);
9537 	if (obj->token_fd > 0)
9538 		close(obj->token_fd);
9539 
9540 	zfree(&obj->arena_data);
9541 
9542 	zfree(&obj->jumptables_data);
9543 	obj->jumptables_data_sz = 0;
9544 
9545 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9546 		close(obj->jumptable_maps[i].fd);
9547 	zfree(&obj->jumptable_maps);
9548 
9549 	free(obj);
9550 }
9551 
9552 const char *bpf_object__name(const struct bpf_object *obj)
9553 {
9554 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9555 }
9556 
9557 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9558 {
9559 	return obj ? obj->kern_version : 0;
9560 }
9561 
9562 int bpf_object__token_fd(const struct bpf_object *obj)
9563 {
9564 	return obj->token_fd ?: -1;
9565 }
9566 
9567 struct btf *bpf_object__btf(const struct bpf_object *obj)
9568 {
9569 	return obj ? obj->btf : NULL;
9570 }
9571 
9572 int bpf_object__btf_fd(const struct bpf_object *obj)
9573 {
9574 	return obj->btf ? btf__fd(obj->btf) : -1;
9575 }
9576 
9577 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9578 {
9579 	if (obj->state >= OBJ_LOADED)
9580 		return libbpf_err(-EINVAL);
9581 
9582 	obj->kern_version = kern_version;
9583 
9584 	return 0;
9585 }
9586 
9587 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9588 {
9589 	struct bpf_gen *gen;
9590 
9591 	if (!opts)
9592 		return libbpf_err(-EFAULT);
9593 	if (!OPTS_VALID(opts, gen_loader_opts))
9594 		return libbpf_err(-EINVAL);
9595 	gen = calloc(1, sizeof(*gen));
9596 	if (!gen)
9597 		return libbpf_err(-ENOMEM);
9598 	gen->opts = opts;
9599 	gen->swapped_endian = !is_native_endianness(obj);
9600 	obj->gen_loader = gen;
9601 	return 0;
9602 }
9603 
9604 static struct bpf_program *
9605 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9606 		    bool forward)
9607 {
9608 	size_t nr_programs = obj->nr_programs;
9609 	ssize_t idx;
9610 
9611 	if (!nr_programs)
9612 		return NULL;
9613 
9614 	if (!p)
9615 		/* Iter from the beginning */
9616 		return forward ? &obj->programs[0] :
9617 			&obj->programs[nr_programs - 1];
9618 
9619 	if (p->obj != obj) {
9620 		pr_warn("error: program handler doesn't match object\n");
9621 		return errno = EINVAL, NULL;
9622 	}
9623 
9624 	idx = (p - obj->programs) + (forward ? 1 : -1);
9625 	if (idx >= obj->nr_programs || idx < 0)
9626 		return NULL;
9627 	return &obj->programs[idx];
9628 }
9629 
9630 struct bpf_program *
9631 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9632 {
9633 	struct bpf_program *prog = prev;
9634 
9635 	do {
9636 		prog = __bpf_program__iter(prog, obj, true);
9637 	} while (prog && prog_is_subprog(obj, prog));
9638 
9639 	return prog;
9640 }
9641 
9642 struct bpf_program *
9643 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9644 {
9645 	struct bpf_program *prog = next;
9646 
9647 	do {
9648 		prog = __bpf_program__iter(prog, obj, false);
9649 	} while (prog && prog_is_subprog(obj, prog));
9650 
9651 	return prog;
9652 }
9653 
9654 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9655 {
9656 	prog->prog_ifindex = ifindex;
9657 }
9658 
9659 const char *bpf_program__name(const struct bpf_program *prog)
9660 {
9661 	return prog->name;
9662 }
9663 
9664 const char *bpf_program__section_name(const struct bpf_program *prog)
9665 {
9666 	return prog->sec_name;
9667 }
9668 
9669 bool bpf_program__autoload(const struct bpf_program *prog)
9670 {
9671 	return prog->autoload;
9672 }
9673 
9674 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9675 {
9676 	if (prog->obj->state >= OBJ_LOADED)
9677 		return libbpf_err(-EINVAL);
9678 
9679 	prog->autoload = autoload;
9680 	return 0;
9681 }
9682 
9683 bool bpf_program__autoattach(const struct bpf_program *prog)
9684 {
9685 	return prog->autoattach;
9686 }
9687 
9688 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9689 {
9690 	prog->autoattach = autoattach;
9691 }
9692 
9693 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9694 {
9695 	return prog->insns;
9696 }
9697 
9698 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9699 {
9700 	return prog->insns_cnt;
9701 }
9702 
9703 int bpf_program__set_insns(struct bpf_program *prog,
9704 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9705 {
9706 	struct bpf_insn *insns;
9707 
9708 	if (prog->obj->state >= OBJ_LOADED)
9709 		return libbpf_err(-EBUSY);
9710 
9711 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9712 	/* NULL is a valid return from reallocarray if the new count is zero */
9713 	if (!insns && new_insn_cnt) {
9714 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9715 		return libbpf_err(-ENOMEM);
9716 	}
9717 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9718 
9719 	prog->insns = insns;
9720 	prog->insns_cnt = new_insn_cnt;
9721 	return 0;
9722 }
9723 
9724 int bpf_program__fd(const struct bpf_program *prog)
9725 {
9726 	if (!prog)
9727 		return libbpf_err(-EINVAL);
9728 
9729 	if (prog->fd < 0)
9730 		return libbpf_err(-ENOENT);
9731 
9732 	return prog->fd;
9733 }
9734 
9735 __alias(bpf_program__type)
9736 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9737 
9738 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9739 {
9740 	return prog->type;
9741 }
9742 
9743 static size_t custom_sec_def_cnt;
9744 static struct bpf_sec_def *custom_sec_defs;
9745 static struct bpf_sec_def custom_fallback_def;
9746 static bool has_custom_fallback_def;
9747 static int last_custom_sec_def_handler_id;
9748 
9749 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9750 {
9751 	if (prog->obj->state >= OBJ_LOADED)
9752 		return libbpf_err(-EBUSY);
9753 
9754 	/* if type is not changed, do nothing */
9755 	if (prog->type == type)
9756 		return 0;
9757 
9758 	prog->type = type;
9759 
9760 	/* If a program type was changed, we need to reset associated SEC()
9761 	 * handler, as it will be invalid now. The only exception is a generic
9762 	 * fallback handler, which by definition is program type-agnostic and
9763 	 * is a catch-all custom handler, optionally set by the application,
9764 	 * so should be able to handle any type of BPF program.
9765 	 */
9766 	if (prog->sec_def != &custom_fallback_def)
9767 		prog->sec_def = NULL;
9768 	return 0;
9769 }
9770 
9771 __alias(bpf_program__expected_attach_type)
9772 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9773 
9774 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9775 {
9776 	return prog->expected_attach_type;
9777 }
9778 
9779 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9780 					   enum bpf_attach_type type)
9781 {
9782 	if (prog->obj->state >= OBJ_LOADED)
9783 		return libbpf_err(-EBUSY);
9784 
9785 	prog->expected_attach_type = type;
9786 	return 0;
9787 }
9788 
9789 __u32 bpf_program__flags(const struct bpf_program *prog)
9790 {
9791 	return prog->prog_flags;
9792 }
9793 
9794 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9795 {
9796 	if (prog->obj->state >= OBJ_LOADED)
9797 		return libbpf_err(-EBUSY);
9798 
9799 	prog->prog_flags = flags;
9800 	return 0;
9801 }
9802 
9803 __u32 bpf_program__log_level(const struct bpf_program *prog)
9804 {
9805 	return prog->log_level;
9806 }
9807 
9808 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9809 {
9810 	if (prog->obj->state >= OBJ_LOADED)
9811 		return libbpf_err(-EBUSY);
9812 
9813 	prog->log_level = log_level;
9814 	return 0;
9815 }
9816 
9817 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9818 {
9819 	*log_size = prog->log_size;
9820 	return prog->log_buf;
9821 }
9822 
9823 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9824 {
9825 	if (log_size && !log_buf)
9826 		return libbpf_err(-EINVAL);
9827 	if (prog->log_size > UINT_MAX)
9828 		return libbpf_err(-EINVAL);
9829 	if (prog->obj->state >= OBJ_LOADED)
9830 		return libbpf_err(-EBUSY);
9831 
9832 	prog->log_buf = log_buf;
9833 	prog->log_size = log_size;
9834 	return 0;
9835 }
9836 
9837 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9838 {
9839 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9840 		return libbpf_err_ptr(-EOPNOTSUPP);
9841 	return prog->func_info;
9842 }
9843 
9844 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9845 {
9846 	return prog->func_info_cnt;
9847 }
9848 
9849 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9850 {
9851 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9852 		return libbpf_err_ptr(-EOPNOTSUPP);
9853 	return prog->line_info;
9854 }
9855 
9856 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9857 {
9858 	return prog->line_info_cnt;
9859 }
9860 
9861 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
9862 {
9863 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
9864 	struct bpf_object *obj;
9865 	const void *info;
9866 	__u32 info_cnt, info_rec_size;
9867 	int err, fd, prog_btf_fd;
9868 
9869 	if (!prog)
9870 		return libbpf_err(-EINVAL);
9871 
9872 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
9873 		return libbpf_err(-EINVAL);
9874 
9875 	obj = prog->obj;
9876 	if (obj->state < OBJ_PREPARED)
9877 		return libbpf_err(-EINVAL);
9878 
9879 	/*
9880 	 * Caller-provided opts take priority; fall back to
9881 	 * prog/object defaults when the caller leaves them zero.
9882 	 */
9883 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
9884 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
9885 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
9886 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
9887 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
9888 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
9889 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
9890 	if (attr.token_fd)
9891 		attr.prog_flags |= BPF_F_TOKEN_FD;
9892 
9893 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
9894 	if (!prog_btf_fd && obj->btf)
9895 		prog_btf_fd = btf__fd(obj->btf);
9896 
9897 	/* BTF func/line info: only pass if kernel supports it */
9898 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
9899 		attr.prog_btf_fd = prog_btf_fd;
9900 
9901 		/* func_info/line_info triples: all-or-nothing from caller */
9902 		info = OPTS_GET(opts, func_info, NULL);
9903 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
9904 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
9905 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9906 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
9907 				prog->name);
9908 			return libbpf_err(-EINVAL);
9909 		}
9910 		attr.func_info = info ?: prog->func_info;
9911 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
9912 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
9913 
9914 		info = OPTS_GET(opts, line_info, NULL);
9915 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
9916 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
9917 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9918 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
9919 				prog->name);
9920 			return libbpf_err(-EINVAL);
9921 		}
9922 		attr.line_info = info ?: prog->line_info;
9923 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
9924 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
9925 	}
9926 
9927 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
9928 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
9929 	attr.log_size = OPTS_GET(opts, log_size, 0);
9930 	attr.log_level = OPTS_GET(opts, log_level, 0);
9931 
9932 	/*
9933 	 * Fields below may be mutated by prog_prepare_load_fn:
9934 	 * Seed them from prog/obj defaults here;
9935 	 * Later override with caller-provided opts.
9936 	 */
9937 	attr.expected_attach_type = prog->expected_attach_type;
9938 	attr.attach_btf_id = prog->attach_btf_id;
9939 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
9940 
9941 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
9942 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
9943 		if (err)
9944 			return libbpf_err(err);
9945 	}
9946 
9947 	/* Re-apply caller overrides for output fields */
9948 	if (OPTS_GET(opts, expected_attach_type, 0))
9949 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
9950 	if (OPTS_GET(opts, attach_btf_id, 0))
9951 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
9952 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
9953 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
9954 
9955 	/*
9956 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
9957 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
9958 	 * required maps themselves using bpf_prog_bind_map().
9959 	 */
9960 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
9961 			   &attr);
9962 
9963 	return libbpf_err(fd);
9964 }
9965 
9966 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9967 	.sec = (char *)sec_pfx,						    \
9968 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9969 	.expected_attach_type = atype,					    \
9970 	.cookie = (long)(flags),					    \
9971 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9972 	__VA_ARGS__							    \
9973 }
9974 
9975 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9976 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9977 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9978 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9979 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9980 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9981 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9982 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9983 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9984 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9985 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9986 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9987 
9988 static const struct bpf_sec_def section_defs[] = {
9989 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9990 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9991 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9992 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9993 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9994 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9995 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9996 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9997 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9998 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9999 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10000 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10001 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10002 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10003 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10004 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10005 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10006 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10007 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10008 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10009 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10010 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10011 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10012 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10013 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10014 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10015 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10016 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10017 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10018 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10019 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10020 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10021 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10022 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10023 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10024 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10025 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10026 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10027 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10028 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10029 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10030 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10031 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10032 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10033 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10034 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10035 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10036 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10037 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10038 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10039 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10040 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10041 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10042 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10043 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10044 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10045 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10046 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10047 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10048 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10049 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10050 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10051 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10052 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10053 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10054 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10055 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10056 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10057 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10058 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10059 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10060 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10061 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10062 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10063 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10064 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10065 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10066 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10067 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10068 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10069 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10070 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10071 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10072 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10073 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10074 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10075 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10076 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10077 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10078 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10079 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10080 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10081 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10082 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10083 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10084 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10085 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10086 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10087 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10088 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10089 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10090 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10091 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10092 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10093 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10094 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10095 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10096 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10097 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10098 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10099 };
10100 
10101 int libbpf_register_prog_handler(const char *sec,
10102 				 enum bpf_prog_type prog_type,
10103 				 enum bpf_attach_type exp_attach_type,
10104 				 const struct libbpf_prog_handler_opts *opts)
10105 {
10106 	struct bpf_sec_def *sec_def;
10107 
10108 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10109 		return libbpf_err(-EINVAL);
10110 
10111 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10112 		return libbpf_err(-E2BIG);
10113 
10114 	if (sec) {
10115 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10116 					      sizeof(*sec_def));
10117 		if (!sec_def)
10118 			return libbpf_err(-ENOMEM);
10119 
10120 		custom_sec_defs = sec_def;
10121 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10122 	} else {
10123 		if (has_custom_fallback_def)
10124 			return libbpf_err(-EBUSY);
10125 
10126 		sec_def = &custom_fallback_def;
10127 	}
10128 
10129 	sec_def->sec = sec ? strdup(sec) : NULL;
10130 	if (sec && !sec_def->sec)
10131 		return libbpf_err(-ENOMEM);
10132 
10133 	sec_def->prog_type = prog_type;
10134 	sec_def->expected_attach_type = exp_attach_type;
10135 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10136 
10137 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10138 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10139 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10140 
10141 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10142 
10143 	if (sec)
10144 		custom_sec_def_cnt++;
10145 	else
10146 		has_custom_fallback_def = true;
10147 
10148 	return sec_def->handler_id;
10149 }
10150 
10151 int libbpf_unregister_prog_handler(int handler_id)
10152 {
10153 	struct bpf_sec_def *sec_defs;
10154 	int i;
10155 
10156 	if (handler_id <= 0)
10157 		return libbpf_err(-EINVAL);
10158 
10159 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10160 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10161 		has_custom_fallback_def = false;
10162 		return 0;
10163 	}
10164 
10165 	for (i = 0; i < custom_sec_def_cnt; i++) {
10166 		if (custom_sec_defs[i].handler_id == handler_id)
10167 			break;
10168 	}
10169 
10170 	if (i == custom_sec_def_cnt)
10171 		return libbpf_err(-ENOENT);
10172 
10173 	free(custom_sec_defs[i].sec);
10174 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10175 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10176 	custom_sec_def_cnt--;
10177 
10178 	/* try to shrink the array, but it's ok if we couldn't */
10179 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10180 	/* if new count is zero, reallocarray can return a valid NULL result;
10181 	 * in this case the previous pointer will be freed, so we *have to*
10182 	 * reassign old pointer to the new value (even if it's NULL)
10183 	 */
10184 	if (sec_defs || custom_sec_def_cnt == 0)
10185 		custom_sec_defs = sec_defs;
10186 
10187 	return 0;
10188 }
10189 
10190 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10191 {
10192 	size_t len = strlen(sec_def->sec);
10193 
10194 	/* "type/" always has to have proper SEC("type/extras") form */
10195 	if (sec_def->sec[len - 1] == '/') {
10196 		if (str_has_pfx(sec_name, sec_def->sec))
10197 			return true;
10198 		return false;
10199 	}
10200 
10201 	/* "type+" means it can be either exact SEC("type") or
10202 	 * well-formed SEC("type/extras") with proper '/' separator
10203 	 */
10204 	if (sec_def->sec[len - 1] == '+') {
10205 		len--;
10206 		/* not even a prefix */
10207 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10208 			return false;
10209 		/* exact match or has '/' separator */
10210 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10211 			return true;
10212 		return false;
10213 	}
10214 
10215 	return strcmp(sec_name, sec_def->sec) == 0;
10216 }
10217 
10218 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10219 {
10220 	const struct bpf_sec_def *sec_def;
10221 	int i, n;
10222 
10223 	n = custom_sec_def_cnt;
10224 	for (i = 0; i < n; i++) {
10225 		sec_def = &custom_sec_defs[i];
10226 		if (sec_def_matches(sec_def, sec_name))
10227 			return sec_def;
10228 	}
10229 
10230 	n = ARRAY_SIZE(section_defs);
10231 	for (i = 0; i < n; i++) {
10232 		sec_def = &section_defs[i];
10233 		if (sec_def_matches(sec_def, sec_name))
10234 			return sec_def;
10235 	}
10236 
10237 	if (has_custom_fallback_def)
10238 		return &custom_fallback_def;
10239 
10240 	return NULL;
10241 }
10242 
10243 #define MAX_TYPE_NAME_SIZE 32
10244 
10245 static char *libbpf_get_type_names(bool attach_type)
10246 {
10247 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10248 	char *buf;
10249 
10250 	buf = malloc(len);
10251 	if (!buf)
10252 		return NULL;
10253 
10254 	buf[0] = '\0';
10255 	/* Forge string buf with all available names */
10256 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10257 		const struct bpf_sec_def *sec_def = &section_defs[i];
10258 
10259 		if (attach_type) {
10260 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10261 				continue;
10262 
10263 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10264 				continue;
10265 		}
10266 
10267 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10268 			free(buf);
10269 			return NULL;
10270 		}
10271 		strcat(buf, " ");
10272 		strcat(buf, section_defs[i].sec);
10273 	}
10274 
10275 	return buf;
10276 }
10277 
10278 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10279 			     enum bpf_attach_type *expected_attach_type)
10280 {
10281 	const struct bpf_sec_def *sec_def;
10282 	char *type_names;
10283 
10284 	if (!name)
10285 		return libbpf_err(-EINVAL);
10286 
10287 	sec_def = find_sec_def(name);
10288 	if (sec_def) {
10289 		*prog_type = sec_def->prog_type;
10290 		*expected_attach_type = sec_def->expected_attach_type;
10291 		return 0;
10292 	}
10293 
10294 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10295 	type_names = libbpf_get_type_names(false);
10296 	if (type_names != NULL) {
10297 		pr_debug("supported section(type) names are:%s\n", type_names);
10298 		free(type_names);
10299 	}
10300 
10301 	return libbpf_err(-ESRCH);
10302 }
10303 
10304 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10305 {
10306 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10307 		return NULL;
10308 
10309 	return attach_type_name[t];
10310 }
10311 
10312 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10313 {
10314 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10315 		return NULL;
10316 
10317 	return link_type_name[t];
10318 }
10319 
10320 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10321 {
10322 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10323 		return NULL;
10324 
10325 	return map_type_name[t];
10326 }
10327 
10328 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10329 {
10330 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10331 		return NULL;
10332 
10333 	return prog_type_name[t];
10334 }
10335 
10336 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10337 						     int sec_idx,
10338 						     size_t offset)
10339 {
10340 	struct bpf_map *map;
10341 	size_t i;
10342 
10343 	for (i = 0; i < obj->nr_maps; i++) {
10344 		map = &obj->maps[i];
10345 		if (!bpf_map__is_struct_ops(map))
10346 			continue;
10347 		if (map->sec_idx == sec_idx &&
10348 		    map->sec_offset <= offset &&
10349 		    offset - map->sec_offset < map->def.value_size)
10350 			return map;
10351 	}
10352 
10353 	return NULL;
10354 }
10355 
10356 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10357  * st_ops->data for shadow type.
10358  */
10359 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10360 					    Elf64_Shdr *shdr, Elf_Data *data)
10361 {
10362 	const struct btf_type *type;
10363 	const struct btf_member *member;
10364 	struct bpf_struct_ops *st_ops;
10365 	struct bpf_program *prog;
10366 	unsigned int shdr_idx;
10367 	const struct btf *btf;
10368 	struct bpf_map *map;
10369 	unsigned int moff, insn_idx;
10370 	const char *name;
10371 	__u32 member_idx;
10372 	Elf64_Sym *sym;
10373 	Elf64_Rel *rel;
10374 	int i, nrels;
10375 
10376 	btf = obj->btf;
10377 	nrels = shdr->sh_size / shdr->sh_entsize;
10378 	for (i = 0; i < nrels; i++) {
10379 		rel = elf_rel_by_idx(data, i);
10380 		if (!rel) {
10381 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10382 			return -LIBBPF_ERRNO__FORMAT;
10383 		}
10384 
10385 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10386 		if (!sym) {
10387 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10388 				(size_t)ELF64_R_SYM(rel->r_info));
10389 			return -LIBBPF_ERRNO__FORMAT;
10390 		}
10391 
10392 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10393 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10394 		if (!map) {
10395 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10396 				(size_t)rel->r_offset);
10397 			return -EINVAL;
10398 		}
10399 
10400 		moff = rel->r_offset - map->sec_offset;
10401 		shdr_idx = sym->st_shndx;
10402 		st_ops = map->st_ops;
10403 		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",
10404 			 map->name,
10405 			 (long long)(rel->r_info >> 32),
10406 			 (long long)sym->st_value,
10407 			 shdr_idx, (size_t)rel->r_offset,
10408 			 map->sec_offset, sym->st_name, name);
10409 
10410 		if (shdr_idx >= SHN_LORESERVE) {
10411 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10412 				map->name, (size_t)rel->r_offset, shdr_idx);
10413 			return -LIBBPF_ERRNO__RELOC;
10414 		}
10415 		if (sym->st_value % BPF_INSN_SZ) {
10416 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10417 				map->name, (unsigned long long)sym->st_value);
10418 			return -LIBBPF_ERRNO__FORMAT;
10419 		}
10420 		insn_idx = sym->st_value / BPF_INSN_SZ;
10421 
10422 		type = btf__type_by_id(btf, st_ops->type_id);
10423 		member = find_member_by_offset(type, moff * 8);
10424 		if (!member) {
10425 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10426 				map->name, moff);
10427 			return -EINVAL;
10428 		}
10429 		member_idx = member - btf_members(type);
10430 		name = btf__name_by_offset(btf, member->name_off);
10431 
10432 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10433 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10434 				map->name, name);
10435 			return -EINVAL;
10436 		}
10437 
10438 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10439 		if (!prog) {
10440 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10441 				map->name, shdr_idx, name);
10442 			return -EINVAL;
10443 		}
10444 
10445 		/* prevent the use of BPF prog with invalid type */
10446 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10447 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10448 				map->name, prog->name);
10449 			return -EINVAL;
10450 		}
10451 
10452 		st_ops->progs[member_idx] = prog;
10453 
10454 		/* st_ops->data will be exposed to users, being returned by
10455 		 * bpf_map__initial_value() as a pointer to the shadow
10456 		 * type. All function pointers in the original struct type
10457 		 * should be converted to a pointer to struct bpf_program
10458 		 * in the shadow type.
10459 		 */
10460 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10461 	}
10462 
10463 	return 0;
10464 }
10465 
10466 #define BTF_TRACE_PREFIX "btf_trace_"
10467 #define BTF_LSM_PREFIX "bpf_lsm_"
10468 #define BTF_ITER_PREFIX "bpf_iter_"
10469 #define BTF_MAX_NAME_SIZE 128
10470 
10471 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10472 				const char **prefix, int *kind)
10473 {
10474 	switch (attach_type) {
10475 	case BPF_TRACE_RAW_TP:
10476 		*prefix = BTF_TRACE_PREFIX;
10477 		*kind = BTF_KIND_TYPEDEF;
10478 		break;
10479 	case BPF_LSM_MAC:
10480 	case BPF_LSM_CGROUP:
10481 		*prefix = BTF_LSM_PREFIX;
10482 		*kind = BTF_KIND_FUNC;
10483 		break;
10484 	case BPF_TRACE_ITER:
10485 		*prefix = BTF_ITER_PREFIX;
10486 		*kind = BTF_KIND_FUNC;
10487 		break;
10488 	default:
10489 		*prefix = "";
10490 		*kind = BTF_KIND_FUNC;
10491 	}
10492 }
10493 
10494 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10495 				   const char *name, __u32 kind)
10496 {
10497 	char btf_type_name[BTF_MAX_NAME_SIZE];
10498 	int ret;
10499 
10500 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10501 		       "%s%s", prefix, name);
10502 	/* snprintf returns the number of characters written excluding the
10503 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10504 	 * indicates truncation.
10505 	 */
10506 	if (ret < 0 || ret >= sizeof(btf_type_name))
10507 		return -ENAMETOOLONG;
10508 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10509 }
10510 
10511 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10512 				     enum bpf_attach_type attach_type)
10513 {
10514 	const char *prefix;
10515 	int kind;
10516 
10517 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10518 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10519 }
10520 
10521 int libbpf_find_vmlinux_btf_id(const char *name,
10522 			       enum bpf_attach_type attach_type)
10523 {
10524 	struct btf *btf;
10525 	int err;
10526 
10527 	btf = btf__load_vmlinux_btf();
10528 	err = libbpf_get_error(btf);
10529 	if (err) {
10530 		pr_warn("vmlinux BTF is not found\n");
10531 		return libbpf_err(err);
10532 	}
10533 
10534 	err = find_attach_btf_id(btf, name, attach_type);
10535 	if (err <= 0)
10536 		pr_warn("%s is not found in vmlinux BTF\n", name);
10537 
10538 	btf__free(btf);
10539 	return libbpf_err(err);
10540 }
10541 
10542 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10543 {
10544 	struct bpf_prog_info info;
10545 	__u32 info_len = sizeof(info);
10546 	struct btf *btf;
10547 	int err;
10548 
10549 	memset(&info, 0, info_len);
10550 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10551 	if (err) {
10552 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10553 			attach_prog_fd, errstr(err));
10554 		return err;
10555 	}
10556 
10557 	err = -EINVAL;
10558 	if (!info.btf_id) {
10559 		pr_warn("The target program doesn't have BTF\n");
10560 		goto out;
10561 	}
10562 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10563 	err = libbpf_get_error(btf);
10564 	if (err) {
10565 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10566 		goto out;
10567 	}
10568 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10569 	btf__free(btf);
10570 	if (err <= 0) {
10571 		pr_warn("%s is not found in prog's BTF\n", name);
10572 		goto out;
10573 	}
10574 out:
10575 	return err;
10576 }
10577 
10578 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10579 			      enum bpf_attach_type attach_type,
10580 			      int *btf_obj_fd, int *btf_type_id)
10581 {
10582 	int ret, i, mod_len = 0;
10583 	const char *fn_name, *mod_name = NULL;
10584 
10585 	fn_name = strchr(attach_name, ':');
10586 	if (fn_name) {
10587 		mod_name = attach_name;
10588 		mod_len = fn_name - mod_name;
10589 		fn_name++;
10590 	}
10591 
10592 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10593 		ret = find_attach_btf_id(obj->btf_vmlinux,
10594 					 mod_name ? fn_name : attach_name,
10595 					 attach_type);
10596 		if (ret > 0) {
10597 			*btf_obj_fd = 0; /* vmlinux BTF */
10598 			*btf_type_id = ret;
10599 			return 0;
10600 		}
10601 		if (ret != -ENOENT)
10602 			return ret;
10603 	}
10604 
10605 	ret = load_module_btfs(obj);
10606 	if (ret)
10607 		return ret;
10608 
10609 	for (i = 0; i < obj->btf_module_cnt; i++) {
10610 		const struct module_btf *mod = &obj->btf_modules[i];
10611 
10612 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10613 			continue;
10614 
10615 		ret = find_attach_btf_id(mod->btf,
10616 					 mod_name ? fn_name : attach_name,
10617 					 attach_type);
10618 		if (ret > 0) {
10619 			*btf_obj_fd = mod->fd;
10620 			*btf_type_id = ret;
10621 			return 0;
10622 		}
10623 		if (ret == -ENOENT)
10624 			continue;
10625 
10626 		return ret;
10627 	}
10628 
10629 	return -ESRCH;
10630 }
10631 
10632 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10633 				     int *btf_obj_fd, int *btf_type_id)
10634 {
10635 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10636 	__u32 attach_prog_fd = prog->attach_prog_fd;
10637 	int err = 0;
10638 
10639 	/* BPF program's BTF ID */
10640 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10641 		if (!attach_prog_fd) {
10642 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10643 			return -EINVAL;
10644 		}
10645 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10646 		if (err < 0) {
10647 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10648 				prog->name, attach_prog_fd, attach_name, errstr(err));
10649 			return err;
10650 		}
10651 		*btf_obj_fd = 0;
10652 		*btf_type_id = err;
10653 		return 0;
10654 	}
10655 
10656 	/* kernel/module BTF ID */
10657 	if (prog->obj->gen_loader) {
10658 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10659 		*btf_obj_fd = 0;
10660 		*btf_type_id = 1;
10661 	} else {
10662 		err = find_kernel_btf_id(prog->obj, attach_name,
10663 					 attach_type, btf_obj_fd,
10664 					 btf_type_id);
10665 	}
10666 	if (err) {
10667 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10668 			prog->name, attach_name, errstr(err));
10669 		return err;
10670 	}
10671 	return 0;
10672 }
10673 
10674 int libbpf_attach_type_by_name(const char *name,
10675 			       enum bpf_attach_type *attach_type)
10676 {
10677 	char *type_names;
10678 	const struct bpf_sec_def *sec_def;
10679 
10680 	if (!name)
10681 		return libbpf_err(-EINVAL);
10682 
10683 	sec_def = find_sec_def(name);
10684 	if (!sec_def) {
10685 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10686 		type_names = libbpf_get_type_names(true);
10687 		if (type_names != NULL) {
10688 			pr_debug("attachable section(type) names are:%s\n", type_names);
10689 			free(type_names);
10690 		}
10691 
10692 		return libbpf_err(-EINVAL);
10693 	}
10694 
10695 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10696 		return libbpf_err(-EINVAL);
10697 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10698 		return libbpf_err(-EINVAL);
10699 
10700 	*attach_type = sec_def->expected_attach_type;
10701 	return 0;
10702 }
10703 
10704 int bpf_map__fd(const struct bpf_map *map)
10705 {
10706 	if (!map)
10707 		return libbpf_err(-EINVAL);
10708 	if (!map_is_created(map))
10709 		return -1;
10710 	return map->fd;
10711 }
10712 
10713 static bool map_uses_real_name(const struct bpf_map *map)
10714 {
10715 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10716 	 * their user-visible name differs from kernel-visible name. Users see
10717 	 * such map's corresponding ELF section name as a map name.
10718 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10719 	 * maps to know which name has to be returned to the user.
10720 	 */
10721 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10722 		return true;
10723 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10724 		return true;
10725 	return false;
10726 }
10727 
10728 const char *bpf_map__name(const struct bpf_map *map)
10729 {
10730 	if (!map)
10731 		return NULL;
10732 
10733 	if (map_uses_real_name(map))
10734 		return map->real_name;
10735 
10736 	return map->name;
10737 }
10738 
10739 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10740 {
10741 	return map->def.type;
10742 }
10743 
10744 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10745 {
10746 	if (map_is_created(map))
10747 		return libbpf_err(-EBUSY);
10748 	map->def.type = type;
10749 	return 0;
10750 }
10751 
10752 __u32 bpf_map__map_flags(const struct bpf_map *map)
10753 {
10754 	return map->def.map_flags;
10755 }
10756 
10757 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10758 {
10759 	if (map_is_created(map))
10760 		return libbpf_err(-EBUSY);
10761 	map->def.map_flags = flags;
10762 	return 0;
10763 }
10764 
10765 __u64 bpf_map__map_extra(const struct bpf_map *map)
10766 {
10767 	return map->map_extra;
10768 }
10769 
10770 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10771 {
10772 	if (map_is_created(map))
10773 		return libbpf_err(-EBUSY);
10774 	map->map_extra = map_extra;
10775 	return 0;
10776 }
10777 
10778 __u32 bpf_map__numa_node(const struct bpf_map *map)
10779 {
10780 	return map->numa_node;
10781 }
10782 
10783 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10784 {
10785 	if (map_is_created(map))
10786 		return libbpf_err(-EBUSY);
10787 	map->numa_node = numa_node;
10788 	return 0;
10789 }
10790 
10791 __u32 bpf_map__key_size(const struct bpf_map *map)
10792 {
10793 	return map->def.key_size;
10794 }
10795 
10796 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10797 {
10798 	if (map_is_created(map))
10799 		return libbpf_err(-EBUSY);
10800 	map->def.key_size = size;
10801 	return 0;
10802 }
10803 
10804 __u32 bpf_map__value_size(const struct bpf_map *map)
10805 {
10806 	return map->def.value_size;
10807 }
10808 
10809 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10810 {
10811 	struct btf *btf;
10812 	struct btf_type *datasec_type, *var_type;
10813 	struct btf_var_secinfo *var;
10814 	const struct btf_type *array_type;
10815 	const struct btf_array *array;
10816 	int vlen, element_sz, new_array_id;
10817 	__u32 nr_elements;
10818 
10819 	/* check btf existence */
10820 	btf = bpf_object__btf(map->obj);
10821 	if (!btf)
10822 		return -ENOENT;
10823 
10824 	/* verify map is datasec */
10825 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10826 	if (!btf_is_datasec(datasec_type)) {
10827 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10828 			bpf_map__name(map));
10829 		return -EINVAL;
10830 	}
10831 
10832 	/* verify datasec has at least one var */
10833 	vlen = btf_vlen(datasec_type);
10834 	if (vlen == 0) {
10835 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10836 			bpf_map__name(map));
10837 		return -EINVAL;
10838 	}
10839 
10840 	/* verify last var in the datasec is an array */
10841 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10842 	var_type = btf_type_by_id(btf, var->type);
10843 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10844 	if (!btf_is_array(array_type)) {
10845 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10846 			bpf_map__name(map));
10847 		return -EINVAL;
10848 	}
10849 
10850 	/* verify request size aligns with array */
10851 	array = btf_array(array_type);
10852 	element_sz = btf__resolve_size(btf, array->type);
10853 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10854 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10855 			bpf_map__name(map), element_sz, size);
10856 		return -EINVAL;
10857 	}
10858 
10859 	/* create a new array based on the existing array, but with new length */
10860 	nr_elements = (size - var->offset) / element_sz;
10861 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10862 	if (new_array_id < 0)
10863 		return new_array_id;
10864 
10865 	/* adding a new btf type invalidates existing pointers to btf objects,
10866 	 * so refresh pointers before proceeding
10867 	 */
10868 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10869 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10870 	var_type = btf_type_by_id(btf, var->type);
10871 
10872 	/* finally update btf info */
10873 	datasec_type->size = size;
10874 	var->size = size - var->offset;
10875 	var_type->type = new_array_id;
10876 
10877 	return 0;
10878 }
10879 
10880 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10881 {
10882 	if (map_is_created(map))
10883 		return libbpf_err(-EBUSY);
10884 
10885 	if (map->mmaped) {
10886 		size_t mmap_old_sz, mmap_new_sz;
10887 		int err;
10888 
10889 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10890 			return libbpf_err(-EOPNOTSUPP);
10891 
10892 		mmap_old_sz = bpf_map_mmap_sz(map);
10893 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10894 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10895 		if (err) {
10896 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10897 				bpf_map__name(map), errstr(err));
10898 			return libbpf_err(err);
10899 		}
10900 		err = map_btf_datasec_resize(map, size);
10901 		if (err && err != -ENOENT) {
10902 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10903 				bpf_map__name(map), errstr(err));
10904 			map->btf_value_type_id = 0;
10905 			map->btf_key_type_id = 0;
10906 		}
10907 	}
10908 
10909 	map->def.value_size = size;
10910 	return 0;
10911 }
10912 
10913 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10914 {
10915 	return map ? map->btf_key_type_id : 0;
10916 }
10917 
10918 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10919 {
10920 	return map ? map->btf_value_type_id : 0;
10921 }
10922 
10923 int bpf_map__set_initial_value(struct bpf_map *map,
10924 			       const void *data, size_t size)
10925 {
10926 	size_t actual_sz;
10927 
10928 	if (map_is_created(map))
10929 		return libbpf_err(-EBUSY);
10930 
10931 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10932 		return libbpf_err(-EINVAL);
10933 
10934 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10935 		actual_sz = map->obj->arena_data_sz;
10936 	else
10937 		actual_sz = map->def.value_size;
10938 	if (size != actual_sz)
10939 		return libbpf_err(-EINVAL);
10940 
10941 	memcpy(map->mmaped, data, size);
10942 	return 0;
10943 }
10944 
10945 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10946 {
10947 	if (bpf_map__is_struct_ops(map)) {
10948 		if (psize)
10949 			*psize = map->def.value_size;
10950 		return map->st_ops->data;
10951 	}
10952 
10953 	if (!map->mmaped)
10954 		return NULL;
10955 
10956 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10957 		*psize = map->obj->arena_data_sz;
10958 	else
10959 		*psize = map->def.value_size;
10960 
10961 	return map->mmaped;
10962 }
10963 
10964 bool bpf_map__is_internal(const struct bpf_map *map)
10965 {
10966 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10967 }
10968 
10969 __u32 bpf_map__ifindex(const struct bpf_map *map)
10970 {
10971 	return map->map_ifindex;
10972 }
10973 
10974 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10975 {
10976 	if (map_is_created(map))
10977 		return libbpf_err(-EBUSY);
10978 	map->map_ifindex = ifindex;
10979 	return 0;
10980 }
10981 
10982 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10983 {
10984 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10985 		pr_warn("error: unsupported map type\n");
10986 		return libbpf_err(-EINVAL);
10987 	}
10988 	if (map->inner_map_fd != -1) {
10989 		pr_warn("error: inner_map_fd already specified\n");
10990 		return libbpf_err(-EINVAL);
10991 	}
10992 	if (map->inner_map) {
10993 		bpf_map__destroy(map->inner_map);
10994 		zfree(&map->inner_map);
10995 	}
10996 	map->inner_map_fd = fd;
10997 	return 0;
10998 }
10999 
11000 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
11001 {
11002 	if (map_is_created(map)) {
11003 		pr_warn("exclusive programs must be set before map creation\n");
11004 		return libbpf_err(-EINVAL);
11005 	}
11006 
11007 	if (map->obj != prog->obj) {
11008 		pr_warn("excl_prog and map must be from the same bpf object\n");
11009 		return libbpf_err(-EINVAL);
11010 	}
11011 
11012 	map->excl_prog = prog;
11013 	return 0;
11014 }
11015 
11016 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11017 {
11018 	return map->excl_prog;
11019 }
11020 
11021 static struct bpf_map *
11022 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11023 {
11024 	ssize_t idx;
11025 	struct bpf_map *s, *e;
11026 
11027 	if (!obj || !obj->maps)
11028 		return errno = EINVAL, NULL;
11029 
11030 	s = obj->maps;
11031 	e = obj->maps + obj->nr_maps;
11032 
11033 	if ((m < s) || (m >= e)) {
11034 		pr_warn("error in %s: map handler doesn't belong to object\n",
11035 			 __func__);
11036 		return errno = EINVAL, NULL;
11037 	}
11038 
11039 	idx = (m - obj->maps) + i;
11040 	if (idx >= obj->nr_maps || idx < 0)
11041 		return NULL;
11042 	return &obj->maps[idx];
11043 }
11044 
11045 struct bpf_map *
11046 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11047 {
11048 	if (prev == NULL && obj != NULL)
11049 		return obj->maps;
11050 
11051 	return __bpf_map__iter(prev, obj, 1);
11052 }
11053 
11054 struct bpf_map *
11055 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11056 {
11057 	if (next == NULL && obj != NULL) {
11058 		if (!obj->nr_maps)
11059 			return NULL;
11060 		return obj->maps + obj->nr_maps - 1;
11061 	}
11062 
11063 	return __bpf_map__iter(next, obj, -1);
11064 }
11065 
11066 struct bpf_map *
11067 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11068 {
11069 	struct bpf_map *pos;
11070 
11071 	bpf_object__for_each_map(pos, obj) {
11072 		/* if it's a special internal map name (which always starts
11073 		 * with dot) then check if that special name matches the
11074 		 * real map name (ELF section name)
11075 		 */
11076 		if (name[0] == '.') {
11077 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11078 				return pos;
11079 			continue;
11080 		}
11081 		/* otherwise map name has to be an exact match */
11082 		if (map_uses_real_name(pos)) {
11083 			if (strcmp(pos->real_name, name) == 0)
11084 				return pos;
11085 			continue;
11086 		}
11087 		if (strcmp(pos->name, name) == 0)
11088 			return pos;
11089 	}
11090 	return errno = ENOENT, NULL;
11091 }
11092 
11093 int
11094 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11095 {
11096 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11097 }
11098 
11099 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11100 			   size_t value_sz, bool check_value_sz, __u64 flags)
11101 {
11102 	if (!map_is_created(map)) /* map is not yet created */
11103 		return -ENOENT;
11104 
11105 	if (map->def.key_size != key_sz) {
11106 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11107 			map->name, key_sz, map->def.key_size);
11108 		return -EINVAL;
11109 	}
11110 
11111 	if (map->fd < 0) {
11112 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11113 		return -EINVAL;
11114 	}
11115 
11116 	if (!check_value_sz)
11117 		return 0;
11118 
11119 	switch (map->def.type) {
11120 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11121 	case BPF_MAP_TYPE_PERCPU_HASH:
11122 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11123 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11124 		int num_cpu = libbpf_num_possible_cpus();
11125 		size_t elem_sz = roundup(map->def.value_size, 8);
11126 
11127 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11128 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11129 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11130 					map->name);
11131 				return -EINVAL;
11132 			}
11133 			if (map->def.value_size != value_sz) {
11134 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11135 					map->name, value_sz, map->def.value_size);
11136 				return -EINVAL;
11137 			}
11138 			break;
11139 		}
11140 
11141 		if (value_sz != num_cpu * elem_sz) {
11142 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
11143 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11144 			return -EINVAL;
11145 		}
11146 		break;
11147 	}
11148 	default:
11149 		if (map->def.value_size != value_sz) {
11150 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11151 				map->name, value_sz, map->def.value_size);
11152 			return -EINVAL;
11153 		}
11154 		break;
11155 	}
11156 	return 0;
11157 }
11158 
11159 int bpf_map__lookup_elem(const struct bpf_map *map,
11160 			 const void *key, size_t key_sz,
11161 			 void *value, size_t value_sz, __u64 flags)
11162 {
11163 	int err;
11164 
11165 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11166 	if (err)
11167 		return libbpf_err(err);
11168 
11169 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11170 }
11171 
11172 int bpf_map__update_elem(const struct bpf_map *map,
11173 			 const void *key, size_t key_sz,
11174 			 const void *value, size_t value_sz, __u64 flags)
11175 {
11176 	int err;
11177 
11178 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11179 	if (err)
11180 		return libbpf_err(err);
11181 
11182 	return bpf_map_update_elem(map->fd, key, value, flags);
11183 }
11184 
11185 int bpf_map__delete_elem(const struct bpf_map *map,
11186 			 const void *key, size_t key_sz, __u64 flags)
11187 {
11188 	int err;
11189 
11190 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11191 	if (err)
11192 		return libbpf_err(err);
11193 
11194 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11195 }
11196 
11197 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11198 				    const void *key, size_t key_sz,
11199 				    void *value, size_t value_sz, __u64 flags)
11200 {
11201 	int err;
11202 
11203 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11204 	if (err)
11205 		return libbpf_err(err);
11206 
11207 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11208 }
11209 
11210 int bpf_map__get_next_key(const struct bpf_map *map,
11211 			  const void *cur_key, void *next_key, size_t key_sz)
11212 {
11213 	int err;
11214 
11215 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11216 	if (err)
11217 		return libbpf_err(err);
11218 
11219 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11220 }
11221 
11222 long libbpf_get_error(const void *ptr)
11223 {
11224 	if (!IS_ERR_OR_NULL(ptr))
11225 		return 0;
11226 
11227 	if (IS_ERR(ptr))
11228 		errno = -PTR_ERR(ptr);
11229 
11230 	/* If ptr == NULL, then errno should be already set by the failing
11231 	 * API, because libbpf never returns NULL on success and it now always
11232 	 * sets errno on error. So no extra errno handling for ptr == NULL
11233 	 * case.
11234 	 */
11235 	return -errno;
11236 }
11237 
11238 /* Replace link's underlying BPF program with the new one */
11239 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11240 {
11241 	int ret;
11242 	int prog_fd = bpf_program__fd(prog);
11243 
11244 	if (prog_fd < 0) {
11245 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11246 			prog->name);
11247 		return libbpf_err(-EINVAL);
11248 	}
11249 
11250 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11251 	return libbpf_err_errno(ret);
11252 }
11253 
11254 /* Release "ownership" of underlying BPF resource (typically, BPF program
11255  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11256  * link, when destructed through bpf_link__destroy() call won't attempt to
11257  * detach/unregisted that BPF resource. This is useful in situations where,
11258  * say, attached BPF program has to outlive userspace program that attached it
11259  * in the system. Depending on type of BPF program, though, there might be
11260  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11261  * exit of userspace program doesn't trigger automatic detachment and clean up
11262  * inside the kernel.
11263  */
11264 void bpf_link__disconnect(struct bpf_link *link)
11265 {
11266 	link->disconnected = true;
11267 }
11268 
11269 int bpf_link__destroy(struct bpf_link *link)
11270 {
11271 	int err = 0;
11272 
11273 	if (IS_ERR_OR_NULL(link))
11274 		return 0;
11275 
11276 	if (!link->disconnected && link->detach)
11277 		err = link->detach(link);
11278 	if (link->pin_path)
11279 		free(link->pin_path);
11280 	if (link->dealloc)
11281 		link->dealloc(link);
11282 	else
11283 		free(link);
11284 
11285 	return libbpf_err(err);
11286 }
11287 
11288 int bpf_link__fd(const struct bpf_link *link)
11289 {
11290 	return link->fd;
11291 }
11292 
11293 const char *bpf_link__pin_path(const struct bpf_link *link)
11294 {
11295 	return link->pin_path;
11296 }
11297 
11298 static int bpf_link__detach_fd(struct bpf_link *link)
11299 {
11300 	return libbpf_err_errno(close(link->fd));
11301 }
11302 
11303 struct bpf_link *bpf_link__open(const char *path)
11304 {
11305 	struct bpf_link *link;
11306 	int fd;
11307 
11308 	fd = bpf_obj_get(path);
11309 	if (fd < 0) {
11310 		fd = -errno;
11311 		pr_warn("failed to open link at %s: %d\n", path, fd);
11312 		return libbpf_err_ptr(fd);
11313 	}
11314 
11315 	link = calloc(1, sizeof(*link));
11316 	if (!link) {
11317 		close(fd);
11318 		return libbpf_err_ptr(-ENOMEM);
11319 	}
11320 	link->detach = &bpf_link__detach_fd;
11321 	link->fd = fd;
11322 
11323 	link->pin_path = strdup(path);
11324 	if (!link->pin_path) {
11325 		bpf_link__destroy(link);
11326 		return libbpf_err_ptr(-ENOMEM);
11327 	}
11328 
11329 	return link;
11330 }
11331 
11332 int bpf_link__detach(struct bpf_link *link)
11333 {
11334 	return bpf_link_detach(link->fd) ? -errno : 0;
11335 }
11336 
11337 int bpf_link__pin(struct bpf_link *link, const char *path)
11338 {
11339 	int err;
11340 
11341 	if (link->pin_path)
11342 		return libbpf_err(-EBUSY);
11343 	err = make_parent_dir(path);
11344 	if (err)
11345 		return libbpf_err(err);
11346 	err = check_path(path);
11347 	if (err)
11348 		return libbpf_err(err);
11349 
11350 	link->pin_path = strdup(path);
11351 	if (!link->pin_path)
11352 		return libbpf_err(-ENOMEM);
11353 
11354 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11355 		err = -errno;
11356 		zfree(&link->pin_path);
11357 		return libbpf_err(err);
11358 	}
11359 
11360 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11361 	return 0;
11362 }
11363 
11364 int bpf_link__unpin(struct bpf_link *link)
11365 {
11366 	int err;
11367 
11368 	if (!link->pin_path)
11369 		return libbpf_err(-EINVAL);
11370 
11371 	err = unlink(link->pin_path);
11372 	if (err != 0)
11373 		return -errno;
11374 
11375 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11376 	zfree(&link->pin_path);
11377 	return 0;
11378 }
11379 
11380 struct bpf_link_perf {
11381 	struct bpf_link link;
11382 	int perf_event_fd;
11383 	/* legacy kprobe support: keep track of probe identifier and type */
11384 	char *legacy_probe_name;
11385 	bool legacy_is_kprobe;
11386 	bool legacy_is_retprobe;
11387 };
11388 
11389 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11390 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11391 
11392 static int bpf_link_perf_detach(struct bpf_link *link)
11393 {
11394 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11395 	int err = 0;
11396 
11397 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11398 		err = -errno;
11399 
11400 	if (perf_link->perf_event_fd != link->fd)
11401 		close(perf_link->perf_event_fd);
11402 	close(link->fd);
11403 
11404 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11405 	if (perf_link->legacy_probe_name) {
11406 		if (perf_link->legacy_is_kprobe) {
11407 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11408 							 perf_link->legacy_is_retprobe);
11409 		} else {
11410 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11411 							 perf_link->legacy_is_retprobe);
11412 		}
11413 	}
11414 
11415 	return err;
11416 }
11417 
11418 static void bpf_link_perf_dealloc(struct bpf_link *link)
11419 {
11420 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11421 
11422 	free(perf_link->legacy_probe_name);
11423 	free(perf_link);
11424 }
11425 
11426 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11427 						     const struct bpf_perf_event_opts *opts)
11428 {
11429 	struct bpf_link_perf *link;
11430 	int prog_fd, link_fd = -1, err;
11431 	bool force_ioctl_attach;
11432 
11433 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11434 		return libbpf_err_ptr(-EINVAL);
11435 
11436 	if (pfd < 0) {
11437 		pr_warn("prog '%s': invalid perf event FD %d\n",
11438 			prog->name, pfd);
11439 		return libbpf_err_ptr(-EINVAL);
11440 	}
11441 	prog_fd = bpf_program__fd(prog);
11442 	if (prog_fd < 0) {
11443 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11444 			prog->name);
11445 		return libbpf_err_ptr(-EINVAL);
11446 	}
11447 
11448 	link = calloc(1, sizeof(*link));
11449 	if (!link)
11450 		return libbpf_err_ptr(-ENOMEM);
11451 	link->link.detach = &bpf_link_perf_detach;
11452 	link->link.dealloc = &bpf_link_perf_dealloc;
11453 	link->perf_event_fd = pfd;
11454 
11455 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11456 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11457 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11458 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11459 
11460 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11461 		if (link_fd < 0) {
11462 			err = -errno;
11463 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11464 				prog->name, pfd, errstr(err));
11465 			goto err_out;
11466 		}
11467 		link->link.fd = link_fd;
11468 	} else {
11469 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11470 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11471 			err = -EOPNOTSUPP;
11472 			goto err_out;
11473 		}
11474 
11475 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11476 			err = -errno;
11477 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11478 				prog->name, pfd, errstr(err));
11479 			if (err == -EPROTO)
11480 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11481 					prog->name, pfd);
11482 			goto err_out;
11483 		}
11484 		link->link.fd = pfd;
11485 	}
11486 
11487 	if (!OPTS_GET(opts, dont_enable, false)) {
11488 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11489 			err = -errno;
11490 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11491 				prog->name, pfd, errstr(err));
11492 			goto err_out;
11493 		}
11494 	}
11495 
11496 	return &link->link;
11497 err_out:
11498 	if (link_fd >= 0)
11499 		close(link_fd);
11500 	free(link);
11501 	return libbpf_err_ptr(err);
11502 }
11503 
11504 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11505 {
11506 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11507 }
11508 
11509 /*
11510  * this function is expected to parse integer in the range of [0, 2^31-1] from
11511  * given file using scanf format string fmt. If actual parsed value is
11512  * negative, the result might be indistinguishable from error
11513  */
11514 static int parse_uint_from_file(const char *file, const char *fmt)
11515 {
11516 	int err, ret;
11517 	FILE *f;
11518 
11519 	f = fopen(file, "re");
11520 	if (!f) {
11521 		err = -errno;
11522 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11523 		return err;
11524 	}
11525 	err = fscanf(f, fmt, &ret);
11526 	if (err != 1) {
11527 		err = err == EOF ? -EIO : -errno;
11528 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11529 		fclose(f);
11530 		return err;
11531 	}
11532 	fclose(f);
11533 	return ret;
11534 }
11535 
11536 static int determine_kprobe_perf_type(void)
11537 {
11538 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11539 
11540 	return parse_uint_from_file(file, "%d\n");
11541 }
11542 
11543 static int determine_uprobe_perf_type(void)
11544 {
11545 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11546 
11547 	return parse_uint_from_file(file, "%d\n");
11548 }
11549 
11550 static int determine_kprobe_retprobe_bit(void)
11551 {
11552 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11553 
11554 	return parse_uint_from_file(file, "config:%d\n");
11555 }
11556 
11557 static int determine_uprobe_retprobe_bit(void)
11558 {
11559 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11560 
11561 	return parse_uint_from_file(file, "config:%d\n");
11562 }
11563 
11564 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11565 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11566 
11567 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11568 				 uint64_t offset, int pid, size_t ref_ctr_off)
11569 {
11570 	const size_t attr_sz = sizeof(struct perf_event_attr);
11571 	struct perf_event_attr attr;
11572 	int type, pfd;
11573 
11574 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11575 		return -EINVAL;
11576 
11577 	memset(&attr, 0, attr_sz);
11578 
11579 	type = uprobe ? determine_uprobe_perf_type()
11580 		      : determine_kprobe_perf_type();
11581 	if (type < 0) {
11582 		pr_warn("failed to determine %s perf type: %s\n",
11583 			uprobe ? "uprobe" : "kprobe",
11584 			errstr(type));
11585 		return type;
11586 	}
11587 	if (retprobe) {
11588 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11589 				 : determine_kprobe_retprobe_bit();
11590 
11591 		if (bit < 0) {
11592 			pr_warn("failed to determine %s retprobe bit: %s\n",
11593 				uprobe ? "uprobe" : "kprobe",
11594 				errstr(bit));
11595 			return bit;
11596 		}
11597 		attr.config |= 1 << bit;
11598 	}
11599 	attr.size = attr_sz;
11600 	attr.type = type;
11601 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11602 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11603 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11604 
11605 	/* pid filter is meaningful only for uprobes */
11606 	pfd = syscall(__NR_perf_event_open, &attr,
11607 		      pid < 0 ? -1 : pid /* pid */,
11608 		      pid == -1 ? 0 : -1 /* cpu */,
11609 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11610 	return pfd >= 0 ? pfd : -errno;
11611 }
11612 
11613 static int append_to_file(const char *file, const char *fmt, ...)
11614 {
11615 	int fd, n, err = 0;
11616 	va_list ap;
11617 	char buf[1024];
11618 
11619 	va_start(ap, fmt);
11620 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11621 	va_end(ap);
11622 
11623 	if (n < 0 || n >= sizeof(buf))
11624 		return -EINVAL;
11625 
11626 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11627 	if (fd < 0)
11628 		return -errno;
11629 
11630 	if (write(fd, buf, n) < 0)
11631 		err = -errno;
11632 
11633 	close(fd);
11634 	return err;
11635 }
11636 
11637 #define DEBUGFS "/sys/kernel/debug/tracing"
11638 #define TRACEFS "/sys/kernel/tracing"
11639 
11640 static bool use_debugfs(void)
11641 {
11642 	static int has_debugfs = -1;
11643 
11644 	if (has_debugfs < 0)
11645 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11646 
11647 	return has_debugfs == 1;
11648 }
11649 
11650 static const char *tracefs_path(void)
11651 {
11652 	return use_debugfs() ? DEBUGFS : TRACEFS;
11653 }
11654 
11655 static const char *tracefs_kprobe_events(void)
11656 {
11657 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11658 }
11659 
11660 static const char *tracefs_uprobe_events(void)
11661 {
11662 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11663 }
11664 
11665 static const char *tracefs_available_filter_functions(void)
11666 {
11667 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11668 			     : TRACEFS"/available_filter_functions";
11669 }
11670 
11671 static const char *tracefs_available_filter_functions_addrs(void)
11672 {
11673 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11674 			     : TRACEFS"/available_filter_functions_addrs";
11675 }
11676 
11677 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11678 					const char *name, size_t offset)
11679 {
11680 	static int index = 0;
11681 	int i;
11682 
11683 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11684 		 __sync_fetch_and_add(&index, 1), name, offset);
11685 
11686 	/* sanitize name in the probe name */
11687 	for (i = 0; buf[i]; i++) {
11688 		if (!isalnum(buf[i]))
11689 			buf[i] = '_';
11690 	}
11691 }
11692 
11693 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11694 				   const char *kfunc_name, size_t offset)
11695 {
11696 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11697 			      retprobe ? 'r' : 'p',
11698 			      retprobe ? "kretprobes" : "kprobes",
11699 			      probe_name, kfunc_name, offset);
11700 }
11701 
11702 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11703 {
11704 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11705 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11706 }
11707 
11708 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11709 {
11710 	char file[256];
11711 
11712 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11713 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11714 
11715 	return parse_uint_from_file(file, "%d\n");
11716 }
11717 
11718 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11719 					 const char *kfunc_name, size_t offset, int pid)
11720 {
11721 	const size_t attr_sz = sizeof(struct perf_event_attr);
11722 	struct perf_event_attr attr;
11723 	int type, pfd, err;
11724 
11725 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11726 	if (err < 0) {
11727 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11728 			kfunc_name, offset,
11729 			errstr(err));
11730 		return err;
11731 	}
11732 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11733 	if (type < 0) {
11734 		err = type;
11735 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11736 			kfunc_name, offset,
11737 			errstr(err));
11738 		goto err_clean_legacy;
11739 	}
11740 
11741 	memset(&attr, 0, attr_sz);
11742 	attr.size = attr_sz;
11743 	attr.config = type;
11744 	attr.type = PERF_TYPE_TRACEPOINT;
11745 
11746 	pfd = syscall(__NR_perf_event_open, &attr,
11747 		      pid < 0 ? -1 : pid, /* pid */
11748 		      pid == -1 ? 0 : -1, /* cpu */
11749 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11750 	if (pfd < 0) {
11751 		err = -errno;
11752 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11753 			errstr(err));
11754 		goto err_clean_legacy;
11755 	}
11756 	return pfd;
11757 
11758 err_clean_legacy:
11759 	/* Clear the newly added legacy kprobe_event */
11760 	remove_kprobe_event_legacy(probe_name, retprobe);
11761 	return err;
11762 }
11763 
11764 static const char *arch_specific_syscall_pfx(void)
11765 {
11766 #if defined(__x86_64__)
11767 	return "x64";
11768 #elif defined(__i386__)
11769 	return "ia32";
11770 #elif defined(__s390x__)
11771 	return "s390x";
11772 #elif defined(__arm__)
11773 	return "arm";
11774 #elif defined(__aarch64__)
11775 	return "arm64";
11776 #elif defined(__mips__)
11777 	return "mips";
11778 #elif defined(__riscv)
11779 	return "riscv";
11780 #elif defined(__powerpc__)
11781 	return "powerpc";
11782 #elif defined(__powerpc64__)
11783 	return "powerpc64";
11784 #else
11785 	return NULL;
11786 #endif
11787 }
11788 
11789 int probe_kern_syscall_wrapper(int token_fd)
11790 {
11791 	char syscall_name[64];
11792 	const char *ksys_pfx;
11793 
11794 	ksys_pfx = arch_specific_syscall_pfx();
11795 	if (!ksys_pfx)
11796 		return 0;
11797 
11798 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11799 
11800 	if (determine_kprobe_perf_type() >= 0) {
11801 		int pfd;
11802 
11803 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11804 		if (pfd >= 0)
11805 			close(pfd);
11806 
11807 		return pfd >= 0 ? 1 : 0;
11808 	} else { /* legacy mode */
11809 		char probe_name[MAX_EVENT_NAME_LEN];
11810 
11811 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11812 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11813 			return 0;
11814 
11815 		(void)remove_kprobe_event_legacy(probe_name, false);
11816 		return 1;
11817 	}
11818 }
11819 
11820 struct bpf_link *
11821 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11822 				const char *func_name,
11823 				const struct bpf_kprobe_opts *opts)
11824 {
11825 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11826 	enum probe_attach_mode attach_mode;
11827 	char *legacy_probe = NULL;
11828 	struct bpf_link *link;
11829 	size_t offset;
11830 	bool retprobe, legacy;
11831 	int pfd, err;
11832 
11833 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11834 		return libbpf_err_ptr(-EINVAL);
11835 
11836 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11837 	retprobe = OPTS_GET(opts, retprobe, false);
11838 	offset = OPTS_GET(opts, offset, 0);
11839 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11840 
11841 	legacy = determine_kprobe_perf_type() < 0;
11842 	switch (attach_mode) {
11843 	case PROBE_ATTACH_MODE_LEGACY:
11844 		legacy = true;
11845 		pe_opts.force_ioctl_attach = true;
11846 		break;
11847 	case PROBE_ATTACH_MODE_PERF:
11848 		if (legacy)
11849 			return libbpf_err_ptr(-ENOTSUP);
11850 		pe_opts.force_ioctl_attach = true;
11851 		break;
11852 	case PROBE_ATTACH_MODE_LINK:
11853 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11854 			return libbpf_err_ptr(-ENOTSUP);
11855 		break;
11856 	case PROBE_ATTACH_MODE_DEFAULT:
11857 		break;
11858 	default:
11859 		return libbpf_err_ptr(-EINVAL);
11860 	}
11861 	if (!func_name && legacy)
11862 		return libbpf_err_ptr(-EOPNOTSUPP);
11863 
11864 	if (!legacy) {
11865 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11866 					    func_name, offset,
11867 					    -1 /* pid */, 0 /* ref_ctr_off */);
11868 	} else {
11869 		char probe_name[MAX_EVENT_NAME_LEN];
11870 
11871 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11872 					    func_name, offset);
11873 
11874 		legacy_probe = strdup(probe_name);
11875 		if (!legacy_probe)
11876 			return libbpf_err_ptr(-ENOMEM);
11877 
11878 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11879 						    offset, -1 /* pid */);
11880 	}
11881 	if (pfd < 0) {
11882 		err = pfd;
11883 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
11884 			prog->name, retprobe ? "kretprobe" : "kprobe",
11885 			func_name ?: "", func_name ? "+" : "",
11886 			offset, errstr(err));
11887 		goto err_out;
11888 	}
11889 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11890 	err = libbpf_get_error(link);
11891 	if (err) {
11892 		close(pfd);
11893 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
11894 			prog->name, retprobe ? "kretprobe" : "kprobe",
11895 			func_name ?: "", func_name ? "+" : "",
11896 			offset, errstr(err));
11897 		goto err_clean_legacy;
11898 	}
11899 	if (legacy) {
11900 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11901 
11902 		perf_link->legacy_probe_name = legacy_probe;
11903 		perf_link->legacy_is_kprobe = true;
11904 		perf_link->legacy_is_retprobe = retprobe;
11905 	}
11906 
11907 	return link;
11908 
11909 err_clean_legacy:
11910 	if (legacy)
11911 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11912 err_out:
11913 	free(legacy_probe);
11914 	return libbpf_err_ptr(err);
11915 }
11916 
11917 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11918 					    bool retprobe,
11919 					    const char *func_name)
11920 {
11921 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11922 		.retprobe = retprobe,
11923 	);
11924 
11925 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11926 }
11927 
11928 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11929 					      const char *syscall_name,
11930 					      const struct bpf_ksyscall_opts *opts)
11931 {
11932 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11933 	char func_name[128];
11934 
11935 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11936 		return libbpf_err_ptr(-EINVAL);
11937 
11938 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11939 		/* arch_specific_syscall_pfx() should never return NULL here
11940 		 * because it is guarded by kernel_supports(). However, since
11941 		 * compiler does not know that we have an explicit conditional
11942 		 * as well.
11943 		 */
11944 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11945 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11946 	} else {
11947 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11948 	}
11949 
11950 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11951 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11952 
11953 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11954 }
11955 
11956 /* Adapted from perf/util/string.c */
11957 bool glob_match(const char *str, const char *pat)
11958 {
11959 	while (*str && *pat && *pat != '*') {
11960 		if (*pat == '?') {      /* Matches any single character */
11961 			str++;
11962 			pat++;
11963 			continue;
11964 		}
11965 		if (*str != *pat)
11966 			return false;
11967 		str++;
11968 		pat++;
11969 	}
11970 	/* Check wild card */
11971 	if (*pat == '*') {
11972 		while (*pat == '*')
11973 			pat++;
11974 		if (!*pat) /* Tail wild card matches all */
11975 			return true;
11976 		while (*str)
11977 			if (glob_match(str++, pat))
11978 				return true;
11979 	}
11980 	return !*str && !*pat;
11981 }
11982 
11983 struct kprobe_multi_resolve {
11984 	const char *pattern;
11985 	unsigned long *addrs;
11986 	size_t cap;
11987 	size_t cnt;
11988 };
11989 
11990 struct avail_kallsyms_data {
11991 	char **syms;
11992 	size_t cnt;
11993 	struct kprobe_multi_resolve *res;
11994 };
11995 
11996 static int avail_func_cmp(const void *a, const void *b)
11997 {
11998 	return strcmp(*(const char **)a, *(const char **)b);
11999 }
12000 
12001 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
12002 			     const char *sym_name, void *ctx)
12003 {
12004 	struct avail_kallsyms_data *data = ctx;
12005 	struct kprobe_multi_resolve *res = data->res;
12006 	int err;
12007 
12008 	if (!glob_match(sym_name, res->pattern))
12009 		return 0;
12010 
12011 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12012 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12013 		 * function names reported in available_filter_functions, but
12014 		 * don't do so for kallsyms. While this is clearly a kernel
12015 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12016 		 * make multi-kprobe usability a bit better: if no match is
12017 		 * found, we will strip .llvm. suffix and try one more time.
12018 		 *
12019 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12020 		 */
12021 		char sym_trim[256], *psym_trim = sym_trim;
12022 		const char *sym_sfx;
12023 
12024 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12025 			return 0;
12026 
12027 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12028 		 * coercion differences and get proper `const char **` pointer
12029 		 * which avail_func_cmp() expects
12030 		 */
12031 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12032 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12033 			return 0;
12034 	}
12035 
12036 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12037 	if (err)
12038 		return err;
12039 
12040 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12041 	return 0;
12042 }
12043 
12044 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12045 {
12046 	const char *available_functions_file = tracefs_available_filter_functions();
12047 	struct avail_kallsyms_data data;
12048 	char sym_name[500];
12049 	FILE *f;
12050 	int err = 0, ret, i;
12051 	char **syms = NULL;
12052 	size_t cap = 0, cnt = 0;
12053 
12054 	f = fopen(available_functions_file, "re");
12055 	if (!f) {
12056 		err = -errno;
12057 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12058 		return err;
12059 	}
12060 
12061 	while (true) {
12062 		char *name;
12063 
12064 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12065 		if (ret == EOF && feof(f))
12066 			break;
12067 
12068 		if (ret != 1) {
12069 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12070 			err = -EINVAL;
12071 			goto cleanup;
12072 		}
12073 
12074 		if (!glob_match(sym_name, res->pattern))
12075 			continue;
12076 
12077 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12078 		if (err)
12079 			goto cleanup;
12080 
12081 		name = strdup(sym_name);
12082 		if (!name) {
12083 			err = -errno;
12084 			goto cleanup;
12085 		}
12086 
12087 		syms[cnt++] = name;
12088 	}
12089 
12090 	/* no entries found, bail out */
12091 	if (cnt == 0) {
12092 		err = -ENOENT;
12093 		goto cleanup;
12094 	}
12095 
12096 	/* sort available functions */
12097 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12098 
12099 	data.syms = syms;
12100 	data.res = res;
12101 	data.cnt = cnt;
12102 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12103 
12104 	if (res->cnt == 0)
12105 		err = -ENOENT;
12106 
12107 cleanup:
12108 	for (i = 0; i < cnt; i++)
12109 		free((char *)syms[i]);
12110 	free(syms);
12111 
12112 	fclose(f);
12113 	return err;
12114 }
12115 
12116 static bool has_available_filter_functions_addrs(void)
12117 {
12118 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12119 }
12120 
12121 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12122 {
12123 	const char *available_path = tracefs_available_filter_functions_addrs();
12124 	char sym_name[500];
12125 	FILE *f;
12126 	int ret, err = 0;
12127 	unsigned long long sym_addr;
12128 
12129 	f = fopen(available_path, "re");
12130 	if (!f) {
12131 		err = -errno;
12132 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12133 		return err;
12134 	}
12135 
12136 	while (true) {
12137 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12138 		if (ret == EOF && feof(f))
12139 			break;
12140 
12141 		if (ret != 2) {
12142 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12143 				ret);
12144 			err = -EINVAL;
12145 			goto cleanup;
12146 		}
12147 
12148 		if (!glob_match(sym_name, res->pattern))
12149 			continue;
12150 
12151 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12152 					sizeof(*res->addrs), res->cnt + 1);
12153 		if (err)
12154 			goto cleanup;
12155 
12156 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12157 	}
12158 
12159 	if (res->cnt == 0)
12160 		err = -ENOENT;
12161 
12162 cleanup:
12163 	fclose(f);
12164 	return err;
12165 }
12166 
12167 struct bpf_link *
12168 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12169 				      const char *pattern,
12170 				      const struct bpf_kprobe_multi_opts *opts)
12171 {
12172 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12173 	struct kprobe_multi_resolve res = {
12174 		.pattern = pattern,
12175 	};
12176 	enum bpf_attach_type attach_type;
12177 	struct bpf_link *link = NULL;
12178 	const unsigned long *addrs;
12179 	int err, link_fd, prog_fd;
12180 	bool retprobe, session, unique_match;
12181 	const __u64 *cookies;
12182 	const char **syms;
12183 	size_t cnt;
12184 
12185 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12186 		return libbpf_err_ptr(-EINVAL);
12187 
12188 	prog_fd = bpf_program__fd(prog);
12189 	if (prog_fd < 0) {
12190 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12191 			prog->name);
12192 		return libbpf_err_ptr(-EINVAL);
12193 	}
12194 
12195 	syms    = OPTS_GET(opts, syms, false);
12196 	addrs   = OPTS_GET(opts, addrs, false);
12197 	cnt     = OPTS_GET(opts, cnt, false);
12198 	cookies = OPTS_GET(opts, cookies, false);
12199 	unique_match = OPTS_GET(opts, unique_match, false);
12200 
12201 	if (!pattern && !addrs && !syms)
12202 		return libbpf_err_ptr(-EINVAL);
12203 	if (pattern && (addrs || syms || cookies || cnt))
12204 		return libbpf_err_ptr(-EINVAL);
12205 	if (!pattern && !cnt)
12206 		return libbpf_err_ptr(-EINVAL);
12207 	if (!pattern && unique_match)
12208 		return libbpf_err_ptr(-EINVAL);
12209 	if (addrs && syms)
12210 		return libbpf_err_ptr(-EINVAL);
12211 
12212 	/*
12213 	 * Exact function name (no wildcards) without unique_match:
12214 	 * bypass kallsyms parsing and pass the symbol directly to the
12215 	 * kernel via syms[] array.  When unique_match is set, fall
12216 	 * through to the slow path which detects duplicate symbols.
12217 	 */
12218 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12219 		syms = &pattern;
12220 		cnt = 1;
12221 	} else if (pattern) {
12222 		if (has_available_filter_functions_addrs())
12223 			err = libbpf_available_kprobes_parse(&res);
12224 		else
12225 			err = libbpf_available_kallsyms_parse(&res);
12226 		if (err)
12227 			goto error;
12228 
12229 		if (unique_match && res.cnt != 1) {
12230 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12231 				prog->name, pattern, res.cnt);
12232 			err = -EINVAL;
12233 			goto error;
12234 		}
12235 
12236 		addrs = res.addrs;
12237 		cnt = res.cnt;
12238 	}
12239 
12240 	retprobe = OPTS_GET(opts, retprobe, false);
12241 	session  = OPTS_GET(opts, session, false);
12242 
12243 	if (retprobe && session)
12244 		return libbpf_err_ptr(-EINVAL);
12245 
12246 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12247 
12248 	lopts.kprobe_multi.syms = syms;
12249 	lopts.kprobe_multi.addrs = addrs;
12250 	lopts.kprobe_multi.cookies = cookies;
12251 	lopts.kprobe_multi.cnt = cnt;
12252 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12253 
12254 	link = calloc(1, sizeof(*link));
12255 	if (!link) {
12256 		err = -ENOMEM;
12257 		goto error;
12258 	}
12259 	link->detach = &bpf_link__detach_fd;
12260 
12261 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12262 	if (link_fd < 0) {
12263 		err = -errno;
12264 		/*
12265 		 * Normalize error code: when exact name bypasses kallsyms
12266 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
12267 		 * Convert to ENOENT for API consistency with the pattern
12268 		 * matching path which returns ENOENT from userspace.
12269 		 */
12270 		if (err == -ESRCH)
12271 			err = -ENOENT;
12272 		pr_warn("prog '%s': failed to attach: %s\n",
12273 			prog->name, errstr(err));
12274 		goto error;
12275 	}
12276 	link->fd = link_fd;
12277 	free(res.addrs);
12278 	return link;
12279 
12280 error:
12281 	free(link);
12282 	free(res.addrs);
12283 	return libbpf_err_ptr(err);
12284 }
12285 
12286 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12287 {
12288 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12289 	long offset = 0;
12290 	const char *func_name;
12291 	char *func;
12292 	int n;
12293 
12294 	*link = NULL;
12295 
12296 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12297 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12298 		return 0;
12299 
12300 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12301 	if (opts.retprobe)
12302 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12303 	else
12304 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12305 
12306 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12307 	if (n < 1) {
12308 		pr_warn("kprobe name is invalid: %s\n", func_name);
12309 		return -EINVAL;
12310 	}
12311 
12312 	if (offset < 0) {
12313 		free(func);
12314 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
12315 		return -EINVAL;
12316 	}
12317 
12318 	if (opts.retprobe && offset != 0) {
12319 		free(func);
12320 		pr_warn("kretprobes do not support offset specification\n");
12321 		return -EINVAL;
12322 	}
12323 
12324 	opts.offset = offset;
12325 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12326 	free(func);
12327 	return libbpf_get_error(*link);
12328 }
12329 
12330 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12331 {
12332 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12333 	const char *syscall_name;
12334 
12335 	*link = NULL;
12336 
12337 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12338 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12339 		return 0;
12340 
12341 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12342 	if (opts.retprobe)
12343 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12344 	else
12345 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12346 
12347 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12348 	return *link ? 0 : -errno;
12349 }
12350 
12351 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12352 {
12353 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12354 	const char *spec;
12355 	char *pattern;
12356 	int n;
12357 
12358 	*link = NULL;
12359 
12360 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12361 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12362 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12363 		return 0;
12364 
12365 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12366 	if (opts.retprobe)
12367 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12368 	else
12369 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12370 
12371 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12372 	if (n < 1) {
12373 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12374 		return -EINVAL;
12375 	}
12376 
12377 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12378 	free(pattern);
12379 	return libbpf_get_error(*link);
12380 }
12381 
12382 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12383 				 struct bpf_link **link)
12384 {
12385 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12386 	const char *spec;
12387 	char *pattern;
12388 	int n;
12389 
12390 	*link = NULL;
12391 
12392 	/* no auto-attach for SEC("kprobe.session") */
12393 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12394 		return 0;
12395 
12396 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12397 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12398 	if (n < 1) {
12399 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12400 		return -EINVAL;
12401 	}
12402 
12403 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12404 	free(pattern);
12405 	return *link ? 0 : -errno;
12406 }
12407 
12408 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12409 {
12410 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12411 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12412 	int n, ret = -EINVAL;
12413 
12414 	*link = NULL;
12415 
12416 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12417 		   &probe_type, &binary_path, &func_name);
12418 	switch (n) {
12419 	case 1:
12420 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12421 		ret = 0;
12422 		break;
12423 	case 3:
12424 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12425 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12426 
12427 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12428 		ret = libbpf_get_error(*link);
12429 		break;
12430 	default:
12431 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12432 			prog->sec_name);
12433 		break;
12434 	}
12435 	free(probe_type);
12436 	free(binary_path);
12437 	free(func_name);
12438 	return ret;
12439 }
12440 
12441 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12442 					  const char *binary_path, size_t offset)
12443 {
12444 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12445 			      retprobe ? 'r' : 'p',
12446 			      retprobe ? "uretprobes" : "uprobes",
12447 			      probe_name, binary_path, offset);
12448 }
12449 
12450 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12451 {
12452 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12453 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12454 }
12455 
12456 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12457 {
12458 	char file[512];
12459 
12460 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12461 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12462 
12463 	return parse_uint_from_file(file, "%d\n");
12464 }
12465 
12466 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12467 					 const char *binary_path, size_t offset, int pid)
12468 {
12469 	const size_t attr_sz = sizeof(struct perf_event_attr);
12470 	struct perf_event_attr attr;
12471 	int type, pfd, err;
12472 
12473 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12474 	if (err < 0) {
12475 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12476 			binary_path, (size_t)offset, errstr(err));
12477 		return err;
12478 	}
12479 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12480 	if (type < 0) {
12481 		err = type;
12482 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12483 			binary_path, offset, errstr(err));
12484 		goto err_clean_legacy;
12485 	}
12486 
12487 	memset(&attr, 0, attr_sz);
12488 	attr.size = attr_sz;
12489 	attr.config = type;
12490 	attr.type = PERF_TYPE_TRACEPOINT;
12491 
12492 	pfd = syscall(__NR_perf_event_open, &attr,
12493 		      pid < 0 ? -1 : pid, /* pid */
12494 		      pid == -1 ? 0 : -1, /* cpu */
12495 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12496 	if (pfd < 0) {
12497 		err = -errno;
12498 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12499 		goto err_clean_legacy;
12500 	}
12501 	return pfd;
12502 
12503 err_clean_legacy:
12504 	/* Clear the newly added legacy uprobe_event */
12505 	remove_uprobe_event_legacy(probe_name, retprobe);
12506 	return err;
12507 }
12508 
12509 /* Find offset of function name in archive specified by path. Currently
12510  * supported are .zip files that do not compress their contents, as used on
12511  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12512  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12513  * library functions.
12514  *
12515  * An overview of the APK format specifically provided here:
12516  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12517  */
12518 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12519 					      const char *func_name)
12520 {
12521 	struct zip_archive *archive;
12522 	struct zip_entry entry;
12523 	long ret;
12524 	Elf *elf;
12525 
12526 	archive = zip_archive_open(archive_path);
12527 	if (IS_ERR(archive)) {
12528 		ret = PTR_ERR(archive);
12529 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12530 		return ret;
12531 	}
12532 
12533 	ret = zip_archive_find_entry(archive, file_name, &entry);
12534 	if (ret) {
12535 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12536 			archive_path, ret);
12537 		goto out;
12538 	}
12539 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12540 		 (unsigned long)entry.data_offset);
12541 
12542 	if (entry.compression) {
12543 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12544 			archive_path);
12545 		ret = -LIBBPF_ERRNO__FORMAT;
12546 		goto out;
12547 	}
12548 
12549 	elf = elf_memory((void *)entry.data, entry.data_length);
12550 	if (!elf) {
12551 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12552 			elf_errmsg(-1));
12553 		ret = -LIBBPF_ERRNO__LIBELF;
12554 		goto out;
12555 	}
12556 
12557 	ret = elf_find_func_offset(elf, file_name, func_name);
12558 	if (ret > 0) {
12559 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12560 			 func_name, file_name, archive_path, entry.data_offset, ret,
12561 			 ret + entry.data_offset);
12562 		ret += entry.data_offset;
12563 	}
12564 	elf_end(elf);
12565 
12566 out:
12567 	zip_archive_close(archive);
12568 	return ret;
12569 }
12570 
12571 static const char *arch_specific_lib_paths(void)
12572 {
12573 	/*
12574 	 * Based on https://packages.debian.org/sid/libc6.
12575 	 *
12576 	 * Assume that the traced program is built for the same architecture
12577 	 * as libbpf, which should cover the vast majority of cases.
12578 	 */
12579 #if defined(__x86_64__)
12580 	return "/lib/x86_64-linux-gnu";
12581 #elif defined(__i386__)
12582 	return "/lib/i386-linux-gnu";
12583 #elif defined(__s390x__)
12584 	return "/lib/s390x-linux-gnu";
12585 #elif defined(__arm__) && defined(__SOFTFP__)
12586 	return "/lib/arm-linux-gnueabi";
12587 #elif defined(__arm__) && !defined(__SOFTFP__)
12588 	return "/lib/arm-linux-gnueabihf";
12589 #elif defined(__aarch64__)
12590 	return "/lib/aarch64-linux-gnu";
12591 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12592 	return "/lib/mips64el-linux-gnuabi64";
12593 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12594 	return "/lib/mipsel-linux-gnu";
12595 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12596 	return "/lib/powerpc64le-linux-gnu";
12597 #elif defined(__sparc__) && defined(__arch64__)
12598 	return "/lib/sparc64-linux-gnu";
12599 #elif defined(__riscv) && __riscv_xlen == 64
12600 	return "/lib/riscv64-linux-gnu";
12601 #else
12602 	return NULL;
12603 #endif
12604 }
12605 
12606 /* Get full path to program/shared library. */
12607 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12608 {
12609 	const char *search_paths[3] = {};
12610 	int i, perm;
12611 
12612 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12613 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12614 		search_paths[1] = "/usr/lib64:/usr/lib";
12615 		search_paths[2] = arch_specific_lib_paths();
12616 		perm = R_OK;
12617 	} else {
12618 		search_paths[0] = getenv("PATH");
12619 		search_paths[1] = "/usr/bin:/usr/sbin";
12620 		perm = R_OK | X_OK;
12621 	}
12622 
12623 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12624 		const char *s;
12625 
12626 		if (!search_paths[i])
12627 			continue;
12628 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12629 			const char *next_path;
12630 			int seg_len;
12631 
12632 			if (s[0] == ':')
12633 				s++;
12634 			next_path = strchr(s, ':');
12635 			seg_len = next_path ? next_path - s : strlen(s);
12636 			if (!seg_len)
12637 				continue;
12638 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12639 			/* ensure it has required permissions */
12640 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12641 				continue;
12642 			pr_debug("resolved '%s' to '%s'\n", file, result);
12643 			return 0;
12644 		}
12645 	}
12646 	return -ENOENT;
12647 }
12648 
12649 struct bpf_link *
12650 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12651 				 pid_t pid,
12652 				 const char *path,
12653 				 const char *func_pattern,
12654 				 const struct bpf_uprobe_multi_opts *opts)
12655 {
12656 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12657 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12658 	unsigned long *resolved_offsets = NULL;
12659 	enum bpf_attach_type attach_type;
12660 	int err = 0, link_fd, prog_fd;
12661 	struct bpf_link *link = NULL;
12662 	char full_path[PATH_MAX];
12663 	bool retprobe, session;
12664 	const __u64 *cookies;
12665 	const char **syms;
12666 	size_t cnt;
12667 
12668 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12669 		return libbpf_err_ptr(-EINVAL);
12670 
12671 	prog_fd = bpf_program__fd(prog);
12672 	if (prog_fd < 0) {
12673 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12674 			prog->name);
12675 		return libbpf_err_ptr(-EINVAL);
12676 	}
12677 
12678 	syms = OPTS_GET(opts, syms, NULL);
12679 	offsets = OPTS_GET(opts, offsets, NULL);
12680 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12681 	cookies = OPTS_GET(opts, cookies, NULL);
12682 	cnt = OPTS_GET(opts, cnt, 0);
12683 	retprobe = OPTS_GET(opts, retprobe, false);
12684 	session  = OPTS_GET(opts, session, false);
12685 
12686 	/*
12687 	 * User can specify 2 mutually exclusive set of inputs:
12688 	 *
12689 	 * 1) use only path/func_pattern/pid arguments
12690 	 *
12691 	 * 2) use path/pid with allowed combinations of:
12692 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12693 	 *
12694 	 *    - syms and offsets are mutually exclusive
12695 	 *    - ref_ctr_offsets and cookies are optional
12696 	 *
12697 	 * Any other usage results in error.
12698 	 */
12699 
12700 	if (!path)
12701 		return libbpf_err_ptr(-EINVAL);
12702 	if (!func_pattern && cnt == 0)
12703 		return libbpf_err_ptr(-EINVAL);
12704 
12705 	if (func_pattern) {
12706 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12707 			return libbpf_err_ptr(-EINVAL);
12708 	} else {
12709 		if (!!syms == !!offsets)
12710 			return libbpf_err_ptr(-EINVAL);
12711 	}
12712 
12713 	if (retprobe && session)
12714 		return libbpf_err_ptr(-EINVAL);
12715 
12716 	if (func_pattern) {
12717 		if (!strchr(path, '/')) {
12718 			err = resolve_full_path(path, full_path, sizeof(full_path));
12719 			if (err) {
12720 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12721 					prog->name, path, errstr(err));
12722 				return libbpf_err_ptr(err);
12723 			}
12724 			path = full_path;
12725 		}
12726 
12727 		err = elf_resolve_pattern_offsets(path, func_pattern,
12728 						  &resolved_offsets, &cnt);
12729 		if (err < 0)
12730 			return libbpf_err_ptr(err);
12731 		offsets = resolved_offsets;
12732 	} else if (syms) {
12733 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12734 		if (err < 0)
12735 			return libbpf_err_ptr(err);
12736 		offsets = resolved_offsets;
12737 	}
12738 
12739 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12740 
12741 	lopts.uprobe_multi.path = path;
12742 	lopts.uprobe_multi.offsets = offsets;
12743 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12744 	lopts.uprobe_multi.cookies = cookies;
12745 	lopts.uprobe_multi.cnt = cnt;
12746 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12747 
12748 	if (pid == 0)
12749 		pid = getpid();
12750 	if (pid > 0)
12751 		lopts.uprobe_multi.pid = pid;
12752 
12753 	link = calloc(1, sizeof(*link));
12754 	if (!link) {
12755 		err = -ENOMEM;
12756 		goto error;
12757 	}
12758 	link->detach = &bpf_link__detach_fd;
12759 
12760 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12761 	if (link_fd < 0) {
12762 		err = -errno;
12763 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12764 			prog->name, errstr(err));
12765 		goto error;
12766 	}
12767 	link->fd = link_fd;
12768 	free(resolved_offsets);
12769 	return link;
12770 
12771 error:
12772 	free(resolved_offsets);
12773 	free(link);
12774 	return libbpf_err_ptr(err);
12775 }
12776 
12777 LIBBPF_API struct bpf_link *
12778 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12779 				const char *binary_path, size_t func_offset,
12780 				const struct bpf_uprobe_opts *opts)
12781 {
12782 	const char *archive_path = NULL, *archive_sep = NULL;
12783 	char *legacy_probe = NULL;
12784 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12785 	enum probe_attach_mode attach_mode;
12786 	char full_path[PATH_MAX];
12787 	struct bpf_link *link;
12788 	size_t ref_ctr_off;
12789 	int pfd, err;
12790 	bool retprobe, legacy;
12791 	const char *func_name;
12792 
12793 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12794 		return libbpf_err_ptr(-EINVAL);
12795 
12796 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12797 	retprobe = OPTS_GET(opts, retprobe, false);
12798 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12799 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12800 
12801 	if (!binary_path)
12802 		return libbpf_err_ptr(-EINVAL);
12803 
12804 	/* Check if "binary_path" refers to an archive. */
12805 	archive_sep = strstr(binary_path, "!/");
12806 	if (archive_sep) {
12807 		full_path[0] = '\0';
12808 		libbpf_strlcpy(full_path, binary_path,
12809 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12810 		archive_path = full_path;
12811 		binary_path = archive_sep + 2;
12812 	} else if (!strchr(binary_path, '/')) {
12813 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12814 		if (err) {
12815 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12816 				prog->name, binary_path, errstr(err));
12817 			return libbpf_err_ptr(err);
12818 		}
12819 		binary_path = full_path;
12820 	}
12821 	func_name = OPTS_GET(opts, func_name, NULL);
12822 	if (func_name) {
12823 		long sym_off;
12824 
12825 		if (archive_path) {
12826 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12827 								    func_name);
12828 			binary_path = archive_path;
12829 		} else {
12830 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12831 		}
12832 		if (sym_off < 0)
12833 			return libbpf_err_ptr(sym_off);
12834 		func_offset += sym_off;
12835 	}
12836 
12837 	legacy = determine_uprobe_perf_type() < 0;
12838 	switch (attach_mode) {
12839 	case PROBE_ATTACH_MODE_LEGACY:
12840 		legacy = true;
12841 		pe_opts.force_ioctl_attach = true;
12842 		break;
12843 	case PROBE_ATTACH_MODE_PERF:
12844 		if (legacy)
12845 			return libbpf_err_ptr(-ENOTSUP);
12846 		pe_opts.force_ioctl_attach = true;
12847 		break;
12848 	case PROBE_ATTACH_MODE_LINK:
12849 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12850 			return libbpf_err_ptr(-ENOTSUP);
12851 		break;
12852 	case PROBE_ATTACH_MODE_DEFAULT:
12853 		break;
12854 	default:
12855 		return libbpf_err_ptr(-EINVAL);
12856 	}
12857 
12858 	if (!legacy) {
12859 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12860 					    func_offset, pid, ref_ctr_off);
12861 	} else {
12862 		char probe_name[MAX_EVENT_NAME_LEN];
12863 
12864 		if (ref_ctr_off)
12865 			return libbpf_err_ptr(-EINVAL);
12866 
12867 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12868 					    strrchr(binary_path, '/') ? : binary_path,
12869 					    func_offset);
12870 
12871 		legacy_probe = strdup(probe_name);
12872 		if (!legacy_probe)
12873 			return libbpf_err_ptr(-ENOMEM);
12874 
12875 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12876 						    binary_path, func_offset, pid);
12877 	}
12878 	if (pfd < 0) {
12879 		err = pfd;
12880 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12881 			prog->name, retprobe ? "uretprobe" : "uprobe",
12882 			binary_path, func_offset,
12883 			errstr(err));
12884 		goto err_out;
12885 	}
12886 
12887 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12888 	err = libbpf_get_error(link);
12889 	if (err) {
12890 		close(pfd);
12891 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12892 			prog->name, retprobe ? "uretprobe" : "uprobe",
12893 			binary_path, func_offset,
12894 			errstr(err));
12895 		goto err_clean_legacy;
12896 	}
12897 	if (legacy) {
12898 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12899 
12900 		perf_link->legacy_probe_name = legacy_probe;
12901 		perf_link->legacy_is_kprobe = false;
12902 		perf_link->legacy_is_retprobe = retprobe;
12903 	}
12904 	return link;
12905 
12906 err_clean_legacy:
12907 	if (legacy)
12908 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12909 err_out:
12910 	free(legacy_probe);
12911 	return libbpf_err_ptr(err);
12912 }
12913 
12914 /* Format of u[ret]probe section definition supporting auto-attach:
12915  * u[ret]probe/binary:function[+offset]
12916  *
12917  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12918  * full binary path via bpf_program__attach_uprobe_opts.
12919  *
12920  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12921  * specified (and auto-attach is not possible) or the above format is specified for
12922  * auto-attach.
12923  */
12924 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12925 {
12926 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12927 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12928 	int n, c, ret = -EINVAL;
12929 	long offset = 0;
12930 
12931 	*link = NULL;
12932 
12933 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12934 		   &probe_type, &binary_path, &func_name);
12935 	switch (n) {
12936 	case 1:
12937 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12938 		ret = 0;
12939 		break;
12940 	case 2:
12941 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12942 			prog->name, prog->sec_name);
12943 		break;
12944 	case 3:
12945 		/* check if user specifies `+offset`, if yes, this should be
12946 		 * the last part of the string, make sure sscanf read to EOL
12947 		 */
12948 		func_off = strrchr(func_name, '+');
12949 		if (func_off) {
12950 			n = sscanf(func_off, "+%li%n", &offset, &c);
12951 			if (n == 1 && *(func_off + c) == '\0')
12952 				func_off[0] = '\0';
12953 			else
12954 				offset = 0;
12955 		}
12956 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12957 				strcmp(probe_type, "uretprobe.s") == 0;
12958 		if (opts.retprobe && offset != 0) {
12959 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12960 				prog->name);
12961 			break;
12962 		}
12963 		opts.func_name = func_name;
12964 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12965 		ret = libbpf_get_error(*link);
12966 		break;
12967 	default:
12968 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12969 			prog->sec_name);
12970 		break;
12971 	}
12972 	free(probe_type);
12973 	free(binary_path);
12974 	free(func_name);
12975 
12976 	return ret;
12977 }
12978 
12979 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12980 					    bool retprobe, pid_t pid,
12981 					    const char *binary_path,
12982 					    size_t func_offset)
12983 {
12984 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12985 
12986 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12987 }
12988 
12989 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12990 					  pid_t pid, const char *binary_path,
12991 					  const char *usdt_provider, const char *usdt_name,
12992 					  const struct bpf_usdt_opts *opts)
12993 {
12994 	char resolved_path[512];
12995 	struct bpf_object *obj = prog->obj;
12996 	struct bpf_link *link;
12997 	__u64 usdt_cookie;
12998 	int err;
12999 
13000 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13001 		return libbpf_err_ptr(-EINVAL);
13002 
13003 	if (bpf_program__fd(prog) < 0) {
13004 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13005 			prog->name);
13006 		return libbpf_err_ptr(-EINVAL);
13007 	}
13008 
13009 	if (!binary_path)
13010 		return libbpf_err_ptr(-EINVAL);
13011 
13012 	if (!strchr(binary_path, '/')) {
13013 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
13014 		if (err) {
13015 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13016 				prog->name, binary_path, errstr(err));
13017 			return libbpf_err_ptr(err);
13018 		}
13019 		binary_path = resolved_path;
13020 	}
13021 
13022 	/* USDT manager is instantiated lazily on first USDT attach. It will
13023 	 * be destroyed together with BPF object in bpf_object__close().
13024 	 */
13025 	if (IS_ERR(obj->usdt_man))
13026 		return libbpf_ptr(obj->usdt_man);
13027 	if (!obj->usdt_man) {
13028 		obj->usdt_man = usdt_manager_new(obj);
13029 		if (IS_ERR(obj->usdt_man))
13030 			return libbpf_ptr(obj->usdt_man);
13031 	}
13032 
13033 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
13034 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
13035 					usdt_provider, usdt_name, usdt_cookie);
13036 	err = libbpf_get_error(link);
13037 	if (err)
13038 		return libbpf_err_ptr(err);
13039 	return link;
13040 }
13041 
13042 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13043 {
13044 	char *path = NULL, *provider = NULL, *name = NULL;
13045 	const char *sec_name;
13046 	int n, err;
13047 
13048 	sec_name = bpf_program__section_name(prog);
13049 	if (strcmp(sec_name, "usdt") == 0) {
13050 		/* no auto-attach for just SEC("usdt") */
13051 		*link = NULL;
13052 		return 0;
13053 	}
13054 
13055 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
13056 	if (n != 3) {
13057 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
13058 			sec_name);
13059 		err = -EINVAL;
13060 	} else {
13061 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
13062 						 provider, name, NULL);
13063 		err = libbpf_get_error(*link);
13064 	}
13065 	free(path);
13066 	free(provider);
13067 	free(name);
13068 	return err;
13069 }
13070 
13071 static int determine_tracepoint_id(const char *tp_category,
13072 				   const char *tp_name)
13073 {
13074 	char file[PATH_MAX];
13075 	int ret;
13076 
13077 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13078 		       tracefs_path(), tp_category, tp_name);
13079 	if (ret < 0)
13080 		return -errno;
13081 	if (ret >= sizeof(file)) {
13082 		pr_debug("tracepoint %s/%s path is too long\n",
13083 			 tp_category, tp_name);
13084 		return -E2BIG;
13085 	}
13086 	return parse_uint_from_file(file, "%d\n");
13087 }
13088 
13089 static int perf_event_open_tracepoint(const char *tp_category,
13090 				      const char *tp_name)
13091 {
13092 	const size_t attr_sz = sizeof(struct perf_event_attr);
13093 	struct perf_event_attr attr;
13094 	int tp_id, pfd, err;
13095 
13096 	tp_id = determine_tracepoint_id(tp_category, tp_name);
13097 	if (tp_id < 0) {
13098 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
13099 			tp_category, tp_name,
13100 			errstr(tp_id));
13101 		return tp_id;
13102 	}
13103 
13104 	memset(&attr, 0, attr_sz);
13105 	attr.type = PERF_TYPE_TRACEPOINT;
13106 	attr.size = attr_sz;
13107 	attr.config = tp_id;
13108 
13109 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
13110 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
13111 	if (pfd < 0) {
13112 		err = -errno;
13113 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
13114 			tp_category, tp_name,
13115 			errstr(err));
13116 		return err;
13117 	}
13118 	return pfd;
13119 }
13120 
13121 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
13122 						     const char *tp_category,
13123 						     const char *tp_name,
13124 						     const struct bpf_tracepoint_opts *opts)
13125 {
13126 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13127 	struct bpf_link *link;
13128 	int pfd, err;
13129 
13130 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
13131 		return libbpf_err_ptr(-EINVAL);
13132 
13133 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13134 
13135 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
13136 	if (pfd < 0) {
13137 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
13138 			prog->name, tp_category, tp_name,
13139 			errstr(pfd));
13140 		return libbpf_err_ptr(pfd);
13141 	}
13142 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13143 	err = libbpf_get_error(link);
13144 	if (err) {
13145 		close(pfd);
13146 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
13147 			prog->name, tp_category, tp_name,
13148 			errstr(err));
13149 		return libbpf_err_ptr(err);
13150 	}
13151 	return link;
13152 }
13153 
13154 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
13155 						const char *tp_category,
13156 						const char *tp_name)
13157 {
13158 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
13159 }
13160 
13161 /*
13162  * Match section name against a prefix array. Returns pointer past
13163  * "prefix/" on match, empty string for bare sections (exact prefix
13164  * match), or NULL if no prefix matches.
13165  */
13166 static const char *sec_name_match_prefix(const char *sec_name,
13167 					 const char *const *prefixes,
13168 					 size_t n)
13169 {
13170 	size_t i;
13171 
13172 	for (i = 0; i < n; i++) {
13173 		size_t pfx_len;
13174 
13175 		if (!str_has_pfx(sec_name, prefixes[i]))
13176 			continue;
13177 
13178 		pfx_len = strlen(prefixes[i]);
13179 		if (sec_name[pfx_len] == '\0')
13180 			return sec_name + pfx_len;
13181 
13182 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
13183 			continue;
13184 
13185 		return sec_name + pfx_len + 1;
13186 	}
13187 	return NULL;
13188 }
13189 
13190 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13191 {
13192 	static const char *const prefixes[] = {
13193 		"tp.s",
13194 		"tp",
13195 		"tracepoint.s",
13196 		"tracepoint",
13197 	};
13198 	char *sec_name, *tp_cat, *tp_name;
13199 	const char *match;
13200 
13201 	*link = NULL;
13202 
13203 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13204 	if (!match) {
13205 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13206 		return -EINVAL;
13207 	}
13208 	if (!match[0]) /* bare section name no autoattach */
13209 		return 0;
13210 
13211 	sec_name = strdup(prog->sec_name);
13212 	if (!sec_name)
13213 		return -ENOMEM;
13214 
13215 	tp_cat = sec_name + (match - prog->sec_name);
13216 	tp_name = strchr(tp_cat, '/');
13217 	if (!tp_name) {
13218 		free(sec_name);
13219 		return -EINVAL;
13220 	}
13221 	*tp_name = '\0';
13222 	tp_name++;
13223 
13224 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
13225 	free(sec_name);
13226 	return libbpf_get_error(*link);
13227 }
13228 
13229 struct bpf_link *
13230 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
13231 					const char *tp_name,
13232 					struct bpf_raw_tracepoint_opts *opts)
13233 {
13234 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
13235 	struct bpf_link *link;
13236 	int prog_fd, pfd;
13237 
13238 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
13239 		return libbpf_err_ptr(-EINVAL);
13240 
13241 	prog_fd = bpf_program__fd(prog);
13242 	if (prog_fd < 0) {
13243 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13244 		return libbpf_err_ptr(-EINVAL);
13245 	}
13246 
13247 	link = calloc(1, sizeof(*link));
13248 	if (!link)
13249 		return libbpf_err_ptr(-ENOMEM);
13250 	link->detach = &bpf_link__detach_fd;
13251 
13252 	raw_opts.tp_name = tp_name;
13253 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13254 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13255 	if (pfd < 0) {
13256 		pfd = -errno;
13257 		free(link);
13258 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13259 			prog->name, tp_name, errstr(pfd));
13260 		return libbpf_err_ptr(pfd);
13261 	}
13262 	link->fd = pfd;
13263 	return link;
13264 }
13265 
13266 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13267 						    const char *tp_name)
13268 {
13269 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13270 }
13271 
13272 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13273 {
13274 	static const char *const prefixes[] = {
13275 		"raw_tp",
13276 		"raw_tracepoint",
13277 		"raw_tp.w",
13278 		"raw_tracepoint.w",
13279 		"raw_tp.s",
13280 		"raw_tracepoint.s",
13281 	};
13282 	const char *match;
13283 
13284 	*link = NULL;
13285 
13286 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13287 	if (!match) {
13288 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13289 		return -EINVAL;
13290 	}
13291 	if (!match[0])
13292 		return 0;
13293 
13294 	*link = bpf_program__attach_raw_tracepoint(prog, match);
13295 	return libbpf_get_error(*link);
13296 }
13297 
13298 /* Common logic for all BPF program types that attach to a btf_id */
13299 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13300 						   const struct bpf_trace_opts *opts)
13301 {
13302 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13303 	struct bpf_link *link;
13304 	int prog_fd, pfd;
13305 
13306 	if (!OPTS_VALID(opts, bpf_trace_opts))
13307 		return libbpf_err_ptr(-EINVAL);
13308 
13309 	prog_fd = bpf_program__fd(prog);
13310 	if (prog_fd < 0) {
13311 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13312 		return libbpf_err_ptr(-EINVAL);
13313 	}
13314 
13315 	link = calloc(1, sizeof(*link));
13316 	if (!link)
13317 		return libbpf_err_ptr(-ENOMEM);
13318 	link->detach = &bpf_link__detach_fd;
13319 
13320 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13321 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13322 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13323 	if (pfd < 0) {
13324 		pfd = -errno;
13325 		free(link);
13326 		pr_warn("prog '%s': failed to attach: %s\n",
13327 			prog->name, errstr(pfd));
13328 		return libbpf_err_ptr(pfd);
13329 	}
13330 	link->fd = pfd;
13331 	return link;
13332 }
13333 
13334 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13335 {
13336 	return bpf_program__attach_btf_id(prog, NULL);
13337 }
13338 
13339 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13340 						const struct bpf_trace_opts *opts)
13341 {
13342 	return bpf_program__attach_btf_id(prog, opts);
13343 }
13344 
13345 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13346 {
13347 	return bpf_program__attach_btf_id(prog, NULL);
13348 }
13349 
13350 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13351 {
13352 	*link = bpf_program__attach_trace(prog);
13353 	return libbpf_get_error(*link);
13354 }
13355 
13356 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13357 {
13358 	*link = bpf_program__attach_lsm(prog);
13359 	return libbpf_get_error(*link);
13360 }
13361 
13362 static struct bpf_link *
13363 bpf_program_attach_fd(const struct bpf_program *prog,
13364 		      int target_fd, const char *target_name,
13365 		      const struct bpf_link_create_opts *opts)
13366 {
13367 	enum bpf_attach_type attach_type;
13368 	struct bpf_link *link;
13369 	int prog_fd, link_fd;
13370 
13371 	prog_fd = bpf_program__fd(prog);
13372 	if (prog_fd < 0) {
13373 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13374 		return libbpf_err_ptr(-EINVAL);
13375 	}
13376 
13377 	link = calloc(1, sizeof(*link));
13378 	if (!link)
13379 		return libbpf_err_ptr(-ENOMEM);
13380 	link->detach = &bpf_link__detach_fd;
13381 
13382 	attach_type = bpf_program__expected_attach_type(prog);
13383 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13384 	if (link_fd < 0) {
13385 		link_fd = -errno;
13386 		free(link);
13387 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13388 			prog->name, target_name,
13389 			errstr(link_fd));
13390 		return libbpf_err_ptr(link_fd);
13391 	}
13392 	link->fd = link_fd;
13393 	return link;
13394 }
13395 
13396 struct bpf_link *
13397 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13398 {
13399 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13400 }
13401 
13402 struct bpf_link *
13403 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13404 {
13405 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13406 }
13407 
13408 struct bpf_link *
13409 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13410 {
13411 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13412 }
13413 
13414 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13415 {
13416 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13417 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13418 }
13419 
13420 struct bpf_link *
13421 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13422 				const struct bpf_cgroup_opts *opts)
13423 {
13424 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13425 	__u32 relative_id;
13426 	int relative_fd;
13427 
13428 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13429 		return libbpf_err_ptr(-EINVAL);
13430 
13431 	relative_id = OPTS_GET(opts, relative_id, 0);
13432 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13433 
13434 	if (relative_fd && relative_id) {
13435 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13436 			prog->name);
13437 		return libbpf_err_ptr(-EINVAL);
13438 	}
13439 
13440 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13441 	link_create_opts.cgroup.relative_fd = relative_fd;
13442 	link_create_opts.cgroup.relative_id = relative_id;
13443 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13444 
13445 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13446 }
13447 
13448 struct bpf_link *
13449 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13450 			const struct bpf_tcx_opts *opts)
13451 {
13452 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13453 	__u32 relative_id;
13454 	int relative_fd;
13455 
13456 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13457 		return libbpf_err_ptr(-EINVAL);
13458 
13459 	relative_id = OPTS_GET(opts, relative_id, 0);
13460 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13461 
13462 	/* validate we don't have unexpected combinations of non-zero fields */
13463 	if (!ifindex) {
13464 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13465 			prog->name);
13466 		return libbpf_err_ptr(-EINVAL);
13467 	}
13468 	if (relative_fd && relative_id) {
13469 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13470 			prog->name);
13471 		return libbpf_err_ptr(-EINVAL);
13472 	}
13473 
13474 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13475 	link_create_opts.tcx.relative_fd = relative_fd;
13476 	link_create_opts.tcx.relative_id = relative_id;
13477 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13478 
13479 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13480 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13481 }
13482 
13483 struct bpf_link *
13484 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13485 			   const struct bpf_netkit_opts *opts)
13486 {
13487 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13488 	__u32 relative_id;
13489 	int relative_fd;
13490 
13491 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13492 		return libbpf_err_ptr(-EINVAL);
13493 
13494 	relative_id = OPTS_GET(opts, relative_id, 0);
13495 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13496 
13497 	/* validate we don't have unexpected combinations of non-zero fields */
13498 	if (!ifindex) {
13499 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13500 			prog->name);
13501 		return libbpf_err_ptr(-EINVAL);
13502 	}
13503 	if (relative_fd && relative_id) {
13504 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13505 			prog->name);
13506 		return libbpf_err_ptr(-EINVAL);
13507 	}
13508 
13509 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13510 	link_create_opts.netkit.relative_fd = relative_fd;
13511 	link_create_opts.netkit.relative_id = relative_id;
13512 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13513 
13514 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13515 }
13516 
13517 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13518 					      int target_fd,
13519 					      const char *attach_func_name)
13520 {
13521 	int btf_id;
13522 
13523 	if (!!target_fd != !!attach_func_name) {
13524 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13525 			prog->name);
13526 		return libbpf_err_ptr(-EINVAL);
13527 	}
13528 
13529 	if (prog->type != BPF_PROG_TYPE_EXT) {
13530 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13531 			prog->name);
13532 		return libbpf_err_ptr(-EINVAL);
13533 	}
13534 
13535 	if (target_fd) {
13536 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13537 
13538 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13539 		if (btf_id < 0)
13540 			return libbpf_err_ptr(btf_id);
13541 
13542 		target_opts.target_btf_id = btf_id;
13543 
13544 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13545 					     &target_opts);
13546 	} else {
13547 		/* no target, so use raw_tracepoint_open for compatibility
13548 		 * with old kernels
13549 		 */
13550 		return bpf_program__attach_trace(prog);
13551 	}
13552 }
13553 
13554 struct bpf_link *
13555 bpf_program__attach_iter(const struct bpf_program *prog,
13556 			 const struct bpf_iter_attach_opts *opts)
13557 {
13558 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13559 	struct bpf_link *link;
13560 	int prog_fd, link_fd;
13561 	__u32 target_fd = 0;
13562 
13563 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13564 		return libbpf_err_ptr(-EINVAL);
13565 
13566 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13567 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13568 
13569 	prog_fd = bpf_program__fd(prog);
13570 	if (prog_fd < 0) {
13571 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13572 		return libbpf_err_ptr(-EINVAL);
13573 	}
13574 
13575 	link = calloc(1, sizeof(*link));
13576 	if (!link)
13577 		return libbpf_err_ptr(-ENOMEM);
13578 	link->detach = &bpf_link__detach_fd;
13579 
13580 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13581 				  &link_create_opts);
13582 	if (link_fd < 0) {
13583 		link_fd = -errno;
13584 		free(link);
13585 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13586 			prog->name, errstr(link_fd));
13587 		return libbpf_err_ptr(link_fd);
13588 	}
13589 	link->fd = link_fd;
13590 	return link;
13591 }
13592 
13593 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13594 {
13595 	*link = bpf_program__attach_iter(prog, NULL);
13596 	return libbpf_get_error(*link);
13597 }
13598 
13599 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13600 					       const struct bpf_netfilter_opts *opts)
13601 {
13602 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13603 	struct bpf_link *link;
13604 	int prog_fd, link_fd;
13605 
13606 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13607 		return libbpf_err_ptr(-EINVAL);
13608 
13609 	prog_fd = bpf_program__fd(prog);
13610 	if (prog_fd < 0) {
13611 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13612 		return libbpf_err_ptr(-EINVAL);
13613 	}
13614 
13615 	link = calloc(1, sizeof(*link));
13616 	if (!link)
13617 		return libbpf_err_ptr(-ENOMEM);
13618 
13619 	link->detach = &bpf_link__detach_fd;
13620 
13621 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13622 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13623 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13624 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13625 
13626 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13627 	if (link_fd < 0) {
13628 		link_fd = -errno;
13629 		free(link);
13630 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13631 			prog->name, errstr(link_fd));
13632 		return libbpf_err_ptr(link_fd);
13633 	}
13634 	link->fd = link_fd;
13635 
13636 	return link;
13637 }
13638 
13639 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13640 {
13641 	struct bpf_link *link = NULL;
13642 	int err;
13643 
13644 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13645 		return libbpf_err_ptr(-EOPNOTSUPP);
13646 
13647 	if (bpf_program__fd(prog) < 0) {
13648 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13649 			prog->name);
13650 		return libbpf_err_ptr(-EINVAL);
13651 	}
13652 
13653 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13654 	if (err)
13655 		return libbpf_err_ptr(err);
13656 
13657 	/* When calling bpf_program__attach() explicitly, auto-attach support
13658 	 * is expected to work, so NULL returned link is considered an error.
13659 	 * This is different for skeleton's attach, see comment in
13660 	 * bpf_object__attach_skeleton().
13661 	 */
13662 	if (!link)
13663 		return libbpf_err_ptr(-EOPNOTSUPP);
13664 
13665 	return link;
13666 }
13667 
13668 struct bpf_link_struct_ops {
13669 	struct bpf_link link;
13670 	int map_fd;
13671 };
13672 
13673 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13674 {
13675 	struct bpf_link_struct_ops *st_link;
13676 	__u32 zero = 0;
13677 
13678 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13679 
13680 	if (st_link->map_fd < 0)
13681 		/* w/o a real link */
13682 		return bpf_map_delete_elem(link->fd, &zero);
13683 
13684 	return close(link->fd);
13685 }
13686 
13687 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13688 {
13689 	struct bpf_link_struct_ops *link;
13690 	__u32 zero = 0;
13691 	int err, fd;
13692 
13693 	if (!bpf_map__is_struct_ops(map)) {
13694 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13695 		return libbpf_err_ptr(-EINVAL);
13696 	}
13697 
13698 	if (map->fd < 0) {
13699 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13700 		return libbpf_err_ptr(-EINVAL);
13701 	}
13702 
13703 	link = calloc(1, sizeof(*link));
13704 	if (!link)
13705 		return libbpf_err_ptr(-EINVAL);
13706 
13707 	/* kern_vdata should be prepared during the loading phase. */
13708 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13709 	/* It can be EBUSY if the map has been used to create or
13710 	 * update a link before.  We don't allow updating the value of
13711 	 * a struct_ops once it is set.  That ensures that the value
13712 	 * never changed.  So, it is safe to skip EBUSY.
13713 	 */
13714 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13715 		free(link);
13716 		return libbpf_err_ptr(err);
13717 	}
13718 
13719 	link->link.detach = bpf_link__detach_struct_ops;
13720 
13721 	if (!(map->def.map_flags & BPF_F_LINK)) {
13722 		/* w/o a real link */
13723 		link->link.fd = map->fd;
13724 		link->map_fd = -1;
13725 		return &link->link;
13726 	}
13727 
13728 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13729 	if (fd < 0) {
13730 		free(link);
13731 		return libbpf_err_ptr(fd);
13732 	}
13733 
13734 	link->link.fd = fd;
13735 	link->map_fd = map->fd;
13736 
13737 	return &link->link;
13738 }
13739 
13740 /*
13741  * Swap the back struct_ops of a link with a new struct_ops map.
13742  */
13743 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13744 {
13745 	struct bpf_link_struct_ops *st_ops_link;
13746 	__u32 zero = 0;
13747 	int err;
13748 
13749 	if (!bpf_map__is_struct_ops(map))
13750 		return libbpf_err(-EINVAL);
13751 
13752 	if (map->fd < 0) {
13753 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13754 		return libbpf_err(-EINVAL);
13755 	}
13756 
13757 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13758 	/* Ensure the type of a link is correct */
13759 	if (st_ops_link->map_fd < 0)
13760 		return libbpf_err(-EINVAL);
13761 
13762 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13763 	/* It can be EBUSY if the map has been used to create or
13764 	 * update a link before.  We don't allow updating the value of
13765 	 * a struct_ops once it is set.  That ensures that the value
13766 	 * never changed.  So, it is safe to skip EBUSY.
13767 	 */
13768 	if (err && err != -EBUSY)
13769 		return err;
13770 
13771 	err = bpf_link_update(link->fd, map->fd, NULL);
13772 	if (err < 0)
13773 		return err;
13774 
13775 	st_ops_link->map_fd = map->fd;
13776 
13777 	return 0;
13778 }
13779 
13780 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13781 							  void *private_data);
13782 
13783 static enum bpf_perf_event_ret
13784 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13785 		       void **copy_mem, size_t *copy_size,
13786 		       bpf_perf_event_print_t fn, void *private_data)
13787 {
13788 	struct perf_event_mmap_page *header = mmap_mem;
13789 	__u64 data_head = ring_buffer_read_head(header);
13790 	__u64 data_tail = header->data_tail;
13791 	void *base = ((__u8 *)header) + page_size;
13792 	int ret = LIBBPF_PERF_EVENT_CONT;
13793 	struct perf_event_header *ehdr;
13794 	size_t ehdr_size;
13795 
13796 	while (data_head != data_tail) {
13797 		ehdr = base + (data_tail & (mmap_size - 1));
13798 		ehdr_size = ehdr->size;
13799 
13800 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13801 			void *copy_start = ehdr;
13802 			size_t len_first = base + mmap_size - copy_start;
13803 			size_t len_secnd = ehdr_size - len_first;
13804 
13805 			if (*copy_size < ehdr_size) {
13806 				free(*copy_mem);
13807 				*copy_mem = malloc(ehdr_size);
13808 				if (!*copy_mem) {
13809 					*copy_size = 0;
13810 					ret = LIBBPF_PERF_EVENT_ERROR;
13811 					break;
13812 				}
13813 				*copy_size = ehdr_size;
13814 			}
13815 
13816 			memcpy(*copy_mem, copy_start, len_first);
13817 			memcpy(*copy_mem + len_first, base, len_secnd);
13818 			ehdr = *copy_mem;
13819 		}
13820 
13821 		ret = fn(ehdr, private_data);
13822 		data_tail += ehdr_size;
13823 		if (ret != LIBBPF_PERF_EVENT_CONT)
13824 			break;
13825 	}
13826 
13827 	ring_buffer_write_tail(header, data_tail);
13828 	return libbpf_err(ret);
13829 }
13830 
13831 struct perf_buffer;
13832 
13833 struct perf_buffer_params {
13834 	struct perf_event_attr *attr;
13835 	/* if event_cb is specified, it takes precendence */
13836 	perf_buffer_event_fn event_cb;
13837 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13838 	perf_buffer_sample_fn sample_cb;
13839 	perf_buffer_lost_fn lost_cb;
13840 	void *ctx;
13841 	int cpu_cnt;
13842 	int *cpus;
13843 	int *map_keys;
13844 };
13845 
13846 struct perf_cpu_buf {
13847 	struct perf_buffer *pb;
13848 	void *base; /* mmap()'ed memory */
13849 	void *buf; /* for reconstructing segmented data */
13850 	size_t buf_size;
13851 	int fd;
13852 	int cpu;
13853 	int map_key;
13854 };
13855 
13856 struct perf_buffer {
13857 	perf_buffer_event_fn event_cb;
13858 	perf_buffer_sample_fn sample_cb;
13859 	perf_buffer_lost_fn lost_cb;
13860 	void *ctx; /* passed into callbacks */
13861 
13862 	size_t page_size;
13863 	size_t mmap_size;
13864 	struct perf_cpu_buf **cpu_bufs;
13865 	struct epoll_event *events;
13866 	int cpu_cnt; /* number of allocated CPU buffers */
13867 	int epoll_fd; /* perf event FD */
13868 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13869 };
13870 
13871 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13872 				      struct perf_cpu_buf *cpu_buf)
13873 {
13874 	if (!cpu_buf)
13875 		return;
13876 	if (cpu_buf->base &&
13877 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13878 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13879 	if (cpu_buf->fd >= 0) {
13880 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13881 		close(cpu_buf->fd);
13882 	}
13883 	free(cpu_buf->buf);
13884 	free(cpu_buf);
13885 }
13886 
13887 void perf_buffer__free(struct perf_buffer *pb)
13888 {
13889 	int i;
13890 
13891 	if (IS_ERR_OR_NULL(pb))
13892 		return;
13893 	if (pb->cpu_bufs) {
13894 		for (i = 0; i < pb->cpu_cnt; i++) {
13895 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13896 
13897 			if (!cpu_buf)
13898 				continue;
13899 
13900 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13901 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13902 		}
13903 		free(pb->cpu_bufs);
13904 	}
13905 	if (pb->epoll_fd >= 0)
13906 		close(pb->epoll_fd);
13907 	free(pb->events);
13908 	free(pb);
13909 }
13910 
13911 static struct perf_cpu_buf *
13912 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13913 			  int cpu, int map_key)
13914 {
13915 	struct perf_cpu_buf *cpu_buf;
13916 	int err;
13917 
13918 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13919 	if (!cpu_buf)
13920 		return ERR_PTR(-ENOMEM);
13921 
13922 	cpu_buf->pb = pb;
13923 	cpu_buf->cpu = cpu;
13924 	cpu_buf->map_key = map_key;
13925 
13926 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13927 			      -1, PERF_FLAG_FD_CLOEXEC);
13928 	if (cpu_buf->fd < 0) {
13929 		err = -errno;
13930 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13931 			cpu, errstr(err));
13932 		goto error;
13933 	}
13934 
13935 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13936 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13937 			     cpu_buf->fd, 0);
13938 	if (cpu_buf->base == MAP_FAILED) {
13939 		cpu_buf->base = NULL;
13940 		err = -errno;
13941 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13942 			cpu, errstr(err));
13943 		goto error;
13944 	}
13945 
13946 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13947 		err = -errno;
13948 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13949 			cpu, errstr(err));
13950 		goto error;
13951 	}
13952 
13953 	return cpu_buf;
13954 
13955 error:
13956 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13957 	return (struct perf_cpu_buf *)ERR_PTR(err);
13958 }
13959 
13960 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13961 					      struct perf_buffer_params *p);
13962 
13963 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13964 				     perf_buffer_sample_fn sample_cb,
13965 				     perf_buffer_lost_fn lost_cb,
13966 				     void *ctx,
13967 				     const struct perf_buffer_opts *opts)
13968 {
13969 	const size_t attr_sz = sizeof(struct perf_event_attr);
13970 	struct perf_buffer_params p = {};
13971 	struct perf_event_attr attr;
13972 	__u32 sample_period;
13973 
13974 	if (!OPTS_VALID(opts, perf_buffer_opts))
13975 		return libbpf_err_ptr(-EINVAL);
13976 
13977 	sample_period = OPTS_GET(opts, sample_period, 1);
13978 	if (!sample_period)
13979 		sample_period = 1;
13980 
13981 	memset(&attr, 0, attr_sz);
13982 	attr.size = attr_sz;
13983 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13984 	attr.type = PERF_TYPE_SOFTWARE;
13985 	attr.sample_type = PERF_SAMPLE_RAW;
13986 	attr.wakeup_events = sample_period;
13987 
13988 	p.attr = &attr;
13989 	p.sample_cb = sample_cb;
13990 	p.lost_cb = lost_cb;
13991 	p.ctx = ctx;
13992 
13993 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13994 }
13995 
13996 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13997 					 struct perf_event_attr *attr,
13998 					 perf_buffer_event_fn event_cb, void *ctx,
13999 					 const struct perf_buffer_raw_opts *opts)
14000 {
14001 	struct perf_buffer_params p = {};
14002 
14003 	if (!attr)
14004 		return libbpf_err_ptr(-EINVAL);
14005 
14006 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
14007 		return libbpf_err_ptr(-EINVAL);
14008 
14009 	p.attr = attr;
14010 	p.event_cb = event_cb;
14011 	p.ctx = ctx;
14012 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
14013 	p.cpus = OPTS_GET(opts, cpus, NULL);
14014 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
14015 
14016 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14017 }
14018 
14019 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14020 					      struct perf_buffer_params *p)
14021 {
14022 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
14023 	struct bpf_map_info map;
14024 	struct perf_buffer *pb;
14025 	bool *online = NULL;
14026 	__u32 map_info_len;
14027 	int err, i, j, n;
14028 
14029 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
14030 		pr_warn("page count should be power of two, but is %zu\n",
14031 			page_cnt);
14032 		return ERR_PTR(-EINVAL);
14033 	}
14034 
14035 	/* best-effort sanity checks */
14036 	memset(&map, 0, sizeof(map));
14037 	map_info_len = sizeof(map);
14038 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
14039 	if (err) {
14040 		err = -errno;
14041 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
14042 		 * -EBADFD, -EFAULT, or -E2BIG on real error
14043 		 */
14044 		if (err != -EINVAL) {
14045 			pr_warn("failed to get map info for map FD %d: %s\n",
14046 				map_fd, errstr(err));
14047 			return ERR_PTR(err);
14048 		}
14049 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
14050 			 map_fd);
14051 	} else {
14052 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
14053 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
14054 				map.name);
14055 			return ERR_PTR(-EINVAL);
14056 		}
14057 	}
14058 
14059 	pb = calloc(1, sizeof(*pb));
14060 	if (!pb)
14061 		return ERR_PTR(-ENOMEM);
14062 
14063 	pb->event_cb = p->event_cb;
14064 	pb->sample_cb = p->sample_cb;
14065 	pb->lost_cb = p->lost_cb;
14066 	pb->ctx = p->ctx;
14067 
14068 	pb->page_size = getpagesize();
14069 	pb->mmap_size = pb->page_size * page_cnt;
14070 	pb->map_fd = map_fd;
14071 
14072 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
14073 	if (pb->epoll_fd < 0) {
14074 		err = -errno;
14075 		pr_warn("failed to create epoll instance: %s\n",
14076 			errstr(err));
14077 		goto error;
14078 	}
14079 
14080 	if (p->cpu_cnt > 0) {
14081 		pb->cpu_cnt = p->cpu_cnt;
14082 	} else {
14083 		pb->cpu_cnt = libbpf_num_possible_cpus();
14084 		if (pb->cpu_cnt < 0) {
14085 			err = pb->cpu_cnt;
14086 			goto error;
14087 		}
14088 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
14089 			pb->cpu_cnt = map.max_entries;
14090 	}
14091 
14092 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
14093 	if (!pb->events) {
14094 		err = -ENOMEM;
14095 		pr_warn("failed to allocate events: out of memory\n");
14096 		goto error;
14097 	}
14098 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
14099 	if (!pb->cpu_bufs) {
14100 		err = -ENOMEM;
14101 		pr_warn("failed to allocate buffers: out of memory\n");
14102 		goto error;
14103 	}
14104 
14105 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
14106 	if (err) {
14107 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
14108 		goto error;
14109 	}
14110 
14111 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
14112 		struct perf_cpu_buf *cpu_buf;
14113 		int cpu, map_key;
14114 
14115 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
14116 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
14117 
14118 		/* in case user didn't explicitly requested particular CPUs to
14119 		 * be attached to, skip offline/not present CPUs
14120 		 */
14121 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
14122 			continue;
14123 
14124 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
14125 		if (IS_ERR(cpu_buf)) {
14126 			err = PTR_ERR(cpu_buf);
14127 			goto error;
14128 		}
14129 
14130 		pb->cpu_bufs[j] = cpu_buf;
14131 
14132 		err = bpf_map_update_elem(pb->map_fd, &map_key,
14133 					  &cpu_buf->fd, 0);
14134 		if (err) {
14135 			err = -errno;
14136 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
14137 				cpu, map_key, cpu_buf->fd,
14138 				errstr(err));
14139 			goto error;
14140 		}
14141 
14142 		pb->events[j].events = EPOLLIN;
14143 		pb->events[j].data.ptr = cpu_buf;
14144 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
14145 			      &pb->events[j]) < 0) {
14146 			err = -errno;
14147 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
14148 				cpu, cpu_buf->fd,
14149 				errstr(err));
14150 			goto error;
14151 		}
14152 		j++;
14153 	}
14154 	pb->cpu_cnt = j;
14155 	free(online);
14156 
14157 	return pb;
14158 
14159 error:
14160 	free(online);
14161 	if (pb)
14162 		perf_buffer__free(pb);
14163 	return ERR_PTR(err);
14164 }
14165 
14166 struct perf_sample_raw {
14167 	struct perf_event_header header;
14168 	uint32_t size;
14169 	char data[];
14170 };
14171 
14172 struct perf_sample_lost {
14173 	struct perf_event_header header;
14174 	uint64_t id;
14175 	uint64_t lost;
14176 	uint64_t sample_id;
14177 };
14178 
14179 static enum bpf_perf_event_ret
14180 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
14181 {
14182 	struct perf_cpu_buf *cpu_buf = ctx;
14183 	struct perf_buffer *pb = cpu_buf->pb;
14184 	void *data = e;
14185 
14186 	/* user wants full control over parsing perf event */
14187 	if (pb->event_cb)
14188 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
14189 
14190 	switch (e->type) {
14191 	case PERF_RECORD_SAMPLE: {
14192 		struct perf_sample_raw *s = data;
14193 
14194 		if (pb->sample_cb)
14195 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
14196 		break;
14197 	}
14198 	case PERF_RECORD_LOST: {
14199 		struct perf_sample_lost *s = data;
14200 
14201 		if (pb->lost_cb)
14202 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
14203 		break;
14204 	}
14205 	default:
14206 		pr_warn("unknown perf sample type %d\n", e->type);
14207 		return LIBBPF_PERF_EVENT_ERROR;
14208 	}
14209 	return LIBBPF_PERF_EVENT_CONT;
14210 }
14211 
14212 static int perf_buffer__process_records(struct perf_buffer *pb,
14213 					struct perf_cpu_buf *cpu_buf)
14214 {
14215 	enum bpf_perf_event_ret ret;
14216 
14217 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
14218 				     pb->page_size, &cpu_buf->buf,
14219 				     &cpu_buf->buf_size,
14220 				     perf_buffer__process_record, cpu_buf);
14221 	if (ret != LIBBPF_PERF_EVENT_CONT)
14222 		return ret;
14223 	return 0;
14224 }
14225 
14226 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14227 {
14228 	return pb->epoll_fd;
14229 }
14230 
14231 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14232 {
14233 	int i, cnt, err;
14234 
14235 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14236 	if (cnt < 0)
14237 		return -errno;
14238 
14239 	for (i = 0; i < cnt; i++) {
14240 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14241 
14242 		err = perf_buffer__process_records(pb, cpu_buf);
14243 		if (err) {
14244 			pr_warn("error while processing records: %s\n", errstr(err));
14245 			return libbpf_err(err);
14246 		}
14247 	}
14248 	return cnt;
14249 }
14250 
14251 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14252  * manager.
14253  */
14254 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14255 {
14256 	return pb->cpu_cnt;
14257 }
14258 
14259 /*
14260  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14261  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14262  * select()/poll()/epoll() Linux syscalls.
14263  */
14264 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14265 {
14266 	struct perf_cpu_buf *cpu_buf;
14267 
14268 	if (buf_idx >= pb->cpu_cnt)
14269 		return libbpf_err(-EINVAL);
14270 
14271 	cpu_buf = pb->cpu_bufs[buf_idx];
14272 	if (!cpu_buf)
14273 		return libbpf_err(-ENOENT);
14274 
14275 	return cpu_buf->fd;
14276 }
14277 
14278 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14279 {
14280 	struct perf_cpu_buf *cpu_buf;
14281 
14282 	if (buf_idx >= pb->cpu_cnt)
14283 		return libbpf_err(-EINVAL);
14284 
14285 	cpu_buf = pb->cpu_bufs[buf_idx];
14286 	if (!cpu_buf)
14287 		return libbpf_err(-ENOENT);
14288 
14289 	*buf = cpu_buf->base;
14290 	*buf_size = pb->mmap_size;
14291 	return 0;
14292 }
14293 
14294 /*
14295  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14296  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14297  * consume, do nothing and return success.
14298  * Returns:
14299  *   - 0 on success;
14300  *   - <0 on failure.
14301  */
14302 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14303 {
14304 	struct perf_cpu_buf *cpu_buf;
14305 
14306 	if (buf_idx >= pb->cpu_cnt)
14307 		return libbpf_err(-EINVAL);
14308 
14309 	cpu_buf = pb->cpu_bufs[buf_idx];
14310 	if (!cpu_buf)
14311 		return libbpf_err(-ENOENT);
14312 
14313 	return perf_buffer__process_records(pb, cpu_buf);
14314 }
14315 
14316 int perf_buffer__consume(struct perf_buffer *pb)
14317 {
14318 	int i, err;
14319 
14320 	for (i = 0; i < pb->cpu_cnt; i++) {
14321 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14322 
14323 		if (!cpu_buf)
14324 			continue;
14325 
14326 		err = perf_buffer__process_records(pb, cpu_buf);
14327 		if (err) {
14328 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14329 				i, errstr(err));
14330 			return libbpf_err(err);
14331 		}
14332 	}
14333 	return 0;
14334 }
14335 
14336 int bpf_program__set_attach_target(struct bpf_program *prog,
14337 				   int attach_prog_fd,
14338 				   const char *attach_func_name)
14339 {
14340 	int btf_obj_fd = 0, btf_id = 0, err;
14341 
14342 	if (!prog || attach_prog_fd < 0)
14343 		return libbpf_err(-EINVAL);
14344 
14345 	if (prog->obj->state >= OBJ_LOADED)
14346 		return libbpf_err(-EINVAL);
14347 
14348 	if (attach_prog_fd && !attach_func_name) {
14349 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14350 		 * the normal object/program load phase.
14351 		 */
14352 		prog->attach_prog_fd = attach_prog_fd;
14353 		return 0;
14354 	}
14355 
14356 	if (attach_prog_fd) {
14357 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14358 						 attach_prog_fd, prog->obj->token_fd);
14359 		if (btf_id < 0)
14360 			return libbpf_err(btf_id);
14361 	} else {
14362 		if (!attach_func_name)
14363 			return libbpf_err(-EINVAL);
14364 
14365 		/* load btf_vmlinux, if not yet */
14366 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14367 		if (err)
14368 			return libbpf_err(err);
14369 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14370 					 prog->expected_attach_type,
14371 					 &btf_obj_fd, &btf_id);
14372 		if (err)
14373 			return libbpf_err(err);
14374 	}
14375 
14376 	prog->attach_btf_id = btf_id;
14377 	prog->attach_btf_obj_fd = btf_obj_fd;
14378 	prog->attach_prog_fd = attach_prog_fd;
14379 	return 0;
14380 }
14381 
14382 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14383 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14384 {
14385 	int prog_fd, map_fd;
14386 
14387 	prog_fd = bpf_program__fd(prog);
14388 	if (prog_fd < 0) {
14389 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14390 			prog->name);
14391 		return libbpf_err(-EINVAL);
14392 	}
14393 
14394 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14395 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14396 		return libbpf_err(-EINVAL);
14397 	}
14398 
14399 	map_fd = bpf_map__fd(map);
14400 	if (map_fd < 0) {
14401 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14402 		return libbpf_err(-EINVAL);
14403 	}
14404 
14405 	if (!bpf_map__is_struct_ops(map)) {
14406 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14407 		return libbpf_err(-EINVAL);
14408 	}
14409 
14410 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14411 }
14412 
14413 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14414 {
14415 	int err = 0, n, len, start, end = -1;
14416 	bool *tmp;
14417 
14418 	*mask = NULL;
14419 	*mask_sz = 0;
14420 
14421 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14422 	while (*s) {
14423 		if (*s == ',' || *s == '\n') {
14424 			s++;
14425 			continue;
14426 		}
14427 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14428 		if (n <= 0 || n > 2) {
14429 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14430 			err = -EINVAL;
14431 			goto cleanup;
14432 		} else if (n == 1) {
14433 			end = start;
14434 		}
14435 		if (start < 0 || start > end) {
14436 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14437 				start, end, s);
14438 			err = -EINVAL;
14439 			goto cleanup;
14440 		}
14441 		tmp = realloc(*mask, end + 1);
14442 		if (!tmp) {
14443 			err = -ENOMEM;
14444 			goto cleanup;
14445 		}
14446 		*mask = tmp;
14447 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14448 		memset(tmp + start, 1, end - start + 1);
14449 		*mask_sz = end + 1;
14450 		s += len;
14451 	}
14452 	if (!*mask_sz) {
14453 		pr_warn("Empty CPU range\n");
14454 		return -EINVAL;
14455 	}
14456 	return 0;
14457 cleanup:
14458 	free(*mask);
14459 	*mask = NULL;
14460 	return err;
14461 }
14462 
14463 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14464 {
14465 	int fd, err = 0, len;
14466 	char buf[128];
14467 
14468 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14469 	if (fd < 0) {
14470 		err = -errno;
14471 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14472 		return err;
14473 	}
14474 	len = read(fd, buf, sizeof(buf));
14475 	close(fd);
14476 	if (len <= 0) {
14477 		err = len ? -errno : -EINVAL;
14478 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14479 		return err;
14480 	}
14481 	if (len >= sizeof(buf)) {
14482 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14483 		return -E2BIG;
14484 	}
14485 	buf[len] = '\0';
14486 
14487 	return parse_cpu_mask_str(buf, mask, mask_sz);
14488 }
14489 
14490 int libbpf_num_possible_cpus(void)
14491 {
14492 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14493 	static int cpus;
14494 	int err, n, i, tmp_cpus;
14495 	bool *mask;
14496 
14497 	tmp_cpus = READ_ONCE(cpus);
14498 	if (tmp_cpus > 0)
14499 		return tmp_cpus;
14500 
14501 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14502 	if (err)
14503 		return libbpf_err(err);
14504 
14505 	tmp_cpus = 0;
14506 	for (i = 0; i < n; i++) {
14507 		if (mask[i])
14508 			tmp_cpus++;
14509 	}
14510 	free(mask);
14511 
14512 	WRITE_ONCE(cpus, tmp_cpus);
14513 	return tmp_cpus;
14514 }
14515 
14516 static int populate_skeleton_maps(const struct bpf_object *obj,
14517 				  struct bpf_map_skeleton *maps,
14518 				  size_t map_cnt, size_t map_skel_sz)
14519 {
14520 	int i;
14521 
14522 	for (i = 0; i < map_cnt; i++) {
14523 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14524 		struct bpf_map **map = map_skel->map;
14525 		const char *name = map_skel->name;
14526 		void **mmaped = map_skel->mmaped;
14527 
14528 		*map = bpf_object__find_map_by_name(obj, name);
14529 		if (!*map) {
14530 			pr_warn("failed to find skeleton map '%s'\n", name);
14531 			return -ESRCH;
14532 		}
14533 
14534 		/* externs shouldn't be pre-setup from user code */
14535 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14536 			*mmaped = (*map)->mmaped;
14537 	}
14538 	return 0;
14539 }
14540 
14541 static int populate_skeleton_progs(const struct bpf_object *obj,
14542 				   struct bpf_prog_skeleton *progs,
14543 				   size_t prog_cnt, size_t prog_skel_sz)
14544 {
14545 	int i;
14546 
14547 	for (i = 0; i < prog_cnt; i++) {
14548 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14549 		struct bpf_program **prog = prog_skel->prog;
14550 		const char *name = prog_skel->name;
14551 
14552 		*prog = bpf_object__find_program_by_name(obj, name);
14553 		if (!*prog) {
14554 			pr_warn("failed to find skeleton program '%s'\n", name);
14555 			return -ESRCH;
14556 		}
14557 	}
14558 	return 0;
14559 }
14560 
14561 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14562 			      const struct bpf_object_open_opts *opts)
14563 {
14564 	struct bpf_object *obj;
14565 	int err;
14566 
14567 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14568 	if (IS_ERR(obj)) {
14569 		err = PTR_ERR(obj);
14570 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14571 			s->name, errstr(err));
14572 		return libbpf_err(err);
14573 	}
14574 
14575 	*s->obj = obj;
14576 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14577 	if (err) {
14578 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14579 		return libbpf_err(err);
14580 	}
14581 
14582 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14583 	if (err) {
14584 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14585 		return libbpf_err(err);
14586 	}
14587 
14588 	return 0;
14589 }
14590 
14591 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14592 {
14593 	int err, len, var_idx, i;
14594 	const char *var_name;
14595 	const struct bpf_map *map;
14596 	struct btf *btf;
14597 	__u32 map_type_id;
14598 	const struct btf_type *map_type, *var_type;
14599 	const struct bpf_var_skeleton *var_skel;
14600 	struct btf_var_secinfo *var;
14601 
14602 	if (!s->obj)
14603 		return libbpf_err(-EINVAL);
14604 
14605 	btf = bpf_object__btf(s->obj);
14606 	if (!btf) {
14607 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14608 			bpf_object__name(s->obj));
14609 		return libbpf_err(-errno);
14610 	}
14611 
14612 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14613 	if (err) {
14614 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14615 		return libbpf_err(err);
14616 	}
14617 
14618 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14619 	if (err) {
14620 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14621 		return libbpf_err(err);
14622 	}
14623 
14624 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14625 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14626 		map = *var_skel->map;
14627 		map_type_id = bpf_map__btf_value_type_id(map);
14628 		map_type = btf__type_by_id(btf, map_type_id);
14629 
14630 		if (!btf_is_datasec(map_type)) {
14631 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14632 				bpf_map__name(map),
14633 				__btf_kind_str(btf_kind(map_type)));
14634 			return libbpf_err(-EINVAL);
14635 		}
14636 
14637 		len = btf_vlen(map_type);
14638 		var = btf_var_secinfos(map_type);
14639 		for (i = 0; i < len; i++, var++) {
14640 			var_type = btf__type_by_id(btf, var->type);
14641 			var_name = btf__name_by_offset(btf, var_type->name_off);
14642 			if (strcmp(var_name, var_skel->name) == 0) {
14643 				*var_skel->addr = map->mmaped + var->offset;
14644 				break;
14645 			}
14646 		}
14647 	}
14648 	return 0;
14649 }
14650 
14651 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14652 {
14653 	if (!s)
14654 		return;
14655 	free(s->maps);
14656 	free(s->progs);
14657 	free(s->vars);
14658 	free(s);
14659 }
14660 
14661 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14662 {
14663 	int i, err;
14664 
14665 	err = bpf_object__load(*s->obj);
14666 	if (err) {
14667 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14668 		return libbpf_err(err);
14669 	}
14670 
14671 	for (i = 0; i < s->map_cnt; i++) {
14672 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14673 		struct bpf_map *map = *map_skel->map;
14674 
14675 		if (!map_skel->mmaped)
14676 			continue;
14677 
14678 		if (map->def.type == BPF_MAP_TYPE_ARENA)
14679 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
14680 		else
14681 			*map_skel->mmaped = map->mmaped;
14682 	}
14683 
14684 	return 0;
14685 }
14686 
14687 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14688 {
14689 	int i, err;
14690 
14691 	for (i = 0; i < s->prog_cnt; i++) {
14692 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14693 		struct bpf_program *prog = *prog_skel->prog;
14694 		struct bpf_link **link = prog_skel->link;
14695 
14696 		if (!prog->autoload || !prog->autoattach)
14697 			continue;
14698 
14699 		/* auto-attaching not supported for this program */
14700 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14701 			continue;
14702 
14703 		/* if user already set the link manually, don't attempt auto-attach */
14704 		if (*link)
14705 			continue;
14706 
14707 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14708 		if (err) {
14709 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14710 				bpf_program__name(prog), errstr(err));
14711 			return libbpf_err(err);
14712 		}
14713 
14714 		/* It's possible that for some SEC() definitions auto-attach
14715 		 * is supported in some cases (e.g., if definition completely
14716 		 * specifies target information), but is not in other cases.
14717 		 * SEC("uprobe") is one such case. If user specified target
14718 		 * binary and function name, such BPF program can be
14719 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14720 		 * attach to fail. It should just be skipped.
14721 		 * attach_fn signals such case with returning 0 (no error) and
14722 		 * setting link to NULL.
14723 		 */
14724 	}
14725 
14726 
14727 	for (i = 0; i < s->map_cnt; i++) {
14728 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14729 		struct bpf_map *map = *map_skel->map;
14730 		struct bpf_link **link;
14731 
14732 		if (!map->autocreate || !map->autoattach)
14733 			continue;
14734 
14735 		/* only struct_ops maps can be attached */
14736 		if (!bpf_map__is_struct_ops(map))
14737 			continue;
14738 
14739 		/* skeleton is created with earlier version of bpftool, notify user */
14740 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14741 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14742 				bpf_map__name(map));
14743 			continue;
14744 		}
14745 
14746 		link = map_skel->link;
14747 		if (!link) {
14748 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14749 				bpf_map__name(map));
14750 			continue;
14751 		}
14752 
14753 		if (*link)
14754 			continue;
14755 
14756 		*link = bpf_map__attach_struct_ops(map);
14757 		if (!*link) {
14758 			err = -errno;
14759 			pr_warn("map '%s': failed to auto-attach: %s\n",
14760 				bpf_map__name(map), errstr(err));
14761 			return libbpf_err(err);
14762 		}
14763 	}
14764 
14765 	return 0;
14766 }
14767 
14768 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14769 {
14770 	int i;
14771 
14772 	for (i = 0; i < s->prog_cnt; i++) {
14773 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14774 		struct bpf_link **link = prog_skel->link;
14775 
14776 		bpf_link__destroy(*link);
14777 		*link = NULL;
14778 	}
14779 
14780 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14781 		return;
14782 
14783 	for (i = 0; i < s->map_cnt; i++) {
14784 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14785 		struct bpf_link **link = map_skel->link;
14786 
14787 		if (link) {
14788 			bpf_link__destroy(*link);
14789 			*link = NULL;
14790 		}
14791 	}
14792 }
14793 
14794 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14795 {
14796 	if (!s)
14797 		return;
14798 
14799 	bpf_object__detach_skeleton(s);
14800 	if (s->obj)
14801 		bpf_object__close(*s->obj);
14802 	free(s->maps);
14803 	free(s->progs);
14804 	free(s);
14805 }
14806