xref: /linux/tools/lib/bpf/libbpf.c (revision fab183d632628381b466a41479489541ac0e29a0)
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 	[BPF_TRACE_FENTRY_MULTI]	= "trace_fentry_multi",
140 	[BPF_TRACE_FEXIT_MULTI]		= "trace_fexit_multi",
141 	[BPF_TRACE_FSESSION_MULTI]	= "trace_fsession_multi",
142 };
143 
144 static const char * const link_type_name[] = {
145 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
146 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
147 	[BPF_LINK_TYPE_TRACING]			= "tracing",
148 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
149 	[BPF_LINK_TYPE_ITER]			= "iter",
150 	[BPF_LINK_TYPE_NETNS]			= "netns",
151 	[BPF_LINK_TYPE_XDP]			= "xdp",
152 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
153 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
154 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
155 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
156 	[BPF_LINK_TYPE_TCX]			= "tcx",
157 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
158 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
159 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
160 	[BPF_LINK_TYPE_TRACING_MULTI]		= "tracing_multi",
161 };
162 
163 static const char * const map_type_name[] = {
164 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
165 	[BPF_MAP_TYPE_HASH]			= "hash",
166 	[BPF_MAP_TYPE_ARRAY]			= "array",
167 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
168 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
169 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
170 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
171 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
172 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
173 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
174 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
175 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
176 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
177 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
178 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
179 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
180 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
181 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
182 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
183 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
184 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
185 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
186 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
187 	[BPF_MAP_TYPE_QUEUE]			= "queue",
188 	[BPF_MAP_TYPE_STACK]			= "stack",
189 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
190 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
191 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
192 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
193 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
194 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
195 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
196 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
197 	[BPF_MAP_TYPE_ARENA]			= "arena",
198 	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
199 	[BPF_MAP_TYPE_RHASH]			= "rhash",
200 };
201 
202 static const char * const prog_type_name[] = {
203 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
204 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
205 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
206 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
207 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
208 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
209 	[BPF_PROG_TYPE_XDP]			= "xdp",
210 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
211 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
212 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
213 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
214 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
215 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
216 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
217 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
218 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
219 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
220 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
221 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
222 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
223 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
224 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
225 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
226 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
227 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
228 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
229 	[BPF_PROG_TYPE_TRACING]			= "tracing",
230 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
231 	[BPF_PROG_TYPE_EXT]			= "ext",
232 	[BPF_PROG_TYPE_LSM]			= "lsm",
233 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
234 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
235 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
236 };
237 
238 static int __base_pr(enum libbpf_print_level level, const char *format,
239 		     va_list args)
240 {
241 	const char *env_var = "LIBBPF_LOG_LEVEL";
242 	static enum libbpf_print_level min_level = LIBBPF_INFO;
243 	static bool initialized;
244 
245 	if (!initialized) {
246 		char *verbosity;
247 
248 		initialized = true;
249 		verbosity = getenv(env_var);
250 		if (verbosity) {
251 			if (strcasecmp(verbosity, "warn") == 0)
252 				min_level = LIBBPF_WARN;
253 			else if (strcasecmp(verbosity, "debug") == 0)
254 				min_level = LIBBPF_DEBUG;
255 			else if (strcasecmp(verbosity, "info") == 0)
256 				min_level = LIBBPF_INFO;
257 			else
258 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
259 					env_var, verbosity);
260 		}
261 	}
262 
263 	/* if too verbose, skip logging  */
264 	if (level > min_level)
265 		return 0;
266 
267 	return vfprintf(stderr, format, args);
268 }
269 
270 static libbpf_print_fn_t __libbpf_pr = __base_pr;
271 
272 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
273 {
274 	libbpf_print_fn_t old_print_fn;
275 
276 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
277 
278 	return old_print_fn;
279 }
280 
281 __printf(2, 3)
282 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
283 {
284 	va_list args;
285 	int old_errno;
286 	libbpf_print_fn_t print_fn;
287 
288 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
289 	if (!print_fn)
290 		return;
291 
292 	old_errno = errno;
293 
294 	va_start(args, format);
295 	print_fn(level, format, args);
296 	va_end(args);
297 
298 	errno = old_errno;
299 }
300 
301 static void pr_perm_msg(int err)
302 {
303 	struct rlimit limit;
304 	char buf[100];
305 
306 	if (err != -EPERM || geteuid() != 0)
307 		return;
308 
309 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
310 	if (err)
311 		return;
312 
313 	if (limit.rlim_cur == RLIM_INFINITY)
314 		return;
315 
316 	if (limit.rlim_cur < 1024)
317 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
318 	else if (limit.rlim_cur < 1024*1024)
319 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
320 	else
321 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
322 
323 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
324 		buf);
325 }
326 
327 /* Copied from tools/perf/util/util.h */
328 #ifndef zfree
329 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
330 #endif
331 
332 #ifndef zclose
333 # define zclose(fd) ({			\
334 	int ___err = 0;			\
335 	if ((fd) >= 0)			\
336 		___err = close((fd));	\
337 	fd = -1;			\
338 	___err; })
339 #endif
340 
341 static inline __u64 ptr_to_u64(const void *ptr)
342 {
343 	return (__u64) (unsigned long) ptr;
344 }
345 
346 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
347 {
348 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
349 	return 0;
350 }
351 
352 __u32 libbpf_major_version(void)
353 {
354 	return LIBBPF_MAJOR_VERSION;
355 }
356 
357 __u32 libbpf_minor_version(void)
358 {
359 	return LIBBPF_MINOR_VERSION;
360 }
361 
362 const char *libbpf_version_string(void)
363 {
364 #define __S(X) #X
365 #define _S(X) __S(X)
366 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
367 #undef _S
368 #undef __S
369 }
370 
371 enum reloc_type {
372 	RELO_LD64,
373 	RELO_CALL,
374 	RELO_DATA,
375 	RELO_EXTERN_LD64,
376 	RELO_EXTERN_CALL,
377 	RELO_SUBPROG_ADDR,
378 	RELO_CORE,
379 	RELO_INSN_ARRAY,
380 };
381 
382 struct reloc_desc {
383 	enum reloc_type type;
384 	int insn_idx;
385 	union {
386 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
387 		struct {
388 			int map_idx;
389 			unsigned int sym_off;
390 			/*
391 			 * The following two fields can be unionized, as the
392 			 * ext_idx field is used for extern symbols, and the
393 			 * sym_size is used for jump tables, which are never
394 			 * extern
395 			 */
396 			union {
397 				int ext_idx;
398 				int sym_size;
399 			};
400 		};
401 	};
402 };
403 
404 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
405 enum sec_def_flags {
406 	SEC_NONE = 0,
407 	/* expected_attach_type is optional, if kernel doesn't support that */
408 	SEC_EXP_ATTACH_OPT = 1,
409 	/* legacy, only used by libbpf_get_type_names() and
410 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
411 	 * This used to be associated with cgroup (and few other) BPF programs
412 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
413 	 * meaningless nowadays, though.
414 	 */
415 	SEC_ATTACHABLE = 2,
416 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
417 	/* attachment target is specified through BTF ID in either kernel or
418 	 * other BPF program's BTF object
419 	 */
420 	SEC_ATTACH_BTF = 4,
421 	/* BPF program type allows sleeping/blocking in kernel */
422 	SEC_SLEEPABLE = 8,
423 	/* BPF program support non-linear XDP buffer */
424 	SEC_XDP_FRAGS = 16,
425 	/* Setup proper attach type for usdt probes. */
426 	SEC_USDT = 32,
427 };
428 
429 struct bpf_sec_def {
430 	char *sec;
431 	enum bpf_prog_type prog_type;
432 	enum bpf_attach_type expected_attach_type;
433 	long cookie;
434 	int handler_id;
435 
436 	libbpf_prog_setup_fn_t prog_setup_fn;
437 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
438 	libbpf_prog_attach_fn_t prog_attach_fn;
439 };
440 
441 struct bpf_light_subprog {
442 	__u32 sec_insn_off;
443 	__u32 sub_insn_off;
444 };
445 
446 /*
447  * bpf_prog should be a better name but it has been used in
448  * linux/filter.h.
449  */
450 struct bpf_program {
451 	char *name;
452 	char *sec_name;
453 	size_t sec_idx;
454 	const struct bpf_sec_def *sec_def;
455 	/* this program's instruction offset (in number of instructions)
456 	 * within its containing ELF section
457 	 */
458 	size_t sec_insn_off;
459 	/* number of original instructions in ELF section belonging to this
460 	 * program, not taking into account subprogram instructions possible
461 	 * appended later during relocation
462 	 */
463 	size_t sec_insn_cnt;
464 	/* Offset (in number of instructions) of the start of instruction
465 	 * belonging to this BPF program  within its containing main BPF
466 	 * program. For the entry-point (main) BPF program, this is always
467 	 * zero. For a sub-program, this gets reset before each of main BPF
468 	 * programs are processed and relocated and is used to determined
469 	 * whether sub-program was already appended to the main program, and
470 	 * if yes, at which instruction offset.
471 	 */
472 	size_t sub_insn_off;
473 
474 	/* instructions that belong to BPF program; insns[0] is located at
475 	 * sec_insn_off instruction within its ELF section in ELF file, so
476 	 * when mapping ELF file instruction index to the local instruction,
477 	 * one needs to subtract sec_insn_off; and vice versa.
478 	 */
479 	struct bpf_insn *insns;
480 	/* actual number of instruction in this BPF program's image; for
481 	 * entry-point BPF programs this includes the size of main program
482 	 * itself plus all the used sub-programs, appended at the end
483 	 */
484 	size_t insns_cnt;
485 
486 	struct reloc_desc *reloc_desc;
487 	int nr_reloc;
488 
489 	/* BPF verifier log settings */
490 	char *log_buf;
491 	size_t log_size;
492 	__u32 log_level;
493 
494 	struct bpf_object *obj;
495 
496 	int fd;
497 	bool autoload;
498 	bool autoattach;
499 	bool sym_global;
500 	bool mark_btf_static;
501 	enum bpf_prog_type type;
502 	enum bpf_attach_type expected_attach_type;
503 	int exception_cb_idx;
504 
505 	int prog_ifindex;
506 	__u32 attach_btf_obj_fd;
507 	__u32 attach_btf_id;
508 	__u32 attach_prog_fd;
509 
510 	void *func_info;
511 	__u32 func_info_rec_size;
512 	__u32 func_info_cnt;
513 
514 	void *line_info;
515 	__u32 line_info_rec_size;
516 	__u32 line_info_cnt;
517 	__u32 prog_flags;
518 	__u8  hash[SHA256_DIGEST_LENGTH];
519 
520 	struct bpf_light_subprog *subprogs;
521 	__u32 subprog_cnt;
522 };
523 
524 struct bpf_struct_ops {
525 	struct bpf_program **progs;
526 	__u32 *kern_func_off;
527 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
528 	void *data;
529 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
530 	 *      btf_vmlinux's format.
531 	 * struct bpf_struct_ops_tcp_congestion_ops {
532 	 *	[... some other kernel fields ...]
533 	 *	struct tcp_congestion_ops data;
534 	 * }
535 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
536 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
537 	 * from "data".
538 	 */
539 	void *kern_vdata;
540 	__u32 type_id;
541 };
542 
543 #define DATA_SEC ".data"
544 #define BSS_SEC ".bss"
545 #define RODATA_SEC ".rodata"
546 #define KCONFIG_SEC ".kconfig"
547 #define KSYMS_SEC ".ksyms"
548 #define STRUCT_OPS_SEC ".struct_ops"
549 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
550 #define ARENA_SEC ".addr_space.1"
551 
552 enum libbpf_map_type {
553 	LIBBPF_MAP_UNSPEC,
554 	LIBBPF_MAP_DATA,
555 	LIBBPF_MAP_BSS,
556 	LIBBPF_MAP_RODATA,
557 	LIBBPF_MAP_KCONFIG,
558 };
559 
560 struct bpf_map_def {
561 	unsigned int type;
562 	unsigned int key_size;
563 	unsigned int value_size;
564 	unsigned int max_entries;
565 	unsigned int map_flags;
566 };
567 
568 struct bpf_map {
569 	struct bpf_object *obj;
570 	char *name;
571 	/* real_name is defined for special internal maps (.rodata*,
572 	 * .data*, .bss, .kconfig) and preserves their original ELF section
573 	 * name. This is important to be able to find corresponding BTF
574 	 * DATASEC information.
575 	 */
576 	char *real_name;
577 	int fd;
578 	int sec_idx;
579 	size_t sec_offset;
580 	int map_ifindex;
581 	int inner_map_fd;
582 	struct bpf_map_def def;
583 	__u32 numa_node;
584 	__u32 btf_var_idx;
585 	int mod_btf_fd;
586 	__u32 btf_key_type_id;
587 	__u32 btf_value_type_id;
588 	__u32 btf_vmlinux_value_type_id;
589 	enum libbpf_map_type libbpf_type;
590 	void *mmaped;
591 	struct bpf_struct_ops *st_ops;
592 	struct bpf_map *inner_map;
593 	void **init_slots;
594 	int init_slots_sz;
595 	char *pin_path;
596 	bool pinned;
597 	bool reused;
598 	bool autocreate;
599 	bool autoattach;
600 	__u64 map_extra;
601 	struct bpf_program *excl_prog;
602 };
603 
604 enum extern_type {
605 	EXT_UNKNOWN,
606 	EXT_KCFG,
607 	EXT_KSYM,
608 };
609 
610 enum kcfg_type {
611 	KCFG_UNKNOWN,
612 	KCFG_CHAR,
613 	KCFG_BOOL,
614 	KCFG_INT,
615 	KCFG_TRISTATE,
616 	KCFG_CHAR_ARR,
617 };
618 
619 struct extern_desc {
620 	enum extern_type type;
621 	int sym_idx;
622 	int btf_id;
623 	int sec_btf_id;
624 	char *name;
625 	char *essent_name;
626 	bool is_set;
627 	bool is_weak;
628 	union {
629 		struct {
630 			enum kcfg_type type;
631 			int sz;
632 			int align;
633 			int data_off;
634 			bool is_signed;
635 		} kcfg;
636 		struct {
637 			unsigned long long addr;
638 
639 			/* target btf_id of the corresponding kernel var. */
640 			int kernel_btf_obj_fd;
641 			int kernel_btf_id;
642 
643 			/* local btf_id of the ksym extern's type. */
644 			__u32 type_id;
645 			/* BTF fd index to be patched in for insn->off, this is
646 			 * 0 for vmlinux BTF, index in obj->fd_array for module
647 			 * BTF
648 			 */
649 			__s16 btf_fd_idx;
650 		} ksym;
651 	};
652 };
653 
654 struct module_btf {
655 	struct btf *btf;
656 	char *name;
657 	__u32 id;
658 	int fd;
659 	int fd_array_idx;
660 };
661 
662 enum sec_type {
663 	SEC_UNUSED = 0,
664 	SEC_RELO,
665 	SEC_BSS,
666 	SEC_DATA,
667 	SEC_RODATA,
668 	SEC_ST_OPS,
669 };
670 
671 struct elf_sec_desc {
672 	enum sec_type sec_type;
673 	Elf64_Shdr *shdr;
674 	Elf_Data *data;
675 };
676 
677 struct elf_state {
678 	int fd;
679 	const void *obj_buf;
680 	size_t obj_buf_sz;
681 	Elf *elf;
682 	Elf64_Ehdr *ehdr;
683 	Elf_Data *symbols;
684 	Elf_Data *arena_data;
685 	size_t shstrndx; /* section index for section name strings */
686 	size_t strtabidx;
687 	struct elf_sec_desc *secs;
688 	size_t sec_cnt;
689 	int btf_maps_shndx;
690 	__u32 btf_maps_sec_btf_id;
691 	int text_shndx;
692 	int symbols_shndx;
693 	bool has_st_ops;
694 	int arena_data_shndx;
695 	int jumptables_data_shndx;
696 };
697 
698 struct usdt_manager;
699 
700 enum bpf_object_state {
701 	OBJ_OPEN,
702 	OBJ_PREPARED,
703 	OBJ_LOADED,
704 };
705 
706 struct bpf_object {
707 	char name[BPF_OBJ_NAME_LEN];
708 	char license[64];
709 	__u32 kern_version;
710 
711 	enum bpf_object_state state;
712 	struct bpf_program *programs;
713 	size_t nr_programs;
714 	struct bpf_map *maps;
715 	size_t nr_maps;
716 	size_t maps_cap;
717 
718 	char *kconfig;
719 	struct extern_desc *externs;
720 	int nr_extern;
721 	int kconfig_map_idx;
722 
723 	bool has_subcalls;
724 	bool has_rodata;
725 
726 	struct bpf_gen *gen_loader;
727 
728 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
729 	struct elf_state efile;
730 
731 	unsigned char byteorder;
732 
733 	struct btf *btf;
734 	struct btf_ext *btf_ext;
735 
736 	/* Parse and load BTF vmlinux if any of the programs in the object need
737 	 * it at load time.
738 	 */
739 	struct btf *btf_vmlinux;
740 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
741 	 * override for vmlinux BTF.
742 	 */
743 	char *btf_custom_path;
744 	/* vmlinux BTF override for CO-RE relocations */
745 	struct btf *btf_vmlinux_override;
746 	/* Lazily initialized kernel module BTFs */
747 	struct module_btf *btf_modules;
748 	bool btf_modules_loaded;
749 	size_t btf_module_cnt;
750 	size_t btf_module_cap;
751 
752 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
753 	char *log_buf;
754 	size_t log_size;
755 	__u32 log_level;
756 
757 	int *fd_array;
758 	size_t fd_array_cap;
759 	size_t fd_array_cnt;
760 
761 	struct usdt_manager *usdt_man;
762 
763 	int arena_map_idx;
764 	void *arena_data;
765 	size_t arena_data_sz;
766 	size_t arena_data_off;
767 
768 	void *jumptables_data;
769 	size_t jumptables_data_sz;
770 
771 	struct {
772 		struct bpf_program *prog;
773 		unsigned int sym_off;
774 		int fd;
775 	} *jumptable_maps;
776 	size_t jumptable_map_cnt;
777 
778 	struct kern_feature_cache *feat_cache;
779 	char *token_path;
780 	int token_fd;
781 
782 	char path[];
783 };
784 
785 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
786 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
787 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
788 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
789 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
790 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
791 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
792 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
793 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
794 
795 void bpf_program__unload(struct bpf_program *prog)
796 {
797 	if (!prog)
798 		return;
799 
800 	zclose(prog->fd);
801 
802 	zfree(&prog->func_info);
803 	zfree(&prog->line_info);
804 	zfree(&prog->subprogs);
805 }
806 
807 static void bpf_program__exit(struct bpf_program *prog)
808 {
809 	if (!prog)
810 		return;
811 
812 	bpf_program__unload(prog);
813 	zfree(&prog->name);
814 	zfree(&prog->sec_name);
815 	zfree(&prog->insns);
816 	zfree(&prog->reloc_desc);
817 
818 	prog->nr_reloc = 0;
819 	prog->insns_cnt = 0;
820 	prog->sec_idx = -1;
821 }
822 
823 static bool insn_is_subprog_call(const struct bpf_insn *insn)
824 {
825 	return BPF_CLASS(insn->code) == BPF_JMP &&
826 	       BPF_OP(insn->code) == BPF_CALL &&
827 	       BPF_SRC(insn->code) == BPF_K &&
828 	       insn->src_reg == BPF_PSEUDO_CALL &&
829 	       insn->dst_reg == 0 &&
830 	       insn->off == 0;
831 }
832 
833 static bool is_call_insn(const struct bpf_insn *insn)
834 {
835 	return insn->code == (BPF_JMP | BPF_CALL);
836 }
837 
838 static bool insn_is_pseudo_func(struct bpf_insn *insn)
839 {
840 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
841 }
842 
843 static int
844 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
845 		      const char *name, size_t sec_idx, const char *sec_name,
846 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
847 {
848 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
849 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
850 			sec_name, name, sec_off, insn_data_sz);
851 		return -EINVAL;
852 	}
853 
854 	memset(prog, 0, sizeof(*prog));
855 	prog->obj = obj;
856 
857 	prog->sec_idx = sec_idx;
858 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
859 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
860 	/* insns_cnt can later be increased by appending used subprograms */
861 	prog->insns_cnt = prog->sec_insn_cnt;
862 
863 	prog->type = BPF_PROG_TYPE_UNSPEC;
864 	prog->fd = -1;
865 	prog->exception_cb_idx = -1;
866 
867 	/* libbpf's convention for SEC("?abc...") is that it's just like
868 	 * SEC("abc...") but the corresponding bpf_program starts out with
869 	 * autoload set to false.
870 	 */
871 	if (sec_name[0] == '?') {
872 		prog->autoload = false;
873 		/* from now on forget there was ? in section name */
874 		sec_name++;
875 	} else {
876 		prog->autoload = true;
877 	}
878 
879 	prog->autoattach = true;
880 
881 	/* inherit object's log_level */
882 	prog->log_level = obj->log_level;
883 
884 	prog->sec_name = strdup(sec_name);
885 	if (!prog->sec_name)
886 		goto errout;
887 
888 	prog->name = strdup(name);
889 	if (!prog->name)
890 		goto errout;
891 
892 	prog->insns = malloc(insn_data_sz);
893 	if (!prog->insns)
894 		goto errout;
895 	memcpy(prog->insns, insn_data, insn_data_sz);
896 
897 	return 0;
898 errout:
899 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
900 	bpf_program__exit(prog);
901 	return -ENOMEM;
902 }
903 
904 static int
905 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
906 			 const char *sec_name, int sec_idx)
907 {
908 	Elf_Data *symbols = obj->efile.symbols;
909 	struct bpf_program *prog, *progs;
910 	void *data = sec_data->d_buf;
911 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
912 	int nr_progs, err, i;
913 	const char *name;
914 	Elf64_Sym *sym;
915 
916 	progs = obj->programs;
917 	nr_progs = obj->nr_programs;
918 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
919 
920 	for (i = 0; i < nr_syms; i++) {
921 		sym = elf_sym_by_idx(obj, i);
922 
923 		if (sym->st_shndx != sec_idx)
924 			continue;
925 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
926 			continue;
927 
928 		prog_sz = sym->st_size;
929 		sec_off = sym->st_value;
930 
931 		name = elf_sym_str(obj, sym->st_name);
932 		if (!name) {
933 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
934 				sec_name, sec_off);
935 			return -LIBBPF_ERRNO__FORMAT;
936 		}
937 
938 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
939 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
940 				sec_name, sec_off);
941 			return -LIBBPF_ERRNO__FORMAT;
942 		}
943 
944 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
945 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
946 			return -ENOTSUP;
947 		}
948 
949 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
950 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
951 
952 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
953 		if (!progs) {
954 			/*
955 			 * In this case the original obj->programs
956 			 * is still valid, so don't need special treat for
957 			 * bpf_close_object().
958 			 */
959 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
960 				sec_name, name);
961 			return -ENOMEM;
962 		}
963 		obj->programs = progs;
964 
965 		prog = &progs[nr_progs];
966 
967 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
968 					    sec_off, data + sec_off, prog_sz);
969 		if (err)
970 			return err;
971 
972 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
973 			prog->sym_global = true;
974 
975 		/* if function is a global/weak symbol, but has restricted
976 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
977 		 * as static to enable more permissive BPF verification mode
978 		 * with more outside context available to BPF verifier
979 		 */
980 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
981 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
982 			prog->mark_btf_static = true;
983 
984 		nr_progs++;
985 		obj->nr_programs = nr_progs;
986 	}
987 
988 	return 0;
989 }
990 
991 static void bpf_object_bswap_progs(struct bpf_object *obj)
992 {
993 	struct bpf_program *prog = obj->programs;
994 	struct bpf_insn *insn;
995 	int p, i;
996 
997 	for (p = 0; p < obj->nr_programs; p++, prog++) {
998 		insn = prog->insns;
999 		for (i = 0; i < prog->insns_cnt; i++, insn++)
1000 			bpf_insn_bswap(insn);
1001 	}
1002 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
1003 }
1004 
1005 static const struct btf_member *
1006 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1007 {
1008 	struct btf_member *m;
1009 	int i;
1010 
1011 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1012 		if (btf_member_bit_offset(t, i) == bit_offset)
1013 			return m;
1014 	}
1015 
1016 	return NULL;
1017 }
1018 
1019 static const struct btf_member *
1020 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1021 		    const char *name)
1022 {
1023 	struct btf_member *m;
1024 	int i;
1025 
1026 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1027 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1028 			return m;
1029 	}
1030 
1031 	return NULL;
1032 }
1033 
1034 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1035 			    __u16 kind, struct btf **res_btf,
1036 			    struct module_btf **res_mod_btf);
1037 
1038 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1039 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1040 				   const char *name, __u32 kind);
1041 
1042 static int
1043 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1044 			   struct module_btf **mod_btf,
1045 			   const struct btf_type **type, __u32 *type_id,
1046 			   const struct btf_type **vtype, __u32 *vtype_id,
1047 			   const struct btf_member **data_member)
1048 {
1049 	const struct btf_type *kern_type, *kern_vtype;
1050 	const struct btf_member *kern_data_member;
1051 	struct btf *btf = NULL;
1052 	__s32 kern_vtype_id, kern_type_id;
1053 	char tname[192], stname[256];
1054 	__u32 i;
1055 
1056 	snprintf(tname, sizeof(tname), "%.*s",
1057 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1058 
1059 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1060 
1061 	/* Look for the corresponding "map_value" type that will be used
1062 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1063 	 * and the mod_btf.
1064 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1065 	 */
1066 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1067 	if (kern_vtype_id < 0) {
1068 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1069 		return kern_vtype_id;
1070 	}
1071 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1072 
1073 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1074 	if (kern_type_id < 0) {
1075 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1076 		return kern_type_id;
1077 	}
1078 	kern_type = btf__type_by_id(btf, kern_type_id);
1079 
1080 	/* Find "struct tcp_congestion_ops" from
1081 	 * struct bpf_struct_ops_tcp_congestion_ops {
1082 	 *	[ ... ]
1083 	 *	struct tcp_congestion_ops data;
1084 	 * }
1085 	 */
1086 	kern_data_member = btf_members(kern_vtype);
1087 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1088 		if (kern_data_member->type == kern_type_id)
1089 			break;
1090 	}
1091 	if (i == btf_vlen(kern_vtype)) {
1092 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1093 			tname, stname);
1094 		return -EINVAL;
1095 	}
1096 
1097 	*type = kern_type;
1098 	*type_id = kern_type_id;
1099 	*vtype = kern_vtype;
1100 	*vtype_id = kern_vtype_id;
1101 	*data_member = kern_data_member;
1102 
1103 	return 0;
1104 }
1105 
1106 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1107 {
1108 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1109 }
1110 
1111 static bool is_valid_st_ops_program(struct bpf_object *obj,
1112 				    const struct bpf_program *prog)
1113 {
1114 	int i;
1115 
1116 	for (i = 0; i < obj->nr_programs; i++) {
1117 		if (&obj->programs[i] == prog)
1118 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1119 	}
1120 
1121 	return false;
1122 }
1123 
1124 /* For each struct_ops program P, referenced from some struct_ops map M,
1125  * enable P.autoload if there are Ms for which M.autocreate is true,
1126  * disable P.autoload if for all Ms M.autocreate is false.
1127  * Don't change P.autoload for programs that are not referenced from any maps.
1128  */
1129 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1130 {
1131 	struct bpf_program *prog, *slot_prog;
1132 	struct bpf_map *map;
1133 	int i, j, k, vlen;
1134 
1135 	for (i = 0; i < obj->nr_programs; ++i) {
1136 		int should_load = false;
1137 		int use_cnt = 0;
1138 
1139 		prog = &obj->programs[i];
1140 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1141 			continue;
1142 
1143 		for (j = 0; j < obj->nr_maps; ++j) {
1144 			const struct btf_type *type;
1145 
1146 			map = &obj->maps[j];
1147 			if (!bpf_map__is_struct_ops(map))
1148 				continue;
1149 
1150 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1151 			vlen = btf_vlen(type);
1152 			for (k = 0; k < vlen; ++k) {
1153 				slot_prog = map->st_ops->progs[k];
1154 				if (prog != slot_prog)
1155 					continue;
1156 
1157 				use_cnt++;
1158 				if (map->autocreate)
1159 					should_load = true;
1160 			}
1161 		}
1162 		if (use_cnt)
1163 			prog->autoload = should_load;
1164 	}
1165 
1166 	return 0;
1167 }
1168 
1169 /* Init the map's fields that depend on kern_btf */
1170 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1171 {
1172 	const struct btf_member *member, *kern_member, *kern_data_member;
1173 	const struct btf_type *type, *kern_type, *kern_vtype;
1174 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1175 	struct bpf_object *obj = map->obj;
1176 	const struct btf *btf = obj->btf;
1177 	struct bpf_struct_ops *st_ops;
1178 	const struct btf *kern_btf;
1179 	struct module_btf *mod_btf = NULL;
1180 	void *data, *kern_data;
1181 	const char *tname;
1182 	int err;
1183 
1184 	st_ops = map->st_ops;
1185 	type = btf__type_by_id(btf, st_ops->type_id);
1186 	tname = btf__name_by_offset(btf, type->name_off);
1187 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1188 					 &kern_type, &kern_type_id,
1189 					 &kern_vtype, &kern_vtype_id,
1190 					 &kern_data_member);
1191 	if (err)
1192 		return err;
1193 
1194 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1195 
1196 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1197 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1198 
1199 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1200 	map->def.value_size = kern_vtype->size;
1201 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1202 
1203 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1204 	if (!st_ops->kern_vdata)
1205 		return -ENOMEM;
1206 
1207 	data = st_ops->data;
1208 	kern_data_off = kern_data_member->offset / 8;
1209 	kern_data = st_ops->kern_vdata + kern_data_off;
1210 
1211 	member = btf_members(type);
1212 	for (i = 0; i < btf_vlen(type); i++, member++) {
1213 		const struct btf_type *mtype, *kern_mtype;
1214 		__u32 mtype_id, kern_mtype_id;
1215 		void *mdata, *kern_mdata;
1216 		struct bpf_program *prog;
1217 		__s64 msize, kern_msize;
1218 		__u32 moff, kern_moff;
1219 		__u32 kern_member_idx;
1220 		const char *mname;
1221 
1222 		mname = btf__name_by_offset(btf, member->name_off);
1223 		moff = member->offset / 8;
1224 		mdata = data + moff;
1225 		msize = btf__resolve_size(btf, member->type);
1226 		if (msize < 0) {
1227 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1228 				map->name, mname);
1229 			return msize;
1230 		}
1231 
1232 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1233 		if (!kern_member) {
1234 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1235 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1236 					map->name, mname);
1237 				return -ENOTSUP;
1238 			}
1239 
1240 			if (st_ops->progs[i]) {
1241 				/* If we had declaratively set struct_ops callback, we need to
1242 				 * force its autoload to false, because it doesn't have
1243 				 * a chance of succeeding from POV of the current struct_ops map.
1244 				 * If this program is still referenced somewhere else, though,
1245 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1246 				 * autoload accordingly.
1247 				 */
1248 				st_ops->progs[i]->autoload = false;
1249 				st_ops->progs[i] = NULL;
1250 			}
1251 
1252 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1253 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1254 				map->name, mname);
1255 			continue;
1256 		}
1257 
1258 		kern_member_idx = kern_member - btf_members(kern_type);
1259 		if (btf_member_bitfield_size(type, i) ||
1260 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1261 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1262 				map->name, mname);
1263 			return -ENOTSUP;
1264 		}
1265 
1266 		kern_moff = kern_member->offset / 8;
1267 		kern_mdata = kern_data + kern_moff;
1268 
1269 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1270 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1271 						    &kern_mtype_id);
1272 		if (BTF_INFO_KIND(mtype->info) !=
1273 		    BTF_INFO_KIND(kern_mtype->info)) {
1274 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1275 				map->name, mname, BTF_INFO_KIND(mtype->info),
1276 				BTF_INFO_KIND(kern_mtype->info));
1277 			return -ENOTSUP;
1278 		}
1279 
1280 		if (btf_is_ptr(mtype)) {
1281 			prog = *(void **)mdata;
1282 			/* just like for !kern_member case above, reset declaratively
1283 			 * set (at compile time) program's autload to false,
1284 			 * if user replaced it with another program or NULL
1285 			 */
1286 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1287 				st_ops->progs[i]->autoload = false;
1288 
1289 			/* Update the value from the shadow type */
1290 			st_ops->progs[i] = prog;
1291 			if (!prog)
1292 				continue;
1293 
1294 			if (!is_valid_st_ops_program(obj, prog)) {
1295 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1296 					map->name, mname);
1297 				return -ENOTSUP;
1298 			}
1299 
1300 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1301 							    kern_mtype->type,
1302 							    &kern_mtype_id);
1303 
1304 			/* mtype->type must be a func_proto which was
1305 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1306 			 * so only check kern_mtype for func_proto here.
1307 			 */
1308 			if (!btf_is_func_proto(kern_mtype)) {
1309 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1310 					map->name, mname);
1311 				return -ENOTSUP;
1312 			}
1313 
1314 			if (mod_btf)
1315 				prog->attach_btf_obj_fd = mod_btf->fd;
1316 
1317 			/* if we haven't yet processed this BPF program, record proper
1318 			 * attach_btf_id and member_idx
1319 			 */
1320 			if (!prog->attach_btf_id) {
1321 				prog->attach_btf_id = kern_type_id;
1322 				prog->expected_attach_type = kern_member_idx;
1323 			}
1324 
1325 			/* struct_ops BPF prog can be re-used between multiple
1326 			 * .struct_ops & .struct_ops.link as long as it's the
1327 			 * same struct_ops struct definition and the same
1328 			 * function pointer field
1329 			 */
1330 			if (prog->attach_btf_id != kern_type_id) {
1331 				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",
1332 					map->name, mname, prog->name, prog->sec_name, prog->type,
1333 					prog->attach_btf_id, kern_type_id);
1334 				return -EINVAL;
1335 			}
1336 			if (prog->expected_attach_type != kern_member_idx) {
1337 				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",
1338 					map->name, mname, prog->name, prog->sec_name, prog->type,
1339 					prog->expected_attach_type, kern_member_idx);
1340 				return -EINVAL;
1341 			}
1342 
1343 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1344 
1345 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1346 				 map->name, mname, prog->name, moff,
1347 				 kern_moff);
1348 
1349 			continue;
1350 		}
1351 
1352 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1353 		if (kern_msize < 0 || msize != kern_msize) {
1354 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1355 				map->name, mname, (ssize_t)msize,
1356 				(ssize_t)kern_msize);
1357 			return -ENOTSUP;
1358 		}
1359 
1360 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1361 			 map->name, mname, (unsigned int)msize,
1362 			 moff, kern_moff);
1363 		memcpy(kern_mdata, mdata, msize);
1364 	}
1365 
1366 	return 0;
1367 }
1368 
1369 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1370 {
1371 	struct bpf_map *map;
1372 	size_t i;
1373 	int err;
1374 
1375 	for (i = 0; i < obj->nr_maps; i++) {
1376 		map = &obj->maps[i];
1377 
1378 		if (!bpf_map__is_struct_ops(map))
1379 			continue;
1380 
1381 		if (!map->autocreate)
1382 			continue;
1383 
1384 		err = bpf_map__init_kern_struct_ops(map);
1385 		if (err)
1386 			return err;
1387 	}
1388 
1389 	return 0;
1390 }
1391 
1392 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1393 				int shndx, Elf_Data *data)
1394 {
1395 	const struct btf_type *type, *datasec;
1396 	const struct btf_var_secinfo *vsi;
1397 	struct bpf_struct_ops *st_ops;
1398 	const char *tname, *var_name;
1399 	__s32 type_id, datasec_id;
1400 	const struct btf *btf;
1401 	struct bpf_map *map;
1402 	__u32 i;
1403 
1404 	if (shndx == -1)
1405 		return 0;
1406 
1407 	btf = obj->btf;
1408 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1409 					    BTF_KIND_DATASEC);
1410 	if (datasec_id < 0) {
1411 		pr_warn("struct_ops init: DATASEC %s not found\n",
1412 			sec_name);
1413 		return -EINVAL;
1414 	}
1415 
1416 	datasec = btf__type_by_id(btf, datasec_id);
1417 	vsi = btf_var_secinfos(datasec);
1418 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1419 		type = btf__type_by_id(obj->btf, vsi->type);
1420 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1421 
1422 		type_id = btf__resolve_type(obj->btf, vsi->type);
1423 		if (type_id < 0) {
1424 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1425 				vsi->type, sec_name);
1426 			return -EINVAL;
1427 		}
1428 
1429 		type = btf__type_by_id(obj->btf, type_id);
1430 		tname = btf__name_by_offset(obj->btf, type->name_off);
1431 		if (!tname[0]) {
1432 			pr_warn("struct_ops init: anonymous type is not supported\n");
1433 			return -ENOTSUP;
1434 		}
1435 		if (!btf_is_struct(type)) {
1436 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1437 			return -EINVAL;
1438 		}
1439 
1440 		map = bpf_object__add_map(obj);
1441 		if (IS_ERR(map))
1442 			return PTR_ERR(map);
1443 
1444 		map->sec_idx = shndx;
1445 		map->sec_offset = vsi->offset;
1446 		map->name = strdup(var_name);
1447 		if (!map->name)
1448 			return -ENOMEM;
1449 		map->btf_value_type_id = type_id;
1450 
1451 		/* Follow same convention as for programs autoload:
1452 		 * SEC("?.struct_ops") means map is not created by default.
1453 		 */
1454 		if (sec_name[0] == '?') {
1455 			map->autocreate = false;
1456 			/* from now on forget there was ? in section name */
1457 			sec_name++;
1458 		}
1459 
1460 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1461 		map->def.key_size = sizeof(int);
1462 		map->def.value_size = type->size;
1463 		map->def.max_entries = 1;
1464 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1465 		map->autoattach = true;
1466 
1467 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1468 		if (!map->st_ops)
1469 			return -ENOMEM;
1470 		st_ops = map->st_ops;
1471 		st_ops->data = malloc(type->size);
1472 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1473 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1474 					       sizeof(*st_ops->kern_func_off));
1475 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1476 			return -ENOMEM;
1477 
1478 		if (vsi->offset + type->size > data->d_size) {
1479 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1480 				var_name, sec_name);
1481 			return -EINVAL;
1482 		}
1483 
1484 		memcpy(st_ops->data,
1485 		       data->d_buf + vsi->offset,
1486 		       type->size);
1487 		st_ops->type_id = type_id;
1488 
1489 		pr_debug("struct_ops init: struct %s(type_id=%d) %s found at offset %u\n",
1490 			 tname, type_id, var_name, vsi->offset);
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1497 {
1498 	const char *sec_name;
1499 	int sec_idx, err;
1500 
1501 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1502 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1503 
1504 		if (desc->sec_type != SEC_ST_OPS)
1505 			continue;
1506 
1507 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1508 		if (!sec_name)
1509 			return -LIBBPF_ERRNO__FORMAT;
1510 
1511 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1512 		if (err)
1513 			return err;
1514 	}
1515 
1516 	return 0;
1517 }
1518 
1519 static struct bpf_object *bpf_object__new(const char *path,
1520 					  const void *obj_buf,
1521 					  size_t obj_buf_sz,
1522 					  const char *obj_name)
1523 {
1524 	struct bpf_object *obj;
1525 	char *end;
1526 
1527 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1528 	if (!obj) {
1529 		pr_warn("alloc memory failed for %s\n", path);
1530 		return ERR_PTR(-ENOMEM);
1531 	}
1532 
1533 	strcpy(obj->path, path);
1534 	if (obj_name) {
1535 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1536 	} else {
1537 		/* Using basename() GNU version which doesn't modify arg. */
1538 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1539 		end = strchr(obj->name, '.');
1540 		if (end)
1541 			*end = 0;
1542 	}
1543 
1544 	obj->efile.fd = -1;
1545 	/*
1546 	 * Caller of this function should also call
1547 	 * bpf_object__elf_finish() after data collection to return
1548 	 * obj_buf to user. If not, we should duplicate the buffer to
1549 	 * avoid user freeing them before elf finish.
1550 	 */
1551 	obj->efile.obj_buf = obj_buf;
1552 	obj->efile.obj_buf_sz = obj_buf_sz;
1553 	obj->efile.btf_maps_shndx = -1;
1554 	obj->kconfig_map_idx = -1;
1555 	obj->arena_map_idx = -1;
1556 
1557 	obj->kern_version = get_kernel_version();
1558 	obj->state  = OBJ_OPEN;
1559 
1560 	return obj;
1561 }
1562 
1563 static void bpf_object__elf_finish(struct bpf_object *obj)
1564 {
1565 	if (!obj->efile.elf)
1566 		return;
1567 
1568 	elf_end(obj->efile.elf);
1569 	obj->efile.elf = NULL;
1570 	obj->efile.ehdr = NULL;
1571 	obj->efile.symbols = NULL;
1572 	obj->efile.arena_data = NULL;
1573 
1574 	zfree(&obj->efile.secs);
1575 	obj->efile.sec_cnt = 0;
1576 	zclose(obj->efile.fd);
1577 	obj->efile.obj_buf = NULL;
1578 	obj->efile.obj_buf_sz = 0;
1579 }
1580 
1581 static int bpf_object__elf_init(struct bpf_object *obj)
1582 {
1583 	Elf64_Ehdr *ehdr;
1584 	int err = 0;
1585 	Elf *elf;
1586 
1587 	if (obj->efile.elf) {
1588 		pr_warn("elf: init internal error\n");
1589 		return -LIBBPF_ERRNO__LIBELF;
1590 	}
1591 
1592 	if (obj->efile.obj_buf_sz > 0) {
1593 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1594 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1595 	} else {
1596 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1597 		if (obj->efile.fd < 0) {
1598 			err = -errno;
1599 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1600 			return err;
1601 		}
1602 
1603 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1604 	}
1605 
1606 	if (!elf) {
1607 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1608 		err = -LIBBPF_ERRNO__LIBELF;
1609 		goto errout;
1610 	}
1611 
1612 	obj->efile.elf = elf;
1613 
1614 	if (elf_kind(elf) != ELF_K_ELF) {
1615 		err = -LIBBPF_ERRNO__FORMAT;
1616 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1617 		goto errout;
1618 	}
1619 
1620 	if (gelf_getclass(elf) != ELFCLASS64) {
1621 		err = -LIBBPF_ERRNO__FORMAT;
1622 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1623 		goto errout;
1624 	}
1625 
1626 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1627 	if (!obj->efile.ehdr) {
1628 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1629 		err = -LIBBPF_ERRNO__FORMAT;
1630 		goto errout;
1631 	}
1632 
1633 	/* Validate ELF object endianness... */
1634 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1635 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1636 		err = -LIBBPF_ERRNO__ENDIAN;
1637 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1638 		goto errout;
1639 	}
1640 	/* and save after bpf_object_open() frees ELF data */
1641 	obj->byteorder = ehdr->e_ident[EI_DATA];
1642 
1643 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1644 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1645 			obj->path, elf_errmsg(-1));
1646 		err = -LIBBPF_ERRNO__FORMAT;
1647 		goto errout;
1648 	}
1649 
1650 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1651 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1652 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1653 			obj->path, elf_errmsg(-1));
1654 		err = -LIBBPF_ERRNO__FORMAT;
1655 		goto errout;
1656 	}
1657 
1658 	/* Old LLVM set e_machine to EM_NONE */
1659 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1660 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1661 		err = -LIBBPF_ERRNO__FORMAT;
1662 		goto errout;
1663 	}
1664 
1665 	return 0;
1666 errout:
1667 	bpf_object__elf_finish(obj);
1668 	return err;
1669 }
1670 
1671 static bool is_native_endianness(struct bpf_object *obj)
1672 {
1673 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1674 	return obj->byteorder == ELFDATA2LSB;
1675 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1676 	return obj->byteorder == ELFDATA2MSB;
1677 #else
1678 # error "Unrecognized __BYTE_ORDER__"
1679 #endif
1680 }
1681 
1682 static int
1683 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1684 {
1685 	if (!data) {
1686 		pr_warn("invalid license section in %s\n", obj->path);
1687 		return -LIBBPF_ERRNO__FORMAT;
1688 	}
1689 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1690 	 * go over allowed ELF data section buffer
1691 	 */
1692 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1693 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1694 	return 0;
1695 }
1696 
1697 static int
1698 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1699 {
1700 	__u32 kver;
1701 
1702 	if (!data || size != sizeof(kver)) {
1703 		pr_warn("invalid kver section in %s\n", obj->path);
1704 		return -LIBBPF_ERRNO__FORMAT;
1705 	}
1706 	memcpy(&kver, data, sizeof(kver));
1707 	obj->kern_version = kver;
1708 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1709 	return 0;
1710 }
1711 
1712 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1713 {
1714 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1715 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1716 		return true;
1717 	return false;
1718 }
1719 
1720 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1721 {
1722 	Elf_Data *data;
1723 	Elf_Scn *scn;
1724 
1725 	if (!name)
1726 		return -EINVAL;
1727 
1728 	scn = elf_sec_by_name(obj, name);
1729 	data = elf_sec_data(obj, scn);
1730 	if (data) {
1731 		*size = data->d_size;
1732 		return 0; /* found it */
1733 	}
1734 
1735 	return -ENOENT;
1736 }
1737 
1738 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1739 {
1740 	Elf_Data *symbols = obj->efile.symbols;
1741 	const char *sname;
1742 	size_t si;
1743 
1744 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1745 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1746 
1747 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1748 			continue;
1749 
1750 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1751 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1752 			continue;
1753 
1754 		sname = elf_sym_str(obj, sym->st_name);
1755 		if (!sname) {
1756 			pr_warn("failed to get sym name string for var %s\n", name);
1757 			return ERR_PTR(-EIO);
1758 		}
1759 		if (strcmp(name, sname) == 0)
1760 			return sym;
1761 	}
1762 
1763 	return ERR_PTR(-ENOENT);
1764 }
1765 
1766 #ifndef MFD_CLOEXEC
1767 #define MFD_CLOEXEC 0x0001U
1768 #endif
1769 #ifndef MFD_NOEXEC_SEAL
1770 #define MFD_NOEXEC_SEAL 0x0008U
1771 #endif
1772 
1773 static int create_placeholder_fd(void)
1774 {
1775 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1776 	const char *name = "libbpf-placeholder-fd";
1777 	int fd;
1778 
1779 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1780 	if (fd >= 0)
1781 		return fd;
1782 	else if (errno != EINVAL)
1783 		return -errno;
1784 
1785 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1786 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1787 	if (fd < 0)
1788 		return -errno;
1789 	return fd;
1790 }
1791 
1792 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1793 {
1794 	struct bpf_map *map;
1795 	int err;
1796 
1797 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1798 				sizeof(*obj->maps), obj->nr_maps + 1);
1799 	if (err)
1800 		return ERR_PTR(err);
1801 
1802 	map = &obj->maps[obj->nr_maps++];
1803 	map->obj = obj;
1804 	/* Preallocate map FD without actually creating BPF map just yet.
1805 	 * These map FD "placeholders" will be reused later without changing
1806 	 * FD value when map is actually created in the kernel.
1807 	 *
1808 	 * This is useful to be able to perform BPF program relocations
1809 	 * without having to create BPF maps before that step. This allows us
1810 	 * to finalize and load BTF very late in BPF object's loading phase,
1811 	 * right before BPF maps have to be created and BPF programs have to
1812 	 * be loaded. By having these map FD placeholders we can perform all
1813 	 * the sanitizations, relocations, and any other adjustments before we
1814 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1815 	 */
1816 	map->fd = create_placeholder_fd();
1817 	if (map->fd < 0)
1818 		return ERR_PTR(map->fd);
1819 	map->inner_map_fd = -1;
1820 	map->autocreate = true;
1821 
1822 	return map;
1823 }
1824 
1825 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1826 {
1827 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1828 	size_t map_sz;
1829 
1830 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1831 	map_sz = roundup(map_sz, page_sz);
1832 	return map_sz;
1833 }
1834 
1835 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1836 {
1837 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1838 
1839 	switch (map->def.type) {
1840 	case BPF_MAP_TYPE_ARRAY:
1841 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1842 	case BPF_MAP_TYPE_ARENA:
1843 		return page_sz * map->def.max_entries;
1844 	default:
1845 		return 0; /* not supported */
1846 	}
1847 }
1848 
1849 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1850 {
1851 	void *mmaped;
1852 
1853 	if (!map->mmaped)
1854 		return -EINVAL;
1855 
1856 	if (old_sz == new_sz)
1857 		return 0;
1858 
1859 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1860 	if (mmaped == MAP_FAILED)
1861 		return -errno;
1862 
1863 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1864 	munmap(map->mmaped, old_sz);
1865 	map->mmaped = mmaped;
1866 	return 0;
1867 }
1868 
1869 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1870 {
1871 	char map_name[BPF_OBJ_NAME_LEN], *p;
1872 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1873 
1874 	/* This is one of the more confusing parts of libbpf for various
1875 	 * reasons, some of which are historical. The original idea for naming
1876 	 * internal names was to include as much of BPF object name prefix as
1877 	 * possible, so that it can be distinguished from similar internal
1878 	 * maps of a different BPF object.
1879 	 * As an example, let's say we have bpf_object named 'my_object_name'
1880 	 * and internal map corresponding to '.rodata' ELF section. The final
1881 	 * map name advertised to user and to the kernel will be
1882 	 * 'my_objec.rodata', taking first 8 characters of object name and
1883 	 * entire 7 characters of '.rodata'.
1884 	 * Somewhat confusingly, if internal map ELF section name is shorter
1885 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1886 	 * for the suffix, even though we only have 4 actual characters, and
1887 	 * resulting map will be called 'my_objec.bss', not even using all 15
1888 	 * characters allowed by the kernel. Oh well, at least the truncated
1889 	 * object name is somewhat consistent in this case. But if the map
1890 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1891 	 * (8 chars) and thus will be left with only first 7 characters of the
1892 	 * object name ('my_obje'). Happy guessing, user, that the final map
1893 	 * name will be "my_obje.kconfig".
1894 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1895 	 * and .data.* data sections, it's possible that ELF section name is
1896 	 * longer than allowed 15 chars, so we now need to be careful to take
1897 	 * only up to 15 first characters of ELF name, taking no BPF object
1898 	 * name characters at all. So '.rodata.abracadabra' will result in
1899 	 * '.rodata.abracad' kernel and user-visible name.
1900 	 * We need to keep this convoluted logic intact for .data, .bss and
1901 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1902 	 * maps we use their ELF names as is, not prepending bpf_object name
1903 	 * in front. We still need to truncate them to 15 characters for the
1904 	 * kernel. Full name can be recovered for such maps by using DATASEC
1905 	 * BTF type associated with such map's value type, though.
1906 	 */
1907 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1908 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1909 
1910 	/* if there are two or more dots in map name, it's a custom dot map */
1911 	if (strchr(real_name + 1, '.') != NULL)
1912 		pfx_len = 0;
1913 	else
1914 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1915 
1916 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1917 		 sfx_len, real_name);
1918 
1919 	/* sanities map name to characters allowed by kernel */
1920 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1921 		if (!isalnum(*p) && *p != '_' && *p != '.')
1922 			*p = '_';
1923 
1924 	return strdup(map_name);
1925 }
1926 
1927 static int
1928 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1929 
1930 /* Internal BPF map is mmap()'able only if at least one of corresponding
1931  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1932  * variable and it's not marked as __hidden (which turns it into, effectively,
1933  * a STATIC variable).
1934  */
1935 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1936 {
1937 	const struct btf_type *t, *vt;
1938 	struct btf_var_secinfo *vsi;
1939 	int i, n;
1940 
1941 	if (!map->btf_value_type_id)
1942 		return false;
1943 
1944 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1945 	if (!btf_is_datasec(t))
1946 		return false;
1947 
1948 	vsi = btf_var_secinfos(t);
1949 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1950 		vt = btf__type_by_id(obj->btf, vsi->type);
1951 		if (!btf_is_var(vt))
1952 			continue;
1953 
1954 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1955 			return true;
1956 	}
1957 
1958 	return false;
1959 }
1960 
1961 static int
1962 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1963 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1964 {
1965 	struct bpf_map_def *def;
1966 	struct bpf_map *map;
1967 	size_t mmap_sz;
1968 	int err;
1969 
1970 	map = bpf_object__add_map(obj);
1971 	if (IS_ERR(map))
1972 		return PTR_ERR(map);
1973 
1974 	map->libbpf_type = type;
1975 	map->sec_idx = sec_idx;
1976 	map->sec_offset = 0;
1977 	map->real_name = strdup(real_name);
1978 	map->name = internal_map_name(obj, real_name);
1979 	if (!map->real_name || !map->name) {
1980 		zfree(&map->real_name);
1981 		zfree(&map->name);
1982 		return -ENOMEM;
1983 	}
1984 
1985 	def = &map->def;
1986 	def->type = BPF_MAP_TYPE_ARRAY;
1987 	def->key_size = sizeof(int);
1988 	def->value_size = data_sz;
1989 	def->max_entries = 1;
1990 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1991 		? BPF_F_RDONLY_PROG : 0;
1992 
1993 	/* failures are fine because of maps like .rodata.str1.1 */
1994 	(void) map_fill_btf_type_info(obj, map);
1995 
1996 	if (map_is_mmapable(obj, map))
1997 		def->map_flags |= BPF_F_MMAPABLE;
1998 
1999 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
2000 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
2001 
2002 	mmap_sz = bpf_map_mmap_sz(map);
2003 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2004 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2005 	if (map->mmaped == MAP_FAILED) {
2006 		err = -errno;
2007 		map->mmaped = NULL;
2008 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2009 		zfree(&map->real_name);
2010 		zfree(&map->name);
2011 		return err;
2012 	}
2013 
2014 	if (data)
2015 		memcpy(map->mmaped, data, data_sz);
2016 
2017 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2018 	return 0;
2019 }
2020 
2021 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2022 {
2023 	struct elf_sec_desc *sec_desc;
2024 	const char *sec_name;
2025 	int err = 0, sec_idx;
2026 
2027 	/*
2028 	 * Populate obj->maps with libbpf internal maps.
2029 	 */
2030 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2031 		sec_desc = &obj->efile.secs[sec_idx];
2032 
2033 		/* Skip recognized sections with size 0. */
2034 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2035 			continue;
2036 
2037 		switch (sec_desc->sec_type) {
2038 		case SEC_DATA:
2039 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2040 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2041 							    sec_name, sec_idx,
2042 							    sec_desc->data->d_buf,
2043 							    sec_desc->data->d_size);
2044 			break;
2045 		case SEC_RODATA:
2046 			obj->has_rodata = true;
2047 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2048 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2049 							    sec_name, sec_idx,
2050 							    sec_desc->data->d_buf,
2051 							    sec_desc->data->d_size);
2052 			break;
2053 		case SEC_BSS:
2054 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2055 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2056 							    sec_name, sec_idx,
2057 							    NULL,
2058 							    sec_desc->data->d_size);
2059 			break;
2060 		default:
2061 			/* skip */
2062 			break;
2063 		}
2064 		if (err)
2065 			return err;
2066 	}
2067 	return 0;
2068 }
2069 
2070 
2071 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2072 					       const void *name)
2073 {
2074 	int i;
2075 
2076 	for (i = 0; i < obj->nr_extern; i++) {
2077 		if (strcmp(obj->externs[i].name, name) == 0)
2078 			return &obj->externs[i];
2079 	}
2080 	return NULL;
2081 }
2082 
2083 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2084 							const void *name, int len)
2085 {
2086 	const char *ext_name;
2087 	int i;
2088 
2089 	for (i = 0; i < obj->nr_extern; i++) {
2090 		ext_name = obj->externs[i].name;
2091 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2092 			return &obj->externs[i];
2093 	}
2094 	return NULL;
2095 }
2096 
2097 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2098 			      char value)
2099 {
2100 	switch (ext->kcfg.type) {
2101 	case KCFG_BOOL:
2102 		if (value == 'm') {
2103 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2104 				ext->name, value);
2105 			return -EINVAL;
2106 		}
2107 		*(bool *)ext_val = value == 'y' ? true : false;
2108 		break;
2109 	case KCFG_TRISTATE:
2110 		if (value == 'y')
2111 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2112 		else if (value == 'm')
2113 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2114 		else /* value == 'n' */
2115 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2116 		break;
2117 	case KCFG_CHAR:
2118 		*(char *)ext_val = value;
2119 		break;
2120 	case KCFG_UNKNOWN:
2121 	case KCFG_INT:
2122 	case KCFG_CHAR_ARR:
2123 	default:
2124 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2125 			ext->name, value);
2126 		return -EINVAL;
2127 	}
2128 	ext->is_set = true;
2129 	return 0;
2130 }
2131 
2132 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2133 			      const char *value)
2134 {
2135 	size_t len;
2136 
2137 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2138 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2139 			ext->name, value);
2140 		return -EINVAL;
2141 	}
2142 
2143 	len = strlen(value);
2144 	if (len < 2 || value[len - 1] != '"') {
2145 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2146 			ext->name, value);
2147 		return -EINVAL;
2148 	}
2149 
2150 	/* strip quotes */
2151 	len -= 2;
2152 	if (len >= ext->kcfg.sz) {
2153 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2154 			ext->name, value, len, ext->kcfg.sz - 1);
2155 		len = ext->kcfg.sz - 1;
2156 	}
2157 	memcpy(ext_val, value + 1, len);
2158 	ext_val[len] = '\0';
2159 	ext->is_set = true;
2160 	return 0;
2161 }
2162 
2163 static int parse_u64(const char *value, __u64 *res)
2164 {
2165 	char *value_end;
2166 	int err;
2167 
2168 	errno = 0;
2169 	*res = strtoull(value, &value_end, 0);
2170 	if (errno) {
2171 		err = -errno;
2172 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2173 		return err;
2174 	}
2175 	if (*value_end) {
2176 		pr_warn("failed to parse '%s' as integer completely\n", value);
2177 		return -EINVAL;
2178 	}
2179 	return 0;
2180 }
2181 
2182 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2183 {
2184 	int bit_sz = ext->kcfg.sz * 8;
2185 
2186 	if (ext->kcfg.sz == 8)
2187 		return true;
2188 
2189 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2190 	 * bytes size without any loss of information. If the target integer
2191 	 * is signed, we rely on the following limits of integer type of
2192 	 * Y bits and subsequent transformation:
2193 	 *
2194 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2195 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2196 	 *            0 <= X + 2^(Y-1) <  2^Y
2197 	 *
2198 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2199 	 *  zero.
2200 	 */
2201 	if (ext->kcfg.is_signed)
2202 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2203 	else
2204 		return (v >> bit_sz) == 0;
2205 }
2206 
2207 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2208 			      __u64 value)
2209 {
2210 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2211 	    ext->kcfg.type != KCFG_BOOL) {
2212 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2213 			ext->name, (unsigned long long)value);
2214 		return -EINVAL;
2215 	}
2216 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2217 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2218 			ext->name, (unsigned long long)value);
2219 		return -EINVAL;
2220 
2221 	}
2222 	if (!is_kcfg_value_in_range(ext, value)) {
2223 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2224 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2225 		return -ERANGE;
2226 	}
2227 	switch (ext->kcfg.sz) {
2228 	case 1:
2229 		*(__u8 *)ext_val = value;
2230 		break;
2231 	case 2:
2232 		*(__u16 *)ext_val = value;
2233 		break;
2234 	case 4:
2235 		*(__u32 *)ext_val = value;
2236 		break;
2237 	case 8:
2238 		*(__u64 *)ext_val = value;
2239 		break;
2240 	default:
2241 		return -EINVAL;
2242 	}
2243 	ext->is_set = true;
2244 	return 0;
2245 }
2246 
2247 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2248 					    char *buf, void *data)
2249 {
2250 	struct extern_desc *ext;
2251 	char *sep, *value;
2252 	int len, err = 0;
2253 	void *ext_val;
2254 	__u64 num;
2255 
2256 	if (!str_has_pfx(buf, "CONFIG_"))
2257 		return 0;
2258 
2259 	sep = strchr(buf, '=');
2260 	if (!sep) {
2261 		pr_warn("failed to parse '%s': no separator\n", buf);
2262 		return -EINVAL;
2263 	}
2264 
2265 	/* Trim ending '\n' */
2266 	len = strlen(buf);
2267 	if (buf[len - 1] == '\n')
2268 		buf[len - 1] = '\0';
2269 	/* Split on '=' and ensure that a value is present. */
2270 	*sep = '\0';
2271 	if (!sep[1]) {
2272 		*sep = '=';
2273 		pr_warn("failed to parse '%s': no value\n", buf);
2274 		return -EINVAL;
2275 	}
2276 
2277 	ext = find_extern_by_name(obj, buf);
2278 	if (!ext || ext->is_set)
2279 		return 0;
2280 
2281 	ext_val = data + ext->kcfg.data_off;
2282 	value = sep + 1;
2283 
2284 	switch (*value) {
2285 	case 'y': case 'n': case 'm':
2286 		err = set_kcfg_value_tri(ext, ext_val, *value);
2287 		break;
2288 	case '"':
2289 		err = set_kcfg_value_str(ext, ext_val, value);
2290 		break;
2291 	default:
2292 		/* assume integer */
2293 		err = parse_u64(value, &num);
2294 		if (err) {
2295 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2296 			return err;
2297 		}
2298 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2299 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2300 			return -EINVAL;
2301 		}
2302 		err = set_kcfg_value_num(ext, ext_val, num);
2303 		break;
2304 	}
2305 	if (err)
2306 		return err;
2307 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2308 	return 0;
2309 }
2310 
2311 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2312 {
2313 	char buf[PATH_MAX];
2314 	struct utsname uts;
2315 	int len, err = 0;
2316 	gzFile file;
2317 
2318 	uname(&uts);
2319 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2320 	if (len < 0)
2321 		return -EINVAL;
2322 	else if (len >= PATH_MAX)
2323 		return -ENAMETOOLONG;
2324 
2325 	/* gzopen also accepts uncompressed files. */
2326 	file = gzopen(buf, "re");
2327 	if (!file)
2328 		file = gzopen("/proc/config.gz", "re");
2329 
2330 	if (!file) {
2331 		pr_warn("failed to open system Kconfig\n");
2332 		return -ENOENT;
2333 	}
2334 
2335 	while (gzgets(file, buf, sizeof(buf))) {
2336 		err = bpf_object__process_kconfig_line(obj, buf, data);
2337 		if (err) {
2338 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2339 				buf, errstr(err));
2340 			goto out;
2341 		}
2342 	}
2343 
2344 out:
2345 	gzclose(file);
2346 	return err;
2347 }
2348 
2349 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2350 					const char *config, void *data)
2351 {
2352 	char buf[PATH_MAX];
2353 	int err = 0;
2354 	FILE *file;
2355 
2356 	file = fmemopen((void *)config, strlen(config), "r");
2357 	if (!file) {
2358 		err = -errno;
2359 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2360 		return err;
2361 	}
2362 
2363 	while (fgets(buf, sizeof(buf), file)) {
2364 		err = bpf_object__process_kconfig_line(obj, buf, data);
2365 		if (err) {
2366 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2367 				buf, errstr(err));
2368 			break;
2369 		}
2370 	}
2371 
2372 	fclose(file);
2373 	return err;
2374 }
2375 
2376 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2377 {
2378 	struct extern_desc *last_ext = NULL, *ext;
2379 	size_t map_sz;
2380 	int i, err;
2381 
2382 	for (i = 0; i < obj->nr_extern; i++) {
2383 		ext = &obj->externs[i];
2384 		if (ext->type == EXT_KCFG)
2385 			last_ext = ext;
2386 	}
2387 
2388 	if (!last_ext)
2389 		return 0;
2390 
2391 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2392 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2393 					    ".kconfig", obj->efile.symbols_shndx,
2394 					    NULL, map_sz);
2395 	if (err)
2396 		return err;
2397 
2398 	obj->kconfig_map_idx = obj->nr_maps - 1;
2399 
2400 	return 0;
2401 }
2402 
2403 const struct btf_type *
2404 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2405 {
2406 	const struct btf_type *t = btf__type_by_id(btf, id);
2407 
2408 	if (res_id)
2409 		*res_id = id;
2410 
2411 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2412 		if (res_id)
2413 			*res_id = t->type;
2414 		t = btf__type_by_id(btf, t->type);
2415 	}
2416 
2417 	return t;
2418 }
2419 
2420 static const struct btf_type *
2421 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2422 {
2423 	const struct btf_type *t;
2424 
2425 	t = skip_mods_and_typedefs(btf, id, NULL);
2426 	if (!btf_is_ptr(t))
2427 		return NULL;
2428 
2429 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2430 
2431 	return btf_is_func_proto(t) ? t : NULL;
2432 }
2433 
2434 static const char *__btf_kind_str(__u16 kind)
2435 {
2436 	switch (kind) {
2437 	case BTF_KIND_UNKN: return "void";
2438 	case BTF_KIND_INT: return "int";
2439 	case BTF_KIND_PTR: return "ptr";
2440 	case BTF_KIND_ARRAY: return "array";
2441 	case BTF_KIND_STRUCT: return "struct";
2442 	case BTF_KIND_UNION: return "union";
2443 	case BTF_KIND_ENUM: return "enum";
2444 	case BTF_KIND_FWD: return "fwd";
2445 	case BTF_KIND_TYPEDEF: return "typedef";
2446 	case BTF_KIND_VOLATILE: return "volatile";
2447 	case BTF_KIND_CONST: return "const";
2448 	case BTF_KIND_RESTRICT: return "restrict";
2449 	case BTF_KIND_FUNC: return "func";
2450 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2451 	case BTF_KIND_VAR: return "var";
2452 	case BTF_KIND_DATASEC: return "datasec";
2453 	case BTF_KIND_FLOAT: return "float";
2454 	case BTF_KIND_DECL_TAG: return "decl_tag";
2455 	case BTF_KIND_TYPE_TAG: return "type_tag";
2456 	case BTF_KIND_ENUM64: return "enum64";
2457 	default: return "unknown";
2458 	}
2459 }
2460 
2461 const char *btf_kind_str(const struct btf_type *t)
2462 {
2463 	return __btf_kind_str(btf_kind(t));
2464 }
2465 
2466 /*
2467  * Fetch integer attribute of BTF map definition. Such attributes are
2468  * represented using a pointer to an array, in which dimensionality of array
2469  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2470  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2471  * type definition, while using only sizeof(void *) space in ELF data section.
2472  */
2473 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2474 			      const struct btf_member *m, __u32 *res)
2475 {
2476 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2477 	const char *name = btf__name_by_offset(btf, m->name_off);
2478 	const struct btf_array *arr_info;
2479 	const struct btf_type *arr_t;
2480 
2481 	if (!btf_is_ptr(t)) {
2482 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2483 			map_name, name, btf_kind_str(t));
2484 		return false;
2485 	}
2486 
2487 	arr_t = btf__type_by_id(btf, t->type);
2488 	if (!arr_t) {
2489 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2490 			map_name, name, t->type);
2491 		return false;
2492 	}
2493 	if (!btf_is_array(arr_t)) {
2494 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2495 			map_name, name, btf_kind_str(arr_t));
2496 		return false;
2497 	}
2498 	arr_info = btf_array(arr_t);
2499 	*res = arr_info->nelems;
2500 	return true;
2501 }
2502 
2503 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2504 			       const struct btf_member *m, __u64 *res)
2505 {
2506 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2507 	const char *name = btf__name_by_offset(btf, m->name_off);
2508 
2509 	if (btf_is_ptr(t)) {
2510 		__u32 res32;
2511 		bool ret;
2512 
2513 		ret = get_map_field_int(map_name, btf, m, &res32);
2514 		if (ret)
2515 			*res = (__u64)res32;
2516 		return ret;
2517 	}
2518 
2519 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2520 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2521 			map_name, name, btf_kind_str(t));
2522 		return false;
2523 	}
2524 
2525 	if (btf_vlen(t) != 1) {
2526 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2527 			map_name, name);
2528 		return false;
2529 	}
2530 
2531 	if (btf_is_enum(t)) {
2532 		const struct btf_enum *e = btf_enum(t);
2533 
2534 		*res = e->val;
2535 	} else {
2536 		const struct btf_enum64 *e = btf_enum64(t);
2537 
2538 		*res = btf_enum64_value(e);
2539 	}
2540 	return true;
2541 }
2542 
2543 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2544 {
2545 	int len;
2546 
2547 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2548 	if (len < 0)
2549 		return -EINVAL;
2550 	if (len >= buf_sz)
2551 		return -ENAMETOOLONG;
2552 
2553 	return 0;
2554 }
2555 
2556 static int build_map_pin_path(struct bpf_map *map, const char *path)
2557 {
2558 	char buf[PATH_MAX];
2559 	int err;
2560 
2561 	if (!path)
2562 		path = BPF_FS_DEFAULT_PATH;
2563 
2564 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2565 	if (err)
2566 		return err;
2567 
2568 	return bpf_map__set_pin_path(map, buf);
2569 }
2570 
2571 /* should match definition in bpf_helpers.h */
2572 enum libbpf_pin_type {
2573 	LIBBPF_PIN_NONE,
2574 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2575 	LIBBPF_PIN_BY_NAME,
2576 };
2577 
2578 int parse_btf_map_def(const char *map_name, struct btf *btf,
2579 		      const struct btf_type *def_t, bool strict,
2580 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2581 {
2582 	const struct btf_type *t;
2583 	const struct btf_member *m;
2584 	bool is_inner = inner_def == NULL;
2585 	int vlen, i;
2586 
2587 	vlen = btf_vlen(def_t);
2588 	m = btf_members(def_t);
2589 	for (i = 0; i < vlen; i++, m++) {
2590 		const char *name = btf__name_by_offset(btf, m->name_off);
2591 
2592 		if (!name) {
2593 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2594 			return -EINVAL;
2595 		}
2596 		if (strcmp(name, "type") == 0) {
2597 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2598 				return -EINVAL;
2599 			map_def->parts |= MAP_DEF_MAP_TYPE;
2600 		} else if (strcmp(name, "max_entries") == 0) {
2601 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2602 				return -EINVAL;
2603 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2604 		} else if (strcmp(name, "map_flags") == 0) {
2605 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2606 				return -EINVAL;
2607 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2608 		} else if (strcmp(name, "numa_node") == 0) {
2609 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2610 				return -EINVAL;
2611 			map_def->parts |= MAP_DEF_NUMA_NODE;
2612 		} else if (strcmp(name, "key_size") == 0) {
2613 			__u32 sz;
2614 
2615 			if (!get_map_field_int(map_name, btf, m, &sz))
2616 				return -EINVAL;
2617 			if (map_def->key_size && map_def->key_size != sz) {
2618 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2619 					map_name, map_def->key_size, sz);
2620 				return -EINVAL;
2621 			}
2622 			map_def->key_size = sz;
2623 			map_def->parts |= MAP_DEF_KEY_SIZE;
2624 		} else if (strcmp(name, "key") == 0) {
2625 			__s64 sz;
2626 
2627 			t = btf__type_by_id(btf, m->type);
2628 			if (!t) {
2629 				pr_warn("map '%s': key type [%u] not found.\n",
2630 					map_name, m->type);
2631 				return -EINVAL;
2632 			}
2633 			if (!btf_is_ptr(t)) {
2634 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2635 					map_name, btf_kind_str(t));
2636 				return -EINVAL;
2637 			}
2638 			sz = btf__resolve_size(btf, t->type);
2639 			if (sz < 0) {
2640 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2641 					map_name, t->type, (ssize_t)sz);
2642 				return sz;
2643 			}
2644 			if (map_def->key_size && map_def->key_size != sz) {
2645 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2646 					map_name, map_def->key_size, (ssize_t)sz);
2647 				return -EINVAL;
2648 			}
2649 			map_def->key_size = sz;
2650 			map_def->key_type_id = t->type;
2651 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2652 		} else if (strcmp(name, "value_size") == 0) {
2653 			__u32 sz;
2654 
2655 			if (!get_map_field_int(map_name, btf, m, &sz))
2656 				return -EINVAL;
2657 			if (map_def->value_size && map_def->value_size != sz) {
2658 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2659 					map_name, map_def->value_size, sz);
2660 				return -EINVAL;
2661 			}
2662 			map_def->value_size = sz;
2663 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2664 		} else if (strcmp(name, "value") == 0) {
2665 			__s64 sz;
2666 
2667 			t = btf__type_by_id(btf, m->type);
2668 			if (!t) {
2669 				pr_warn("map '%s': value type [%u] not found.\n",
2670 					map_name, m->type);
2671 				return -EINVAL;
2672 			}
2673 			if (!btf_is_ptr(t)) {
2674 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2675 					map_name, btf_kind_str(t));
2676 				return -EINVAL;
2677 			}
2678 			sz = btf__resolve_size(btf, t->type);
2679 			if (sz < 0) {
2680 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2681 					map_name, t->type, (ssize_t)sz);
2682 				return sz;
2683 			}
2684 			if (map_def->value_size && map_def->value_size != sz) {
2685 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2686 					map_name, map_def->value_size, (ssize_t)sz);
2687 				return -EINVAL;
2688 			}
2689 			map_def->value_size = sz;
2690 			map_def->value_type_id = t->type;
2691 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2692 		}
2693 		else if (strcmp(name, "values") == 0) {
2694 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2695 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2696 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2697 			char inner_map_name[128];
2698 			int err;
2699 
2700 			if (is_inner) {
2701 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2702 					map_name);
2703 				return -ENOTSUP;
2704 			}
2705 			if (i != vlen - 1) {
2706 				pr_warn("map '%s': '%s' member should be last.\n",
2707 					map_name, name);
2708 				return -EINVAL;
2709 			}
2710 			if (!is_map_in_map && !is_prog_array) {
2711 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2712 					map_name);
2713 				return -ENOTSUP;
2714 			}
2715 			if (map_def->value_size && map_def->value_size != 4) {
2716 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2717 					map_name, map_def->value_size);
2718 				return -EINVAL;
2719 			}
2720 			map_def->value_size = 4;
2721 			t = btf__type_by_id(btf, m->type);
2722 			if (!t) {
2723 				pr_warn("map '%s': %s type [%u] not found.\n",
2724 					map_name, desc, m->type);
2725 				return -EINVAL;
2726 			}
2727 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2728 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2729 					map_name, desc);
2730 				return -EINVAL;
2731 			}
2732 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2733 			if (!btf_is_ptr(t)) {
2734 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2735 					map_name, desc, btf_kind_str(t));
2736 				return -EINVAL;
2737 			}
2738 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2739 			if (is_prog_array) {
2740 				if (!btf_is_func_proto(t)) {
2741 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2742 						map_name, btf_kind_str(t));
2743 					return -EINVAL;
2744 				}
2745 				continue;
2746 			}
2747 			if (!btf_is_struct(t)) {
2748 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2749 					map_name, btf_kind_str(t));
2750 				return -EINVAL;
2751 			}
2752 
2753 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2754 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2755 			if (err)
2756 				return err;
2757 
2758 			map_def->parts |= MAP_DEF_INNER_MAP;
2759 		} else if (strcmp(name, "pinning") == 0) {
2760 			__u32 val;
2761 
2762 			if (is_inner) {
2763 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2764 				return -EINVAL;
2765 			}
2766 			if (!get_map_field_int(map_name, btf, m, &val))
2767 				return -EINVAL;
2768 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2769 				pr_warn("map '%s': invalid pinning value %u.\n",
2770 					map_name, val);
2771 				return -EINVAL;
2772 			}
2773 			map_def->pinning = val;
2774 			map_def->parts |= MAP_DEF_PINNING;
2775 		} else if (strcmp(name, "map_extra") == 0) {
2776 			__u64 map_extra;
2777 
2778 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2779 				return -EINVAL;
2780 			map_def->map_extra = map_extra;
2781 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2782 		} else {
2783 			if (strict) {
2784 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2785 				return -ENOTSUP;
2786 			}
2787 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2788 		}
2789 	}
2790 
2791 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2792 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2793 		return -EINVAL;
2794 	}
2795 
2796 	return 0;
2797 }
2798 
2799 static size_t adjust_ringbuf_sz(size_t sz)
2800 {
2801 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2802 	__u32 mul;
2803 
2804 	/* if user forgot to set any size, make sure they see error */
2805 	if (sz == 0)
2806 		return 0;
2807 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2808 	 * a power-of-2 multiple of kernel's page size. If user diligently
2809 	 * satisified these conditions, pass the size through.
2810 	 */
2811 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2812 		return sz;
2813 
2814 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2815 	 * user-set size to satisfy both user size request and kernel
2816 	 * requirements and substitute correct max_entries for map creation.
2817 	 */
2818 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2819 		if (mul * page_sz > sz)
2820 			return mul * page_sz;
2821 	}
2822 
2823 	/* if it's impossible to satisfy the conditions (i.e., user size is
2824 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2825 	 * page_size) then just return original size and let kernel reject it
2826 	 */
2827 	return sz;
2828 }
2829 
2830 static bool map_is_ringbuf(const struct bpf_map *map)
2831 {
2832 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2833 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2834 }
2835 
2836 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2837 {
2838 	map->def.type = def->map_type;
2839 	map->def.key_size = def->key_size;
2840 	map->def.value_size = def->value_size;
2841 	map->def.max_entries = def->max_entries;
2842 	map->def.map_flags = def->map_flags;
2843 	map->map_extra = def->map_extra;
2844 
2845 	map->numa_node = def->numa_node;
2846 	map->btf_key_type_id = def->key_type_id;
2847 	map->btf_value_type_id = def->value_type_id;
2848 
2849 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2850 	if (map_is_ringbuf(map))
2851 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2852 
2853 	if (def->parts & MAP_DEF_MAP_TYPE)
2854 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2855 
2856 	if (def->parts & MAP_DEF_KEY_TYPE)
2857 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2858 			 map->name, def->key_type_id, def->key_size);
2859 	else if (def->parts & MAP_DEF_KEY_SIZE)
2860 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2861 
2862 	if (def->parts & MAP_DEF_VALUE_TYPE)
2863 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2864 			 map->name, def->value_type_id, def->value_size);
2865 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2866 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2867 
2868 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2869 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2870 	if (def->parts & MAP_DEF_MAP_FLAGS)
2871 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2872 	if (def->parts & MAP_DEF_MAP_EXTRA)
2873 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2874 			 (unsigned long long)def->map_extra);
2875 	if (def->parts & MAP_DEF_PINNING)
2876 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2877 	if (def->parts & MAP_DEF_NUMA_NODE)
2878 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2879 
2880 	if (def->parts & MAP_DEF_INNER_MAP)
2881 		pr_debug("map '%s': found inner map definition.\n", map->name);
2882 }
2883 
2884 static const char *btf_var_linkage_str(__u32 linkage)
2885 {
2886 	switch (linkage) {
2887 	case BTF_VAR_STATIC: return "static";
2888 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2889 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2890 	default: return "unknown";
2891 	}
2892 }
2893 
2894 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2895 					 const struct btf_type *sec,
2896 					 int var_idx, int sec_idx,
2897 					 const Elf_Data *data, bool strict,
2898 					 const char *pin_root_path)
2899 {
2900 	struct btf_map_def map_def = {}, inner_def = {};
2901 	const struct btf_type *var, *def;
2902 	const struct btf_var_secinfo *vi;
2903 	const struct btf_var *var_extra;
2904 	const char *map_name;
2905 	struct bpf_map *map;
2906 	int err;
2907 
2908 	vi = btf_var_secinfos(sec) + var_idx;
2909 	var = btf__type_by_id(obj->btf, vi->type);
2910 	var_extra = btf_var(var);
2911 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2912 
2913 	if (str_is_empty(map_name)) {
2914 		pr_warn("map #%d: empty name.\n", var_idx);
2915 		return -EINVAL;
2916 	}
2917 	if ((__u64)vi->offset + vi->size > data->d_size) {
2918 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2919 		return -EINVAL;
2920 	}
2921 	if (!btf_is_var(var)) {
2922 		pr_warn("map '%s': unexpected var kind %s.\n",
2923 			map_name, btf_kind_str(var));
2924 		return -EINVAL;
2925 	}
2926 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2927 		pr_warn("map '%s': unsupported map linkage %s.\n",
2928 			map_name, btf_var_linkage_str(var_extra->linkage));
2929 		return -EOPNOTSUPP;
2930 	}
2931 
2932 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2933 	if (!btf_is_struct(def)) {
2934 		pr_warn("map '%s': unexpected def kind %s.\n",
2935 			map_name, btf_kind_str(var));
2936 		return -EINVAL;
2937 	}
2938 	if (def->size > vi->size) {
2939 		pr_warn("map '%s': invalid def size.\n", map_name);
2940 		return -EINVAL;
2941 	}
2942 
2943 	map = bpf_object__add_map(obj);
2944 	if (IS_ERR(map))
2945 		return PTR_ERR(map);
2946 	map->name = strdup(map_name);
2947 	if (!map->name) {
2948 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2949 		return -ENOMEM;
2950 	}
2951 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2952 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2953 	map->sec_idx = sec_idx;
2954 	map->sec_offset = vi->offset;
2955 	map->btf_var_idx = var_idx;
2956 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2957 		 map_name, map->sec_idx, map->sec_offset);
2958 
2959 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2960 	if (err)
2961 		return err;
2962 
2963 	fill_map_from_def(map, &map_def);
2964 
2965 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2966 		err = build_map_pin_path(map, pin_root_path);
2967 		if (err) {
2968 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2969 			return err;
2970 		}
2971 	}
2972 
2973 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2974 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2975 		if (!map->inner_map)
2976 			return -ENOMEM;
2977 		map->inner_map->fd = create_placeholder_fd();
2978 		if (map->inner_map->fd < 0)
2979 			return map->inner_map->fd;
2980 		map->inner_map->sec_idx = sec_idx;
2981 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2982 		if (!map->inner_map->name)
2983 			return -ENOMEM;
2984 		sprintf(map->inner_map->name, "%s.inner", map_name);
2985 
2986 		fill_map_from_def(map->inner_map, &inner_def);
2987 	}
2988 
2989 	err = map_fill_btf_type_info(obj, map);
2990 	if (err)
2991 		return err;
2992 
2993 	return 0;
2994 }
2995 
2996 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2997 			       const char *sec_name, int sec_idx,
2998 			       void *data, size_t data_sz)
2999 {
3000 	const long page_sz = sysconf(_SC_PAGE_SIZE);
3001 	const size_t data_alloc_sz = roundup(data_sz, page_sz);
3002 	size_t mmap_sz;
3003 
3004 	mmap_sz = bpf_map_mmap_sz(map);
3005 	if (data_alloc_sz > mmap_sz) {
3006 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
3007 			sec_name, mmap_sz, data_sz);
3008 		return -E2BIG;
3009 	}
3010 
3011 	obj->arena_data = malloc(data_sz);
3012 	if (!obj->arena_data)
3013 		return -ENOMEM;
3014 	memcpy(obj->arena_data, data, data_sz);
3015 	obj->arena_data_sz = data_sz;
3016 
3017 	/* make bpf_map__init_value() work for ARENA maps */
3018 	map->mmaped = obj->arena_data;
3019 
3020 	return 0;
3021 }
3022 
3023 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3024 					  const char *pin_root_path)
3025 {
3026 	const struct btf_type *sec = NULL;
3027 	int nr_types, i, vlen, err;
3028 	const struct btf_type *t;
3029 	const char *name;
3030 	Elf_Data *data;
3031 	Elf_Scn *scn;
3032 
3033 	if (obj->efile.btf_maps_shndx < 0)
3034 		return 0;
3035 
3036 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3037 	data = elf_sec_data(obj, scn);
3038 	if (!data) {
3039 		pr_warn("elf: failed to get %s map definitions for %s\n",
3040 			MAPS_ELF_SEC, obj->path);
3041 		return -EINVAL;
3042 	}
3043 
3044 	nr_types = btf__type_cnt(obj->btf);
3045 	for (i = 1; i < nr_types; i++) {
3046 		t = btf__type_by_id(obj->btf, i);
3047 		if (!btf_is_datasec(t))
3048 			continue;
3049 		name = btf__name_by_offset(obj->btf, t->name_off);
3050 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3051 			sec = t;
3052 			obj->efile.btf_maps_sec_btf_id = i;
3053 			break;
3054 		}
3055 	}
3056 
3057 	if (!sec) {
3058 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3059 		return -ENOENT;
3060 	}
3061 
3062 	vlen = btf_vlen(sec);
3063 	for (i = 0; i < vlen; i++) {
3064 		err = bpf_object__init_user_btf_map(obj, sec, i,
3065 						    obj->efile.btf_maps_shndx,
3066 						    data, strict,
3067 						    pin_root_path);
3068 		if (err)
3069 			return err;
3070 	}
3071 
3072 	for (i = 0; i < obj->nr_maps; i++) {
3073 		struct bpf_map *map = &obj->maps[i];
3074 
3075 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3076 			continue;
3077 
3078 		if (obj->arena_map_idx >= 0) {
3079 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3080 				map->name, obj->maps[obj->arena_map_idx].name);
3081 			return -EINVAL;
3082 		}
3083 		obj->arena_map_idx = i;
3084 
3085 		if (obj->efile.arena_data) {
3086 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3087 						  obj->efile.arena_data->d_buf,
3088 						  obj->efile.arena_data->d_size);
3089 			if (err)
3090 				return err;
3091 		}
3092 	}
3093 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3094 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3095 			ARENA_SEC);
3096 		return -ENOENT;
3097 	}
3098 
3099 	return 0;
3100 }
3101 
3102 static int bpf_object__init_maps(struct bpf_object *obj,
3103 				 const struct bpf_object_open_opts *opts)
3104 {
3105 	const char *pin_root_path;
3106 	bool strict;
3107 	int err = 0;
3108 
3109 	strict = !OPTS_GET(opts, relaxed_maps, false);
3110 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3111 
3112 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3113 	err = err ?: bpf_object__init_global_data_maps(obj);
3114 	err = err ?: bpf_object__init_kconfig_map(obj);
3115 	err = err ?: bpf_object_init_struct_ops(obj);
3116 
3117 	return err;
3118 }
3119 
3120 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3121 {
3122 	Elf64_Shdr *sh;
3123 
3124 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3125 	if (!sh)
3126 		return false;
3127 
3128 	return sh->sh_flags & SHF_EXECINSTR;
3129 }
3130 
3131 static bool starts_with_qmark(const char *s)
3132 {
3133 	return s && s[0] == '?';
3134 }
3135 
3136 static bool btf_needs_sanitization(struct bpf_object *obj)
3137 {
3138 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3139 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3140 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3141 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3142 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3143 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3144 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3145 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3146 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3147 
3148 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3149 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3150 	       !has_layout;
3151 }
3152 
3153 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3154 {
3155 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3156 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3157 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3158 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3159 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3160 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3161 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3162 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3163 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3164 	int enum64_placeholder_id = 0;
3165 	const struct btf_header *hdr;
3166 	struct btf *btf = NULL;
3167 	const void *raw_data;
3168 	struct btf_type *t;
3169 	int i, j, vlen;
3170 	__u32 sz;
3171 	int err;
3172 
3173 	/* clone BTF to sanitize a copy and leave the original intact */
3174 	raw_data = btf__raw_data(orig_btf, &sz);
3175 	if (!raw_data)
3176 		return ERR_PTR(-ENOMEM);
3177 	/* btf_header() gives us endian-safe header info */
3178 	hdr = btf_header(orig_btf);
3179 
3180 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3181 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3182 		const struct btf_header *old_hdr = raw_data;
3183 		struct btf_header *new_hdr;
3184 		void *new_raw_data;
3185 		__u32 new_str_off;
3186 
3187 		/*
3188 		 * Need to rewrite BTF to exclude layout information and
3189 		 * move string section to immediately after types.
3190 		 */
3191 		new_raw_data = malloc(sz);
3192 		if (!new_raw_data)
3193 			return ERR_PTR(-ENOMEM);
3194 
3195 		memcpy(new_raw_data, raw_data, sz);
3196 		new_hdr = new_raw_data;
3197 		new_hdr->layout_off = 0;
3198 		new_hdr->layout_len = 0;
3199 		new_str_off = hdr->type_off + hdr->type_len;
3200 		/* Handle swapped endian case */
3201 		if (old_hdr->magic != hdr->magic)
3202 			new_hdr->str_off = bswap_32(new_str_off);
3203 		else
3204 			new_hdr->str_off = new_str_off;
3205 
3206 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3207 			new_raw_data + hdr->hdr_len + hdr->str_off,
3208 			hdr->str_len);
3209 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3210 		btf = btf__new(new_raw_data, sz);
3211 		free(new_raw_data);
3212 	} else {
3213 		btf = btf__new(raw_data, sz);
3214 	}
3215 	err = libbpf_get_error(btf);
3216 	if (err)
3217 		return ERR_PTR(err);
3218 
3219 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3220 	btf__set_pointer_size(btf, 8);
3221 
3222 	for (i = 1; i < btf__type_cnt(btf); i++) {
3223 		t = (struct btf_type *)btf__type_by_id(btf, i);
3224 
3225 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3226 			/* replace VAR/DECL_TAG with INT */
3227 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3228 			/*
3229 			 * using size = 1 is the safest choice, 4 will be too
3230 			 * big and cause kernel BTF validation failure if
3231 			 * original variable took less than 4 bytes
3232 			 */
3233 			t->size = 1;
3234 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3235 		} else if (!has_datasec && btf_is_datasec(t)) {
3236 			/* replace DATASEC with STRUCT */
3237 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3238 			struct btf_member *m = btf_members(t);
3239 			struct btf_type *vt;
3240 			char *name;
3241 
3242 			name = (char *)btf__name_by_offset(btf, t->name_off);
3243 			while (*name) {
3244 				if (*name == '.' || *name == '?')
3245 					*name = '_';
3246 				name++;
3247 			}
3248 
3249 			vlen = btf_vlen(t);
3250 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3251 			for (j = 0; j < vlen; j++, v++, m++) {
3252 				/* order of field assignments is important */
3253 				m->offset = v->offset * 8;
3254 				m->type = v->type;
3255 				/* preserve variable name as member name */
3256 				vt = (void *)btf__type_by_id(btf, v->type);
3257 				m->name_off = vt->name_off;
3258 			}
3259 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3260 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3261 			/* replace '?' prefix with '_' for DATASEC names */
3262 			char *name;
3263 
3264 			name = (char *)btf__name_by_offset(btf, t->name_off);
3265 			if (name[0] == '?')
3266 				name[0] = '_';
3267 		} else if (!has_func && btf_is_func_proto(t)) {
3268 			/* replace FUNC_PROTO with ENUM */
3269 			vlen = btf_vlen(t);
3270 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3271 			t->size = sizeof(__u32); /* kernel enforced */
3272 		} else if (!has_func && btf_is_func(t)) {
3273 			/* replace FUNC with TYPEDEF */
3274 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3275 		} else if (!has_func_global && btf_is_func(t)) {
3276 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3277 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3278 		} else if (!has_float && btf_is_float(t)) {
3279 			/* replace FLOAT with an equally-sized empty STRUCT;
3280 			 * since C compilers do not accept e.g. "float" as a
3281 			 * valid struct name, make it anonymous
3282 			 */
3283 			t->name_off = 0;
3284 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3285 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3286 			/* replace TYPE_TAG with a CONST */
3287 			t->name_off = 0;
3288 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3289 		} else if (!has_enum64 && btf_is_enum(t)) {
3290 			/* clear the kflag */
3291 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3292 		} else if (!has_enum64 && btf_is_enum64(t)) {
3293 			/* replace ENUM64 with a union */
3294 			struct btf_member *m;
3295 
3296 			if (enum64_placeholder_id == 0) {
3297 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3298 				if (enum64_placeholder_id < 0) {
3299 					btf__free(btf);
3300 					return ERR_PTR(enum64_placeholder_id);
3301 				}
3302 				t = (struct btf_type *)btf__type_by_id(btf, i);
3303 			}
3304 
3305 			m = btf_members(t);
3306 			vlen = btf_vlen(t);
3307 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3308 			for (j = 0; j < vlen; j++, m++) {
3309 				m->type = enum64_placeholder_id;
3310 				m->offset = 0;
3311 			}
3312 		}
3313 	}
3314 
3315 	return btf;
3316 }
3317 
3318 static bool libbpf_needs_btf(const struct bpf_object *obj)
3319 {
3320 	return obj->efile.btf_maps_shndx >= 0 ||
3321 	       obj->efile.has_st_ops ||
3322 	       obj->nr_extern > 0;
3323 }
3324 
3325 static bool kernel_needs_btf(const struct bpf_object *obj)
3326 {
3327 	return obj->efile.has_st_ops;
3328 }
3329 
3330 static int bpf_object__init_btf(struct bpf_object *obj,
3331 				Elf_Data *btf_data,
3332 				Elf_Data *btf_ext_data)
3333 {
3334 	int err = -ENOENT;
3335 
3336 	if (btf_data) {
3337 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3338 		err = libbpf_get_error(obj->btf);
3339 		if (err) {
3340 			obj->btf = NULL;
3341 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3342 			goto out;
3343 		}
3344 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3345 		btf__set_pointer_size(obj->btf, 8);
3346 	}
3347 	if (btf_ext_data) {
3348 		struct btf_ext_info *ext_segs[3];
3349 		int seg_num, sec_num;
3350 
3351 		if (!obj->btf) {
3352 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3353 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3354 			goto out;
3355 		}
3356 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3357 		err = libbpf_get_error(obj->btf_ext);
3358 		if (err) {
3359 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3360 				BTF_EXT_ELF_SEC, errstr(err));
3361 			obj->btf_ext = NULL;
3362 			goto out;
3363 		}
3364 
3365 		/* setup .BTF.ext to ELF section mapping */
3366 		ext_segs[0] = &obj->btf_ext->func_info;
3367 		ext_segs[1] = &obj->btf_ext->line_info;
3368 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3369 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3370 			struct btf_ext_info *seg = ext_segs[seg_num];
3371 			const struct btf_ext_info_sec *sec;
3372 			const char *sec_name;
3373 			Elf_Scn *scn;
3374 
3375 			if (seg->sec_cnt == 0)
3376 				continue;
3377 
3378 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3379 			if (!seg->sec_idxs) {
3380 				err = -ENOMEM;
3381 				goto out;
3382 			}
3383 
3384 			sec_num = 0;
3385 			for_each_btf_ext_sec(seg, sec) {
3386 				/* preventively increment index to avoid doing
3387 				 * this before every continue below
3388 				 */
3389 				sec_num++;
3390 
3391 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3392 				if (str_is_empty(sec_name))
3393 					continue;
3394 				scn = elf_sec_by_name(obj, sec_name);
3395 				if (!scn)
3396 					continue;
3397 
3398 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3399 			}
3400 		}
3401 	}
3402 out:
3403 	if (err && libbpf_needs_btf(obj)) {
3404 		pr_warn("BTF is required, but is missing or corrupted.\n");
3405 		return err;
3406 	}
3407 	return 0;
3408 }
3409 
3410 static int compare_vsi_off(const void *_a, const void *_b)
3411 {
3412 	const struct btf_var_secinfo *a = _a;
3413 	const struct btf_var_secinfo *b = _b;
3414 
3415 	return a->offset - b->offset;
3416 }
3417 
3418 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3419 			     struct btf_type *t)
3420 {
3421 	__u32 size = 0, i, vars = btf_vlen(t);
3422 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3423 	struct btf_var_secinfo *vsi;
3424 	bool fixup_offsets = false;
3425 	int err;
3426 
3427 	if (!sec_name) {
3428 		pr_debug("No name found in string section for DATASEC kind.\n");
3429 		return -ENOENT;
3430 	}
3431 
3432 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3433 	 * variable offsets set at the previous step. Further, not every
3434 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3435 	 * all fixups altogether for such sections and go straight to sorting
3436 	 * VARs within their DATASEC.
3437 	 */
3438 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3439 		goto sort_vars;
3440 
3441 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3442 	 * fix this up. But BPF static linker already fixes this up and fills
3443 	 * all the sizes and offsets during static linking. So this step has
3444 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3445 	 * non-extern DATASEC, so the variable fixup loop below handles both
3446 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3447 	 * symbol matching just once.
3448 	 */
3449 	if (t->size == 0) {
3450 		err = find_elf_sec_sz(obj, sec_name, &size);
3451 		if (err || !size) {
3452 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3453 				 sec_name, size, errstr(err));
3454 			return -ENOENT;
3455 		}
3456 
3457 		t->size = size;
3458 		fixup_offsets = true;
3459 	}
3460 
3461 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3462 		const struct btf_type *t_var;
3463 		struct btf_var *var;
3464 		const char *var_name;
3465 		Elf64_Sym *sym;
3466 
3467 		t_var = btf__type_by_id(btf, vsi->type);
3468 		if (!t_var || !btf_is_var(t_var)) {
3469 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3470 			return -EINVAL;
3471 		}
3472 
3473 		var = btf_var(t_var);
3474 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3475 			continue;
3476 
3477 		var_name = btf__name_by_offset(btf, t_var->name_off);
3478 		if (!var_name) {
3479 			pr_debug("sec '%s': failed to find name of DATASEC's member #%u\n",
3480 				 sec_name, i);
3481 			return -ENOENT;
3482 		}
3483 
3484 		sym = find_elf_var_sym(obj, var_name);
3485 		if (IS_ERR(sym)) {
3486 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3487 				 sec_name, var_name);
3488 			return -ENOENT;
3489 		}
3490 
3491 		if (fixup_offsets)
3492 			vsi->offset = sym->st_value;
3493 
3494 		/* if variable is a global/weak symbol, but has restricted
3495 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3496 		 * as static. This follows similar logic for functions (BPF
3497 		 * subprogs) and influences libbpf's further decisions about
3498 		 * whether to make global data BPF array maps as
3499 		 * BPF_F_MMAPABLE.
3500 		 */
3501 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3502 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3503 			var->linkage = BTF_VAR_STATIC;
3504 	}
3505 
3506 sort_vars:
3507 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3508 	return 0;
3509 }
3510 
3511 static int bpf_object_fixup_btf(struct bpf_object *obj)
3512 {
3513 	int i, n, err = 0;
3514 
3515 	if (!obj->btf)
3516 		return 0;
3517 
3518 	n = btf__type_cnt(obj->btf);
3519 	for (i = 1; i < n; i++) {
3520 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3521 
3522 		/* Loader needs to fix up some of the things compiler
3523 		 * couldn't get its hands on while emitting BTF. This
3524 		 * is section size and global variable offset. We use
3525 		 * the info from the ELF itself for this purpose.
3526 		 */
3527 		if (btf_is_datasec(t)) {
3528 			err = btf_fixup_datasec(obj, obj->btf, t);
3529 			if (err)
3530 				return err;
3531 		}
3532 	}
3533 
3534 	return 0;
3535 }
3536 
3537 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3538 {
3539 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3540 	    prog->type == BPF_PROG_TYPE_LSM)
3541 		return true;
3542 
3543 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3544 	 * also need vmlinux BTF
3545 	 */
3546 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3547 		return true;
3548 
3549 	return false;
3550 }
3551 
3552 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3553 {
3554 	return bpf_map__is_struct_ops(map);
3555 }
3556 
3557 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3558 {
3559 	struct bpf_program *prog;
3560 	struct bpf_map *map;
3561 	int i;
3562 
3563 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3564 	 * is not specified
3565 	 */
3566 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3567 		return true;
3568 
3569 	/* Support for typed ksyms needs kernel BTF */
3570 	for (i = 0; i < obj->nr_extern; i++) {
3571 		const struct extern_desc *ext;
3572 
3573 		ext = &obj->externs[i];
3574 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3575 			return true;
3576 	}
3577 
3578 	bpf_object__for_each_program(prog, obj) {
3579 		if (!prog->autoload)
3580 			continue;
3581 		if (prog_needs_vmlinux_btf(prog))
3582 			return true;
3583 	}
3584 
3585 	bpf_object__for_each_map(map, obj) {
3586 		if (map_needs_vmlinux_btf(map))
3587 			return true;
3588 	}
3589 
3590 	return false;
3591 }
3592 
3593 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3594 {
3595 	int err;
3596 
3597 	/* btf_vmlinux could be loaded earlier */
3598 	if (obj->btf_vmlinux || obj->gen_loader)
3599 		return 0;
3600 
3601 	if (!force && !obj_needs_vmlinux_btf(obj))
3602 		return 0;
3603 
3604 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3605 	err = libbpf_get_error(obj->btf_vmlinux);
3606 	if (err) {
3607 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3608 		obj->btf_vmlinux = NULL;
3609 		return err;
3610 	}
3611 	return 0;
3612 }
3613 
3614 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3615 {
3616 	struct btf *kern_btf = obj->btf;
3617 	bool btf_mandatory, sanitize;
3618 	int i, err = 0;
3619 
3620 	if (!obj->btf)
3621 		return 0;
3622 
3623 	if (!kernel_supports(obj, FEAT_BTF)) {
3624 		if (kernel_needs_btf(obj)) {
3625 			err = -EOPNOTSUPP;
3626 			goto report;
3627 		}
3628 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3629 		return 0;
3630 	}
3631 
3632 	/* Even though some subprogs are global/weak, user might prefer more
3633 	 * permissive BPF verification process that BPF verifier performs for
3634 	 * static functions, taking into account more context from the caller
3635 	 * functions. In such case, they need to mark such subprogs with
3636 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3637 	 * corresponding FUNC BTF type to be marked as static and trigger more
3638 	 * involved BPF verification process.
3639 	 */
3640 	for (i = 0; i < obj->nr_programs; i++) {
3641 		struct bpf_program *prog = &obj->programs[i];
3642 		struct btf_type *t;
3643 		const char *name;
3644 		int j, n;
3645 
3646 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3647 			continue;
3648 
3649 		n = btf__type_cnt(obj->btf);
3650 		for (j = 1; j < n; j++) {
3651 			t = btf_type_by_id(obj->btf, j);
3652 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3653 				continue;
3654 
3655 			name = btf__str_by_offset(obj->btf, t->name_off);
3656 			if (strcmp(name, prog->name) != 0)
3657 				continue;
3658 
3659 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3660 			break;
3661 		}
3662 	}
3663 
3664 	sanitize = btf_needs_sanitization(obj);
3665 	if (sanitize) {
3666 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3667 		if (IS_ERR(kern_btf))
3668 			return PTR_ERR(kern_btf);
3669 	}
3670 
3671 	if (obj->gen_loader) {
3672 		__u32 raw_size = 0;
3673 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3674 
3675 		if (!raw_data)
3676 			return -ENOMEM;
3677 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3678 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3679 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3680 		 */
3681 		btf__set_fd(kern_btf, 0);
3682 	} else {
3683 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3684 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3685 					   obj->log_level ? 1 : 0, obj->token_fd);
3686 	}
3687 	if (sanitize) {
3688 		if (!err) {
3689 			/* move fd to libbpf's BTF */
3690 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3691 			btf__set_fd(kern_btf, -1);
3692 		}
3693 		btf__free(kern_btf);
3694 	}
3695 report:
3696 	if (err) {
3697 		btf_mandatory = kernel_needs_btf(obj);
3698 		if (btf_mandatory) {
3699 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3700 				errstr(err));
3701 		} else {
3702 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3703 				errstr(err));
3704 			err = 0;
3705 		}
3706 	}
3707 	return err;
3708 }
3709 
3710 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3711 {
3712 	const char *name;
3713 
3714 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3715 	if (!name) {
3716 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3717 			off, obj->path, elf_errmsg(-1));
3718 		return NULL;
3719 	}
3720 
3721 	return name;
3722 }
3723 
3724 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3725 {
3726 	const char *name;
3727 
3728 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3729 	if (!name) {
3730 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3731 			off, obj->path, elf_errmsg(-1));
3732 		return NULL;
3733 	}
3734 
3735 	return name;
3736 }
3737 
3738 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3739 {
3740 	Elf_Scn *scn;
3741 
3742 	scn = elf_getscn(obj->efile.elf, idx);
3743 	if (!scn) {
3744 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3745 			idx, obj->path, elf_errmsg(-1));
3746 		return NULL;
3747 	}
3748 	return scn;
3749 }
3750 
3751 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3752 {
3753 	Elf_Scn *scn = NULL;
3754 	Elf *elf = obj->efile.elf;
3755 	const char *sec_name;
3756 
3757 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3758 		sec_name = elf_sec_name(obj, scn);
3759 		if (!sec_name)
3760 			return NULL;
3761 
3762 		if (strcmp(sec_name, name) != 0)
3763 			continue;
3764 
3765 		return scn;
3766 	}
3767 	return NULL;
3768 }
3769 
3770 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3771 {
3772 	Elf64_Shdr *shdr;
3773 
3774 	if (!scn)
3775 		return NULL;
3776 
3777 	shdr = elf64_getshdr(scn);
3778 	if (!shdr) {
3779 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3780 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3781 		return NULL;
3782 	}
3783 
3784 	return shdr;
3785 }
3786 
3787 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3788 {
3789 	const char *name;
3790 	Elf64_Shdr *sh;
3791 
3792 	if (!scn)
3793 		return NULL;
3794 
3795 	sh = elf_sec_hdr(obj, scn);
3796 	if (!sh)
3797 		return NULL;
3798 
3799 	name = elf_sec_str(obj, sh->sh_name);
3800 	if (!name) {
3801 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3802 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3803 		return NULL;
3804 	}
3805 
3806 	return name;
3807 }
3808 
3809 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3810 {
3811 	Elf_Data *data;
3812 
3813 	if (!scn)
3814 		return NULL;
3815 
3816 	data = elf_getdata(scn, 0);
3817 	if (!data) {
3818 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3819 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3820 			obj->path, elf_errmsg(-1));
3821 		return NULL;
3822 	}
3823 
3824 	return data;
3825 }
3826 
3827 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3828 {
3829 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3830 		return NULL;
3831 
3832 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3833 }
3834 
3835 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3836 {
3837 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3838 		return NULL;
3839 
3840 	return (Elf64_Rel *)data->d_buf + idx;
3841 }
3842 
3843 static bool is_sec_name_dwarf(const char *name)
3844 {
3845 	/* approximation, but the actual list is too long */
3846 	return str_has_pfx(name, ".debug_");
3847 }
3848 
3849 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3850 {
3851 	/* no special handling of .strtab */
3852 	if (hdr->sh_type == SHT_STRTAB)
3853 		return true;
3854 
3855 	/* ignore .llvm_addrsig section as well */
3856 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3857 		return true;
3858 
3859 	/* no subprograms will lead to an empty .text section, ignore it */
3860 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3861 	    strcmp(name, ".text") == 0)
3862 		return true;
3863 
3864 	/* DWARF sections */
3865 	if (is_sec_name_dwarf(name))
3866 		return true;
3867 
3868 	if (str_has_pfx(name, ".rel")) {
3869 		name += sizeof(".rel") - 1;
3870 		/* DWARF section relocations */
3871 		if (is_sec_name_dwarf(name))
3872 			return true;
3873 
3874 		/* .BTF and .BTF.ext don't need relocations */
3875 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3876 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3877 			return true;
3878 	}
3879 
3880 	return false;
3881 }
3882 
3883 static int cmp_progs(const void *_a, const void *_b)
3884 {
3885 	const struct bpf_program *a = _a;
3886 	const struct bpf_program *b = _b;
3887 
3888 	if (a->sec_idx != b->sec_idx)
3889 		return a->sec_idx < b->sec_idx ? -1 : 1;
3890 
3891 	/* sec_insn_off can't be the same within the section */
3892 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3893 }
3894 
3895 static int bpf_object__elf_collect(struct bpf_object *obj)
3896 {
3897 	struct elf_sec_desc *sec_desc;
3898 	Elf *elf = obj->efile.elf;
3899 	Elf_Data *btf_ext_data = NULL;
3900 	Elf_Data *btf_data = NULL;
3901 	int idx = 0, err = 0;
3902 	const char *name;
3903 	Elf_Data *data;
3904 	Elf_Scn *scn;
3905 	Elf64_Shdr *sh;
3906 
3907 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3908 	 * section. Since section count retrieved by elf_getshdrnum() does
3909 	 * include sec #0, it is already the necessary size of an array to keep
3910 	 * all the sections.
3911 	 */
3912 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3913 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3914 			obj->path, elf_errmsg(-1));
3915 		return -LIBBPF_ERRNO__FORMAT;
3916 	}
3917 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3918 	if (!obj->efile.secs)
3919 		return -ENOMEM;
3920 
3921 	/* a bunch of ELF parsing functionality depends on processing symbols,
3922 	 * so do the first pass and find the symbol table
3923 	 */
3924 	scn = NULL;
3925 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3926 		sh = elf_sec_hdr(obj, scn);
3927 		if (!sh)
3928 			return -LIBBPF_ERRNO__FORMAT;
3929 
3930 		if (sh->sh_type == SHT_SYMTAB) {
3931 			if (obj->efile.symbols) {
3932 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3933 				return -LIBBPF_ERRNO__FORMAT;
3934 			}
3935 
3936 			data = elf_sec_data(obj, scn);
3937 			if (!data)
3938 				return -LIBBPF_ERRNO__FORMAT;
3939 
3940 			idx = elf_ndxscn(scn);
3941 
3942 			obj->efile.symbols = data;
3943 			obj->efile.symbols_shndx = idx;
3944 			obj->efile.strtabidx = sh->sh_link;
3945 		}
3946 	}
3947 
3948 	if (!obj->efile.symbols) {
3949 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3950 			obj->path);
3951 		return -ENOENT;
3952 	}
3953 
3954 	scn = NULL;
3955 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3956 		idx = elf_ndxscn(scn);
3957 		sec_desc = &obj->efile.secs[idx];
3958 
3959 		sh = elf_sec_hdr(obj, scn);
3960 		if (!sh)
3961 			return -LIBBPF_ERRNO__FORMAT;
3962 
3963 		name = elf_sec_str(obj, sh->sh_name);
3964 		if (!name)
3965 			return -LIBBPF_ERRNO__FORMAT;
3966 
3967 		if (ignore_elf_section(sh, name))
3968 			continue;
3969 
3970 		data = elf_sec_data(obj, scn);
3971 		if (!data)
3972 			return -LIBBPF_ERRNO__FORMAT;
3973 
3974 		pr_debug("elf: section(%d) %s, size %lu, link %d, flags %lx, type=%d\n",
3975 			 idx, name, (unsigned long)data->d_size,
3976 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3977 			 (int)sh->sh_type);
3978 
3979 		if (strcmp(name, "license") == 0) {
3980 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3981 			if (err)
3982 				return err;
3983 		} else if (strcmp(name, "version") == 0) {
3984 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3985 			if (err)
3986 				return err;
3987 		} else if (strcmp(name, "maps") == 0) {
3988 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3989 			return -ENOTSUP;
3990 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3991 			obj->efile.btf_maps_shndx = idx;
3992 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3993 			if (sh->sh_type != SHT_PROGBITS)
3994 				return -LIBBPF_ERRNO__FORMAT;
3995 			btf_data = data;
3996 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3997 			if (sh->sh_type != SHT_PROGBITS)
3998 				return -LIBBPF_ERRNO__FORMAT;
3999 			btf_ext_data = data;
4000 		} else if (sh->sh_type == SHT_SYMTAB) {
4001 			/* already processed during the first pass above */
4002 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4003 			if (sh->sh_flags & SHF_EXECINSTR) {
4004 				if (strcmp(name, ".text") == 0)
4005 					obj->efile.text_shndx = idx;
4006 				err = bpf_object__add_programs(obj, data, name, idx);
4007 				if (err)
4008 					return err;
4009 			} else if (strcmp(name, DATA_SEC) == 0 ||
4010 				   str_has_pfx(name, DATA_SEC ".")) {
4011 				sec_desc->sec_type = SEC_DATA;
4012 				sec_desc->shdr = sh;
4013 				sec_desc->data = data;
4014 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4015 				   str_has_pfx(name, RODATA_SEC ".")) {
4016 				sec_desc->sec_type = SEC_RODATA;
4017 				sec_desc->shdr = sh;
4018 				sec_desc->data = data;
4019 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4020 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4021 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4022 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4023 				sec_desc->sec_type = SEC_ST_OPS;
4024 				sec_desc->shdr = sh;
4025 				sec_desc->data = data;
4026 				obj->efile.has_st_ops = true;
4027 			} else if (strcmp(name, ARENA_SEC) == 0) {
4028 				obj->efile.arena_data = data;
4029 				obj->efile.arena_data_shndx = idx;
4030 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4031 				obj->jumptables_data = malloc(data->d_size);
4032 				if (!obj->jumptables_data)
4033 					return -ENOMEM;
4034 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4035 				obj->jumptables_data_sz = data->d_size;
4036 				obj->efile.jumptables_data_shndx = idx;
4037 			} else {
4038 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4039 					idx, name);
4040 			}
4041 		} else if (sh->sh_type == SHT_REL) {
4042 			int targ_sec_idx = sh->sh_info; /* points to other section */
4043 
4044 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4045 			    targ_sec_idx >= obj->efile.sec_cnt)
4046 				return -LIBBPF_ERRNO__FORMAT;
4047 
4048 			/* Only do relo for section with exec instructions */
4049 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4050 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4051 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4052 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4053 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4054 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4055 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4056 					idx, name, targ_sec_idx,
4057 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4058 				continue;
4059 			}
4060 
4061 			sec_desc->sec_type = SEC_RELO;
4062 			sec_desc->shdr = sh;
4063 			sec_desc->data = data;
4064 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4065 							 str_has_pfx(name, BSS_SEC "."))) {
4066 			sec_desc->sec_type = SEC_BSS;
4067 			sec_desc->shdr = sh;
4068 			sec_desc->data = data;
4069 		} else {
4070 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4071 				(size_t)sh->sh_size);
4072 		}
4073 	}
4074 
4075 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4076 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4077 		return -LIBBPF_ERRNO__FORMAT;
4078 	}
4079 
4080 	/* change BPF program insns to native endianness for introspection */
4081 	if (!is_native_endianness(obj))
4082 		bpf_object_bswap_progs(obj);
4083 
4084 	/* sort BPF programs by section name and in-section instruction offset
4085 	 * for faster search
4086 	 */
4087 	if (obj->nr_programs)
4088 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4089 
4090 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4091 }
4092 
4093 static bool sym_is_extern(const Elf64_Sym *sym)
4094 {
4095 	int bind = ELF64_ST_BIND(sym->st_info);
4096 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4097 	return sym->st_shndx == SHN_UNDEF &&
4098 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4099 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4100 }
4101 
4102 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4103 {
4104 	int bind = ELF64_ST_BIND(sym->st_info);
4105 	int type = ELF64_ST_TYPE(sym->st_info);
4106 
4107 	/* in .text section */
4108 	if (sym->st_shndx != text_shndx)
4109 		return false;
4110 
4111 	/* local function */
4112 	if (bind == STB_LOCAL && type == STT_SECTION)
4113 		return true;
4114 
4115 	/* global function */
4116 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4117 }
4118 
4119 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4120 {
4121 	const struct btf_type *t;
4122 	const char *tname;
4123 	int i, n;
4124 
4125 	if (!btf)
4126 		return -ESRCH;
4127 
4128 	n = btf__type_cnt(btf);
4129 	for (i = 1; i < n; i++) {
4130 		t = btf__type_by_id(btf, i);
4131 
4132 		if (!btf_is_var(t) && !btf_is_func(t))
4133 			continue;
4134 
4135 		tname = btf__name_by_offset(btf, t->name_off);
4136 		if (strcmp(tname, ext_name))
4137 			continue;
4138 
4139 		if (btf_is_var(t) &&
4140 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4141 			return -EINVAL;
4142 
4143 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4144 			return -EINVAL;
4145 
4146 		return i;
4147 	}
4148 
4149 	return -ENOENT;
4150 }
4151 
4152 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4153 	const struct btf_var_secinfo *vs;
4154 	const struct btf_type *t;
4155 	int i, j, n;
4156 
4157 	if (!btf)
4158 		return -ESRCH;
4159 
4160 	n = btf__type_cnt(btf);
4161 	for (i = 1; i < n; i++) {
4162 		t = btf__type_by_id(btf, i);
4163 
4164 		if (!btf_is_datasec(t))
4165 			continue;
4166 
4167 		vs = btf_var_secinfos(t);
4168 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4169 			if (vs->type == ext_btf_id)
4170 				return i;
4171 		}
4172 	}
4173 
4174 	return -ENOENT;
4175 }
4176 
4177 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4178 				     bool *is_signed)
4179 {
4180 	const struct btf_type *t;
4181 	const char *name;
4182 
4183 	t = skip_mods_and_typedefs(btf, id, NULL);
4184 	name = btf__name_by_offset(btf, t->name_off);
4185 
4186 	if (is_signed)
4187 		*is_signed = false;
4188 	switch (btf_kind(t)) {
4189 	case BTF_KIND_INT: {
4190 		int enc = btf_int_encoding(t);
4191 
4192 		if (enc & BTF_INT_BOOL)
4193 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4194 		if (is_signed)
4195 			*is_signed = enc & BTF_INT_SIGNED;
4196 		if (t->size == 1)
4197 			return KCFG_CHAR;
4198 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4199 			return KCFG_UNKNOWN;
4200 		return KCFG_INT;
4201 	}
4202 	case BTF_KIND_ENUM:
4203 		if (t->size != 4)
4204 			return KCFG_UNKNOWN;
4205 		if (strcmp(name, "libbpf_tristate"))
4206 			return KCFG_UNKNOWN;
4207 		return KCFG_TRISTATE;
4208 	case BTF_KIND_ENUM64:
4209 		if (strcmp(name, "libbpf_tristate"))
4210 			return KCFG_UNKNOWN;
4211 		return KCFG_TRISTATE;
4212 	case BTF_KIND_ARRAY:
4213 		if (btf_array(t)->nelems == 0)
4214 			return KCFG_UNKNOWN;
4215 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4216 			return KCFG_UNKNOWN;
4217 		return KCFG_CHAR_ARR;
4218 	default:
4219 		return KCFG_UNKNOWN;
4220 	}
4221 }
4222 
4223 static int cmp_externs(const void *_a, const void *_b)
4224 {
4225 	const struct extern_desc *a = _a;
4226 	const struct extern_desc *b = _b;
4227 
4228 	if (a->type != b->type)
4229 		return a->type < b->type ? -1 : 1;
4230 
4231 	if (a->type == EXT_KCFG) {
4232 		/* descending order by alignment requirements */
4233 		if (a->kcfg.align != b->kcfg.align)
4234 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4235 		/* ascending order by size, within same alignment class */
4236 		if (a->kcfg.sz != b->kcfg.sz)
4237 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4238 	}
4239 
4240 	/* resolve ties by name */
4241 	return strcmp(a->name, b->name);
4242 }
4243 
4244 static int find_int_btf_id(const struct btf *btf)
4245 {
4246 	const struct btf_type *t;
4247 	int i, n;
4248 
4249 	n = btf__type_cnt(btf);
4250 	for (i = 1; i < n; i++) {
4251 		t = btf__type_by_id(btf, i);
4252 
4253 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4254 			return i;
4255 	}
4256 
4257 	return 0;
4258 }
4259 
4260 static int add_dummy_ksym_var(struct btf *btf)
4261 {
4262 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4263 	const struct btf_var_secinfo *vs;
4264 	const struct btf_type *sec;
4265 
4266 	if (!btf)
4267 		return 0;
4268 
4269 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4270 					    BTF_KIND_DATASEC);
4271 	if (sec_btf_id < 0)
4272 		return 0;
4273 
4274 	sec = btf__type_by_id(btf, sec_btf_id);
4275 	vs = btf_var_secinfos(sec);
4276 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4277 		const struct btf_type *vt;
4278 
4279 		vt = btf__type_by_id(btf, vs->type);
4280 		if (btf_is_func(vt))
4281 			break;
4282 	}
4283 
4284 	/* No func in ksyms sec.  No need to add dummy var. */
4285 	if (i == btf_vlen(sec))
4286 		return 0;
4287 
4288 	int_btf_id = find_int_btf_id(btf);
4289 	dummy_var_btf_id = btf__add_var(btf,
4290 					"dummy_ksym",
4291 					BTF_VAR_GLOBAL_ALLOCATED,
4292 					int_btf_id);
4293 	if (dummy_var_btf_id < 0)
4294 		pr_warn("cannot create a dummy_ksym var\n");
4295 
4296 	return dummy_var_btf_id;
4297 }
4298 
4299 static int bpf_object__collect_externs(struct bpf_object *obj)
4300 {
4301 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4302 	const struct btf_type *t;
4303 	struct extern_desc *ext;
4304 	int i, n, off, dummy_var_btf_id;
4305 	const char *ext_name, *sec_name;
4306 	size_t ext_essent_len;
4307 	Elf_Scn *scn;
4308 	Elf64_Shdr *sh;
4309 
4310 	if (!obj->efile.symbols)
4311 		return 0;
4312 
4313 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4314 	sh = elf_sec_hdr(obj, scn);
4315 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4316 		return -LIBBPF_ERRNO__FORMAT;
4317 
4318 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4319 	if (dummy_var_btf_id < 0)
4320 		return dummy_var_btf_id;
4321 
4322 	n = sh->sh_size / sh->sh_entsize;
4323 	pr_debug("looking for externs among %d symbols...\n", n);
4324 
4325 	for (i = 0; i < n; i++) {
4326 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4327 
4328 		if (!sym)
4329 			return -LIBBPF_ERRNO__FORMAT;
4330 		if (!sym_is_extern(sym))
4331 			continue;
4332 		ext_name = elf_sym_str(obj, sym->st_name);
4333 		if (str_is_empty(ext_name))
4334 			continue;
4335 
4336 		ext = obj->externs;
4337 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4338 		if (!ext)
4339 			return -ENOMEM;
4340 		obj->externs = ext;
4341 		ext = &ext[obj->nr_extern];
4342 		memset(ext, 0, sizeof(*ext));
4343 		obj->nr_extern++;
4344 
4345 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4346 		if (ext->btf_id <= 0) {
4347 			pr_warn("failed to find BTF for extern '%s': %d\n",
4348 				ext_name, ext->btf_id);
4349 			return ext->btf_id;
4350 		}
4351 		t = btf__type_by_id(obj->btf, ext->btf_id);
4352 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4353 		if (!ext->name)
4354 			return -ENOMEM;
4355 		ext->sym_idx = i;
4356 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4357 
4358 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4359 		ext->essent_name = NULL;
4360 		if (ext_essent_len != strlen(ext->name)) {
4361 			ext->essent_name = strndup(ext->name, ext_essent_len);
4362 			if (!ext->essent_name)
4363 				return -ENOMEM;
4364 		}
4365 
4366 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4367 		if (ext->sec_btf_id <= 0) {
4368 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4369 				ext_name, ext->btf_id, ext->sec_btf_id);
4370 			return ext->sec_btf_id;
4371 		}
4372 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4373 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4374 
4375 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4376 			if (btf_is_func(t)) {
4377 				pr_warn("extern function %s is unsupported under %s section\n",
4378 					ext->name, KCONFIG_SEC);
4379 				return -ENOTSUP;
4380 			}
4381 			kcfg_sec = sec;
4382 			ext->type = EXT_KCFG;
4383 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4384 			if (ext->kcfg.sz <= 0) {
4385 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4386 					ext_name, ext->kcfg.sz);
4387 				return ext->kcfg.sz;
4388 			}
4389 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4390 			if (ext->kcfg.align <= 0) {
4391 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4392 					ext_name, ext->kcfg.align);
4393 				return -EINVAL;
4394 			}
4395 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4396 							&ext->kcfg.is_signed);
4397 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4398 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4399 				return -ENOTSUP;
4400 			}
4401 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4402 			ksym_sec = sec;
4403 			ext->type = EXT_KSYM;
4404 			skip_mods_and_typedefs(obj->btf, t->type,
4405 					       &ext->ksym.type_id);
4406 		} else {
4407 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4408 			return -ENOTSUP;
4409 		}
4410 	}
4411 	pr_debug("collected %d externs total\n", obj->nr_extern);
4412 
4413 	if (!obj->nr_extern)
4414 		return 0;
4415 
4416 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4417 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4418 
4419 	/* for .ksyms section, we need to turn all externs into allocated
4420 	 * variables in BTF to pass kernel verification; we do this by
4421 	 * pretending that each extern is a 8-byte variable
4422 	 */
4423 	if (ksym_sec) {
4424 		/* find existing 4-byte integer type in BTF to use for fake
4425 		 * extern variables in DATASEC
4426 		 */
4427 		int int_btf_id = find_int_btf_id(obj->btf);
4428 		/* For extern function, a dummy_var added earlier
4429 		 * will be used to replace the vs->type and
4430 		 * its name string will be used to refill
4431 		 * the missing param's name.
4432 		 */
4433 		const struct btf_type *dummy_var;
4434 
4435 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4436 		for (i = 0; i < obj->nr_extern; i++) {
4437 			ext = &obj->externs[i];
4438 			if (ext->type != EXT_KSYM)
4439 				continue;
4440 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4441 				 i, ext->sym_idx, ext->name);
4442 		}
4443 
4444 		sec = ksym_sec;
4445 		n = btf_vlen(sec);
4446 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4447 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4448 			struct btf_type *vt;
4449 
4450 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4451 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4452 			ext = find_extern_by_name(obj, ext_name);
4453 			if (!ext) {
4454 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4455 					btf_kind_str(vt), ext_name);
4456 				return -ESRCH;
4457 			}
4458 			if (btf_is_func(vt)) {
4459 				const struct btf_type *func_proto;
4460 				struct btf_param *param;
4461 				int j;
4462 
4463 				func_proto = btf__type_by_id(obj->btf,
4464 							     vt->type);
4465 				param = btf_params(func_proto);
4466 				/* Reuse the dummy_var string if the
4467 				 * func proto does not have param name.
4468 				 */
4469 				for (j = 0; j < btf_vlen(func_proto); j++)
4470 					if (param[j].type && !param[j].name_off)
4471 						param[j].name_off =
4472 							dummy_var->name_off;
4473 				vs->type = dummy_var_btf_id;
4474 				vt->info &= ~0xffff;
4475 				vt->info |= BTF_FUNC_GLOBAL;
4476 			} else {
4477 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4478 				vt->type = int_btf_id;
4479 			}
4480 			vs->offset = off;
4481 			vs->size = sizeof(int);
4482 		}
4483 		sec->size = off;
4484 	}
4485 
4486 	if (kcfg_sec) {
4487 		sec = kcfg_sec;
4488 		/* for kcfg externs calculate their offsets within a .kconfig map */
4489 		off = 0;
4490 		for (i = 0; i < obj->nr_extern; i++) {
4491 			ext = &obj->externs[i];
4492 			if (ext->type != EXT_KCFG)
4493 				continue;
4494 
4495 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4496 			off = ext->kcfg.data_off + ext->kcfg.sz;
4497 			pr_debug("extern (kcfg) #%d: symbol %d, off %d, name %s\n",
4498 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4499 		}
4500 		sec->size = off;
4501 		n = btf_vlen(sec);
4502 		for (i = 0; i < n; i++) {
4503 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4504 
4505 			t = btf__type_by_id(obj->btf, vs->type);
4506 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4507 			ext = find_extern_by_name(obj, ext_name);
4508 			if (!ext) {
4509 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4510 					ext_name);
4511 				return -ESRCH;
4512 			}
4513 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4514 			vs->offset = ext->kcfg.data_off;
4515 		}
4516 	}
4517 	return 0;
4518 }
4519 
4520 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4521 {
4522 	return prog->sec_idx == obj->efile.text_shndx;
4523 }
4524 
4525 struct bpf_program *
4526 bpf_object__find_program_by_name(const struct bpf_object *obj,
4527 				 const char *name)
4528 {
4529 	struct bpf_program *prog;
4530 
4531 	bpf_object__for_each_program(prog, obj) {
4532 		if (prog_is_subprog(obj, prog))
4533 			continue;
4534 		if (!strcmp(prog->name, name))
4535 			return prog;
4536 	}
4537 	return errno = ENOENT, NULL;
4538 }
4539 
4540 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4541 				      int shndx)
4542 {
4543 	switch (obj->efile.secs[shndx].sec_type) {
4544 	case SEC_BSS:
4545 	case SEC_DATA:
4546 	case SEC_RODATA:
4547 		return true;
4548 	default:
4549 		return false;
4550 	}
4551 }
4552 
4553 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4554 				      int shndx)
4555 {
4556 	return shndx == obj->efile.btf_maps_shndx;
4557 }
4558 
4559 static enum libbpf_map_type
4560 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4561 {
4562 	if (shndx == obj->efile.symbols_shndx)
4563 		return LIBBPF_MAP_KCONFIG;
4564 
4565 	switch (obj->efile.secs[shndx].sec_type) {
4566 	case SEC_BSS:
4567 		return LIBBPF_MAP_BSS;
4568 	case SEC_DATA:
4569 		return LIBBPF_MAP_DATA;
4570 	case SEC_RODATA:
4571 		return LIBBPF_MAP_RODATA;
4572 	default:
4573 		return LIBBPF_MAP_UNSPEC;
4574 	}
4575 }
4576 
4577 static int bpf_prog_compute_hash(struct bpf_program *prog)
4578 {
4579 	struct bpf_insn *purged;
4580 	int i, err = 0;
4581 
4582 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4583 	if (!purged)
4584 		return -ENOMEM;
4585 
4586 	/* If relocations have been done, the map_fd needs to be
4587 	 * discarded for the digest calculation.
4588 	 */
4589 	for (i = 0; i < prog->insns_cnt; i++) {
4590 		purged[i] = prog->insns[i];
4591 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4592 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4593 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4594 			purged[i].imm = 0;
4595 			i++;
4596 			if (i >= prog->insns_cnt ||
4597 			    prog->insns[i].code != 0 ||
4598 			    prog->insns[i].dst_reg != 0 ||
4599 			    prog->insns[i].src_reg != 0 ||
4600 			    prog->insns[i].off != 0) {
4601 				err = -EINVAL;
4602 				goto out;
4603 			}
4604 			purged[i] = prog->insns[i];
4605 			purged[i].imm = 0;
4606 		}
4607 	}
4608 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4609 		      prog->hash);
4610 out:
4611 	free(purged);
4612 	return err;
4613 }
4614 
4615 static int bpf_program__record_reloc(struct bpf_program *prog,
4616 				     struct reloc_desc *reloc_desc,
4617 				     __u32 insn_idx, const char *sym_name,
4618 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4619 {
4620 	struct bpf_insn *insn = &prog->insns[insn_idx];
4621 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4622 	struct bpf_object *obj = prog->obj;
4623 	__u32 shdr_idx = sym->st_shndx;
4624 	enum libbpf_map_type type;
4625 	const char *sym_sec_name;
4626 	struct bpf_map *map;
4627 
4628 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4629 		pr_warn("prog '%s': invalid relo against '%s' for insns[%u].code 0x%x\n",
4630 			prog->name, sym_name, insn_idx, insn->code);
4631 		return -LIBBPF_ERRNO__RELOC;
4632 	}
4633 
4634 	if (sym_is_extern(sym)) {
4635 		int sym_idx = ELF64_R_SYM(rel->r_info);
4636 		int i, n = obj->nr_extern;
4637 		struct extern_desc *ext;
4638 
4639 		for (i = 0; i < n; i++) {
4640 			ext = &obj->externs[i];
4641 			if (ext->sym_idx == sym_idx)
4642 				break;
4643 		}
4644 		if (i >= n) {
4645 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4646 				prog->name, sym_name, sym_idx);
4647 			return -LIBBPF_ERRNO__RELOC;
4648 		}
4649 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4650 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4651 		if (insn->code == (BPF_JMP | BPF_CALL))
4652 			reloc_desc->type = RELO_EXTERN_CALL;
4653 		else
4654 			reloc_desc->type = RELO_EXTERN_LD64;
4655 		reloc_desc->insn_idx = insn_idx;
4656 		reloc_desc->ext_idx = i;
4657 		return 0;
4658 	}
4659 
4660 	/* sub-program call relocation */
4661 	if (is_call_insn(insn)) {
4662 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4663 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4664 			return -LIBBPF_ERRNO__RELOC;
4665 		}
4666 		/* text_shndx can be 0, if no default "main" program exists */
4667 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4668 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4669 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4670 				prog->name, sym_name, sym_sec_name);
4671 			return -LIBBPF_ERRNO__RELOC;
4672 		}
4673 		if (sym->st_value % BPF_INSN_SZ) {
4674 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4675 				prog->name, sym_name, (size_t)sym->st_value);
4676 			return -LIBBPF_ERRNO__RELOC;
4677 		}
4678 		reloc_desc->type = RELO_CALL;
4679 		reloc_desc->insn_idx = insn_idx;
4680 		reloc_desc->sym_off = sym->st_value;
4681 		return 0;
4682 	}
4683 
4684 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4685 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4686 			prog->name, sym_name, shdr_idx);
4687 		return -LIBBPF_ERRNO__RELOC;
4688 	}
4689 
4690 	/* loading subprog addresses */
4691 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4692 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4693 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4694 		 */
4695 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4696 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4697 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4698 			return -LIBBPF_ERRNO__RELOC;
4699 		}
4700 
4701 		reloc_desc->type = RELO_SUBPROG_ADDR;
4702 		reloc_desc->insn_idx = insn_idx;
4703 		reloc_desc->sym_off = sym->st_value;
4704 		return 0;
4705 	}
4706 
4707 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4708 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4709 
4710 	/* arena data relocation */
4711 	if (shdr_idx == obj->efile.arena_data_shndx) {
4712 		if (obj->arena_map_idx < 0) {
4713 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4714 				prog->name, insn_idx);
4715 			return -LIBBPF_ERRNO__RELOC;
4716 		}
4717 		reloc_desc->type = RELO_DATA;
4718 		reloc_desc->insn_idx = insn_idx;
4719 		reloc_desc->map_idx = obj->arena_map_idx;
4720 		reloc_desc->sym_off = sym->st_value;
4721 
4722 		map = &obj->maps[obj->arena_map_idx];
4723 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4724 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4725 			 map->sec_offset, insn_idx);
4726 		return 0;
4727 	}
4728 
4729 	/* jump table data relocation */
4730 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4731 		reloc_desc->type = RELO_INSN_ARRAY;
4732 		reloc_desc->insn_idx = insn_idx;
4733 		reloc_desc->map_idx = -1;
4734 		reloc_desc->sym_off = sym->st_value;
4735 		reloc_desc->sym_size = sym->st_size;
4736 		return 0;
4737 	}
4738 
4739 	/* generic map reference relocation */
4740 	if (type == LIBBPF_MAP_UNSPEC) {
4741 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4742 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4743 				prog->name, sym_name, sym_sec_name);
4744 			return -LIBBPF_ERRNO__RELOC;
4745 		}
4746 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4747 			map = &obj->maps[map_idx];
4748 			if (map->libbpf_type != type ||
4749 			    map->sec_idx != sym->st_shndx ||
4750 			    map->sec_offset != sym->st_value)
4751 				continue;
4752 			pr_debug("prog '%s': found map %zu (%s, sec %d, off %zu) for insn #%u\n",
4753 				 prog->name, map_idx, map->name, map->sec_idx,
4754 				 map->sec_offset, insn_idx);
4755 			break;
4756 		}
4757 		if (map_idx >= nr_maps) {
4758 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4759 				prog->name, sym_sec_name, (size_t)sym->st_value);
4760 			return -LIBBPF_ERRNO__RELOC;
4761 		}
4762 		reloc_desc->type = RELO_LD64;
4763 		reloc_desc->insn_idx = insn_idx;
4764 		reloc_desc->map_idx = map_idx;
4765 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4766 		return 0;
4767 	}
4768 
4769 	/* global data map relocation */
4770 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4771 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4772 			prog->name, sym_sec_name);
4773 		return -LIBBPF_ERRNO__RELOC;
4774 	}
4775 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4776 		map = &obj->maps[map_idx];
4777 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4778 			continue;
4779 		pr_debug("prog '%s': found data map %zu (%s, sec %d, off %zu) for insn %u\n",
4780 			 prog->name, map_idx, map->name, map->sec_idx,
4781 			 map->sec_offset, insn_idx);
4782 		break;
4783 	}
4784 	if (map_idx >= nr_maps) {
4785 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4786 			prog->name, sym_sec_name);
4787 		return -LIBBPF_ERRNO__RELOC;
4788 	}
4789 
4790 	reloc_desc->type = RELO_DATA;
4791 	reloc_desc->insn_idx = insn_idx;
4792 	reloc_desc->map_idx = map_idx;
4793 	reloc_desc->sym_off = sym->st_value;
4794 	return 0;
4795 }
4796 
4797 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4798 {
4799 	return insn_idx >= prog->sec_insn_off &&
4800 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4801 }
4802 
4803 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4804 						 size_t sec_idx, size_t insn_idx)
4805 {
4806 	int l = 0, r = obj->nr_programs - 1, m;
4807 	struct bpf_program *prog;
4808 
4809 	if (!obj->nr_programs)
4810 		return NULL;
4811 
4812 	while (l < r) {
4813 		m = l + (r - l + 1) / 2;
4814 		prog = &obj->programs[m];
4815 
4816 		if (prog->sec_idx < sec_idx ||
4817 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4818 			l = m;
4819 		else
4820 			r = m - 1;
4821 	}
4822 	/* matching program could be at index l, but it still might be the
4823 	 * wrong one, so we need to double check conditions for the last time
4824 	 */
4825 	prog = &obj->programs[l];
4826 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4827 		return prog;
4828 	return NULL;
4829 }
4830 
4831 static int
4832 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4833 {
4834 	const char *relo_sec_name, *sec_name;
4835 	size_t sec_idx = shdr->sh_info, sym_idx;
4836 	struct bpf_program *prog;
4837 	struct reloc_desc *relos;
4838 	int err, i, nrels;
4839 	const char *sym_name;
4840 	__u32 insn_idx;
4841 	Elf_Scn *scn;
4842 	Elf_Data *scn_data;
4843 	Elf64_Sym *sym;
4844 	Elf64_Rel *rel;
4845 
4846 	if (sec_idx >= obj->efile.sec_cnt)
4847 		return -EINVAL;
4848 
4849 	scn = elf_sec_by_idx(obj, sec_idx);
4850 	scn_data = elf_sec_data(obj, scn);
4851 	if (!scn_data)
4852 		return -LIBBPF_ERRNO__FORMAT;
4853 
4854 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4855 	sec_name = elf_sec_name(obj, scn);
4856 	if (!relo_sec_name || !sec_name)
4857 		return -EINVAL;
4858 
4859 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4860 		 relo_sec_name, sec_idx, sec_name);
4861 	nrels = shdr->sh_size / shdr->sh_entsize;
4862 
4863 	for (i = 0; i < nrels; i++) {
4864 		rel = elf_rel_by_idx(data, i);
4865 		if (!rel) {
4866 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4867 			return -LIBBPF_ERRNO__FORMAT;
4868 		}
4869 
4870 		sym_idx = ELF64_R_SYM(rel->r_info);
4871 		sym = elf_sym_by_idx(obj, sym_idx);
4872 		if (!sym) {
4873 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4874 				relo_sec_name, sym_idx, i);
4875 			return -LIBBPF_ERRNO__FORMAT;
4876 		}
4877 
4878 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4879 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4880 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4881 			return -LIBBPF_ERRNO__FORMAT;
4882 		}
4883 
4884 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4885 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4886 				relo_sec_name, (size_t)rel->r_offset, i);
4887 			return -LIBBPF_ERRNO__FORMAT;
4888 		}
4889 
4890 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4891 		/* relocations against static functions are recorded as
4892 		 * relocations against the section that contains a function;
4893 		 * in such case, symbol will be STT_SECTION and sym.st_name
4894 		 * will point to empty string (0), so fetch section name
4895 		 * instead
4896 		 */
4897 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4898 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4899 		else
4900 			sym_name = elf_sym_str(obj, sym->st_name);
4901 		sym_name = sym_name ?: "<?";
4902 
4903 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4904 			 relo_sec_name, i, insn_idx, sym_name);
4905 
4906 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4907 		if (!prog) {
4908 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4909 				relo_sec_name, i, sec_name, insn_idx);
4910 			continue;
4911 		}
4912 
4913 		relos = libbpf_reallocarray(prog->reloc_desc,
4914 					    prog->nr_reloc + 1, sizeof(*relos));
4915 		if (!relos)
4916 			return -ENOMEM;
4917 		prog->reloc_desc = relos;
4918 
4919 		/* adjust insn_idx to local BPF program frame of reference */
4920 		insn_idx -= prog->sec_insn_off;
4921 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4922 						insn_idx, sym_name, sym, rel);
4923 		if (err)
4924 			return err;
4925 
4926 		prog->nr_reloc++;
4927 	}
4928 	return 0;
4929 }
4930 
4931 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4932 {
4933 	int id;
4934 
4935 	if (!obj->btf)
4936 		return -ENOENT;
4937 
4938 	/* if it's BTF-defined map, we don't need to search for type IDs.
4939 	 * For struct_ops map, it does not need btf_key_type_id and
4940 	 * btf_value_type_id.
4941 	 */
4942 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4943 		return 0;
4944 
4945 	/*
4946 	 * LLVM annotates global data differently in BTF, that is,
4947 	 * only as '.data', '.bss' or '.rodata'.
4948 	 */
4949 	if (!bpf_map__is_internal(map))
4950 		return -ENOENT;
4951 
4952 	id = btf__find_by_name(obj->btf, map->real_name);
4953 	if (id < 0)
4954 		return id;
4955 
4956 	map->btf_key_type_id = 0;
4957 	map->btf_value_type_id = id;
4958 	return 0;
4959 }
4960 
4961 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4962 {
4963 	char file[PATH_MAX], buff[4096];
4964 	FILE *fp;
4965 	__u32 val;
4966 	int err;
4967 
4968 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4969 	memset(info, 0, sizeof(*info));
4970 
4971 	fp = fopen(file, "re");
4972 	if (!fp) {
4973 		err = -errno;
4974 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4975 			errstr(err));
4976 		return err;
4977 	}
4978 
4979 	while (fgets(buff, sizeof(buff), fp)) {
4980 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4981 			info->type = val;
4982 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4983 			info->key_size = val;
4984 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4985 			info->value_size = val;
4986 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4987 			info->max_entries = val;
4988 		else if (sscanf(buff, "map_flags:\t%x", &val) == 1)
4989 			info->map_flags = val;
4990 	}
4991 
4992 	fclose(fp);
4993 
4994 	return 0;
4995 }
4996 
4997 static bool map_is_created(const struct bpf_map *map)
4998 {
4999 	return map->obj->state >= OBJ_PREPARED || map->reused;
5000 }
5001 
5002 bool bpf_map__autocreate(const struct bpf_map *map)
5003 {
5004 	return map->autocreate;
5005 }
5006 
5007 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5008 {
5009 	if (map_is_created(map))
5010 		return libbpf_err(-EBUSY);
5011 
5012 	map->autocreate = autocreate;
5013 	return 0;
5014 }
5015 
5016 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5017 {
5018 	if (!bpf_map__is_struct_ops(map))
5019 		return libbpf_err(-EINVAL);
5020 
5021 	map->autoattach = autoattach;
5022 	return 0;
5023 }
5024 
5025 bool bpf_map__autoattach(const struct bpf_map *map)
5026 {
5027 	return map->autoattach;
5028 }
5029 
5030 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5031 {
5032 	struct bpf_map_info info;
5033 	__u32 len = sizeof(info), name_len;
5034 	int new_fd, err;
5035 	char *new_name;
5036 
5037 	memset(&info, 0, len);
5038 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5039 	if (err && errno == EINVAL)
5040 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5041 	if (err)
5042 		return libbpf_err(err);
5043 
5044 	name_len = strlen(info.name);
5045 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5046 		new_name = strdup(map->name);
5047 	else
5048 		new_name = strdup(info.name);
5049 
5050 	if (!new_name)
5051 		return libbpf_err(-errno);
5052 
5053 	/*
5054 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5055 	 * This is similar to what we do in ensure_good_fd(), but without
5056 	 * closing original FD.
5057 	 */
5058 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5059 	if (new_fd < 0) {
5060 		err = -errno;
5061 		goto err_free_new_name;
5062 	}
5063 
5064 	err = reuse_fd(map->fd, new_fd);
5065 	if (err)
5066 		goto err_free_new_name;
5067 
5068 	free(map->name);
5069 
5070 	map->name = new_name;
5071 	map->def.type = info.type;
5072 	map->def.key_size = info.key_size;
5073 	map->def.value_size = info.value_size;
5074 	map->def.max_entries = info.max_entries;
5075 	map->def.map_flags = info.map_flags;
5076 	map->btf_key_type_id = info.btf_key_type_id;
5077 	map->btf_value_type_id = info.btf_value_type_id;
5078 	map->reused = true;
5079 	map->map_extra = info.map_extra;
5080 
5081 	return 0;
5082 
5083 err_free_new_name:
5084 	free(new_name);
5085 	return libbpf_err(err);
5086 }
5087 
5088 __u32 bpf_map__max_entries(const struct bpf_map *map)
5089 {
5090 	return map->def.max_entries;
5091 }
5092 
5093 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5094 {
5095 	if (!bpf_map_type__is_map_in_map(map->def.type))
5096 		return errno = EINVAL, NULL;
5097 
5098 	return map->inner_map;
5099 }
5100 
5101 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5102 {
5103 	if (map_is_created(map))
5104 		return libbpf_err(-EBUSY);
5105 
5106 	map->def.max_entries = max_entries;
5107 
5108 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5109 	if (map_is_ringbuf(map))
5110 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5111 
5112 	return 0;
5113 }
5114 
5115 static int bpf_object_prepare_token(struct bpf_object *obj)
5116 {
5117 	const char *bpffs_path;
5118 	int bpffs_fd = -1, token_fd, err;
5119 	bool mandatory;
5120 	enum libbpf_print_level level;
5121 
5122 	/* token is explicitly prevented */
5123 	if (obj->token_path && obj->token_path[0] == '\0') {
5124 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5125 		return 0;
5126 	}
5127 
5128 	mandatory = obj->token_path != NULL;
5129 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5130 
5131 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5132 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5133 	if (bpffs_fd < 0) {
5134 		err = -errno;
5135 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5136 		     obj->name, errstr(err), bpffs_path,
5137 		     mandatory ? "" : ", skipping optional step...");
5138 		return mandatory ? err : 0;
5139 	}
5140 
5141 	token_fd = bpf_token_create(bpffs_fd, 0);
5142 	close(bpffs_fd);
5143 	if (token_fd < 0) {
5144 		if (!mandatory && token_fd == -ENOENT) {
5145 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5146 				 obj->name, bpffs_path);
5147 			return 0;
5148 		}
5149 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5150 		     obj->name, token_fd, bpffs_path,
5151 		     mandatory ? "" : ", skipping optional step...");
5152 		return mandatory ? token_fd : 0;
5153 	}
5154 
5155 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5156 	if (!obj->feat_cache) {
5157 		close(token_fd);
5158 		return -ENOMEM;
5159 	}
5160 
5161 	obj->token_fd = token_fd;
5162 	obj->feat_cache->token_fd = token_fd;
5163 
5164 	return 0;
5165 }
5166 
5167 static int
5168 bpf_object__probe_loading(struct bpf_object *obj)
5169 {
5170 	struct bpf_insn insns[] = {
5171 		BPF_MOV64_IMM(BPF_REG_0, 0),
5172 		BPF_EXIT_INSN(),
5173 	};
5174 	int ret, insn_cnt = ARRAY_SIZE(insns);
5175 
5176 	if (obj->gen_loader || obj->token_fd)
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, NULL);
5186 	if (ret < 0)
5187 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
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 [%u] 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 [%u] 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 [%u] 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 [%u] 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 [%u] %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 #%u 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 #%u 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 #%u: %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 [%u] %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 %u 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 #%d: %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 %zu, trying to access %u\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 				(unsigned 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 %u\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 %u\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 %zu rel->r_offset %zu name %u ('%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 [%u] 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 static inline bool is_tracing_multi(enum bpf_attach_type type)
7772 {
7773 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
7774 	       type == BPF_TRACE_FSESSION_MULTI;
7775 }
7776 
7777 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
7778 {
7779 	const char *sep, *mod_name = NULL;
7780 	int i, mod_len, err;
7781 
7782 	/*
7783 	 * We expect attach string in the form of either
7784 	 * - function_pattern or
7785 	 * - <module>:function_pattern
7786 	 */
7787 	sep = strchr(attach, ':');
7788 	if (sep) {
7789 		mod_name = attach;
7790 		mod_len = sep - mod_name;
7791 	}
7792 	if (!mod_name)
7793 		return NULL;
7794 
7795 	err = load_module_btfs(obj);
7796 	if (err)
7797 		return NULL;
7798 
7799 	for (i = 0; i < obj->btf_module_cnt; i++) {
7800 		const struct module_btf *mod = &obj->btf_modules[i];
7801 
7802 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
7803 			return mod;
7804 	}
7805 	return NULL;
7806 }
7807 
7808 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
7809 {
7810 	const char *attach_name, *sep;
7811 	const struct module_btf *mod;
7812 
7813 	*btf_obj_fd = 0;
7814 	attach_name = strchr(prog->sec_name, '/');
7815 
7816 	/* Program with no details in spec, using kernel btf. */
7817 	if (!attach_name)
7818 		return 0;
7819 
7820 	/* Program with no module section, using kernel btf. */
7821 	sep = strchr(++attach_name, ':');
7822 	if (!sep)
7823 		return 0;
7824 
7825 	/* Program with module specified, get its btf fd. */
7826 	mod = find_attach_module(prog->obj, attach_name);
7827 	if (!mod)
7828 		return -EINVAL;
7829 
7830 	*btf_obj_fd = mod->fd;
7831 	return 0;
7832 }
7833 
7834 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7835 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7836 				    struct bpf_prog_load_opts *opts, long cookie)
7837 {
7838 	enum sec_def_flags def = cookie;
7839 
7840 	/* old kernels might not support specifying expected_attach_type */
7841 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7842 		opts->expected_attach_type = 0;
7843 
7844 	if (def & SEC_SLEEPABLE)
7845 		opts->prog_flags |= BPF_F_SLEEPABLE;
7846 
7847 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7848 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7849 
7850 	/* special check for usdt to use uprobe_multi link */
7851 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7852 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7853 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7854 		 * update both.
7855 		 */
7856 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7857 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7858 	}
7859 
7860 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7861 		int btf_obj_fd = 0, btf_type_id = 0, err;
7862 		const char *attach_name;
7863 
7864 		attach_name = strchr(prog->sec_name, '/');
7865 		if (!attach_name) {
7866 			/* if BPF program is annotated with just SEC("fentry")
7867 			 * (or similar) without declaratively specifying
7868 			 * target, then it is expected that target will be
7869 			 * specified with bpf_program__set_attach_target() at
7870 			 * runtime before BPF object load step. If not, then
7871 			 * there is nothing to load into the kernel as BPF
7872 			 * verifier won't be able to validate BPF program
7873 			 * correctness anyways.
7874 			 */
7875 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7876 				prog->name);
7877 			return -EINVAL;
7878 		}
7879 		attach_name++; /* skip over / */
7880 
7881 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7882 		if (err)
7883 			return err;
7884 
7885 		/* cache resolved BTF FD and BTF type ID in the prog */
7886 		prog->attach_btf_obj_fd = btf_obj_fd;
7887 		prog->attach_btf_id = btf_type_id;
7888 
7889 		/* but by now libbpf common logic is not utilizing
7890 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7891 		 * this callback is called after opts were populated by
7892 		 * libbpf, so this callback has to update opts explicitly here
7893 		 */
7894 		opts->attach_btf_obj_fd = btf_obj_fd;
7895 		opts->attach_btf_id = btf_type_id;
7896 	}
7897 
7898 	if (is_tracing_multi(prog->expected_attach_type)) {
7899 		int err, btf_obj_fd = 0;
7900 
7901 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
7902 		if (err < 0)
7903 			return err;
7904 
7905 		prog->attach_btf_obj_fd = btf_obj_fd;
7906 		opts->attach_btf_obj_fd = btf_obj_fd;
7907 	}
7908 
7909 	return 0;
7910 }
7911 
7912 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7913 
7914 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7915 				struct bpf_insn *insns, int insns_cnt,
7916 				const char *license, __u32 kern_version, int *prog_fd)
7917 {
7918 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7919 	const char *prog_name = NULL;
7920 	size_t log_buf_size = 0;
7921 	char *log_buf = NULL, *tmp;
7922 	bool own_log_buf = true;
7923 	__u32 log_level = prog->log_level;
7924 	int ret, err;
7925 
7926 	/* Be more helpful by rejecting programs that can't be validated early
7927 	 * with more meaningful and actionable error message.
7928 	 */
7929 	switch (prog->type) {
7930 	case BPF_PROG_TYPE_UNSPEC:
7931 		/*
7932 		 * The program type must be set.  Most likely we couldn't find a proper
7933 		 * section definition at load time, and thus we didn't infer the type.
7934 		 */
7935 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7936 			prog->name, prog->sec_name);
7937 		return -EINVAL;
7938 	case BPF_PROG_TYPE_STRUCT_OPS:
7939 		if (prog->attach_btf_id == 0) {
7940 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7941 				prog->name);
7942 			return -EINVAL;
7943 		}
7944 		break;
7945 	default:
7946 		break;
7947 	}
7948 
7949 	if (!insns || !insns_cnt)
7950 		return -EINVAL;
7951 
7952 	if (kernel_supports(obj, FEAT_PROG_NAME))
7953 		prog_name = prog->name;
7954 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7955 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7956 	load_attr.attach_btf_id = prog->attach_btf_id;
7957 	load_attr.kern_version = kern_version;
7958 	load_attr.prog_ifindex = prog->prog_ifindex;
7959 	load_attr.expected_attach_type = prog->expected_attach_type;
7960 
7961 	/* specify func_info/line_info only if kernel supports them */
7962 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7963 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7964 		load_attr.func_info = prog->func_info;
7965 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7966 		load_attr.func_info_cnt = prog->func_info_cnt;
7967 		load_attr.line_info = prog->line_info;
7968 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7969 		load_attr.line_info_cnt = prog->line_info_cnt;
7970 	}
7971 	load_attr.log_level = log_level;
7972 	load_attr.prog_flags = prog->prog_flags;
7973 	load_attr.fd_array = obj->fd_array;
7974 
7975 	load_attr.token_fd = obj->token_fd;
7976 	if (obj->token_fd)
7977 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7978 
7979 	/* adjust load_attr if sec_def provides custom preload callback */
7980 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7981 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7982 		if (err < 0) {
7983 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7984 				prog->name, errstr(err));
7985 			return err;
7986 		}
7987 		insns = prog->insns;
7988 		insns_cnt = prog->insns_cnt;
7989 	}
7990 
7991 	if (obj->gen_loader) {
7992 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7993 				   license, insns, insns_cnt, &load_attr,
7994 				   prog - obj->programs);
7995 		*prog_fd = -1;
7996 		return 0;
7997 	}
7998 
7999 retry_load:
8000 	/* if log_level is zero, we don't request logs initially even if
8001 	 * custom log_buf is specified; if the program load fails, then we'll
8002 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8003 	 * our own and retry the load to get details on what failed
8004 	 */
8005 	if (log_level) {
8006 		if (prog->log_buf) {
8007 			log_buf = prog->log_buf;
8008 			log_buf_size = prog->log_size;
8009 			own_log_buf = false;
8010 		} else if (obj->log_buf) {
8011 			log_buf = obj->log_buf;
8012 			log_buf_size = obj->log_size;
8013 			own_log_buf = false;
8014 		} else {
8015 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8016 			tmp = realloc(log_buf, log_buf_size);
8017 			if (!tmp) {
8018 				ret = -ENOMEM;
8019 				goto out;
8020 			}
8021 			log_buf = tmp;
8022 			log_buf[0] = '\0';
8023 			own_log_buf = true;
8024 		}
8025 	}
8026 
8027 	load_attr.log_buf = log_buf;
8028 	load_attr.log_size = log_buf_size;
8029 	load_attr.log_level = log_level;
8030 
8031 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8032 	if (ret >= 0) {
8033 		if (log_level && own_log_buf) {
8034 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8035 				 prog->name, log_buf);
8036 		}
8037 
8038 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8039 			struct bpf_map *map;
8040 			int i;
8041 
8042 			for (i = 0; i < obj->nr_maps; i++) {
8043 				map = &prog->obj->maps[i];
8044 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
8045 					continue;
8046 
8047 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8048 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8049 						prog->name, map->real_name, errstr(errno));
8050 					/* Don't fail hard if can't bind rodata. */
8051 				}
8052 			}
8053 		}
8054 
8055 		*prog_fd = ret;
8056 		ret = 0;
8057 		goto out;
8058 	}
8059 
8060 	if (log_level == 0) {
8061 		log_level = 1;
8062 		goto retry_load;
8063 	}
8064 	/* On ENOSPC, increase log buffer size and retry, unless custom
8065 	 * log_buf is specified.
8066 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
8067 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
8068 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
8069 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
8070 	 */
8071 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
8072 		goto retry_load;
8073 
8074 	ret = -errno;
8075 
8076 	/* post-process verifier log to improve error descriptions */
8077 	fixup_verifier_log(prog, log_buf, log_buf_size);
8078 
8079 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8080 	pr_perm_msg(ret);
8081 
8082 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8083 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8084 			prog->name, log_buf);
8085 	}
8086 
8087 out:
8088 	if (own_log_buf)
8089 		free(log_buf);
8090 	return ret;
8091 }
8092 
8093 static char *find_prev_line(char *buf, char *cur)
8094 {
8095 	char *p;
8096 
8097 	if (cur == buf) /* end of a log buf */
8098 		return NULL;
8099 
8100 	p = cur - 1;
8101 	while (p - 1 >= buf && *(p - 1) != '\n')
8102 		p--;
8103 
8104 	return p;
8105 }
8106 
8107 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8108 		      char *orig, size_t orig_sz, const char *patch)
8109 {
8110 	/* size of the remaining log content to the right from the to-be-replaced part */
8111 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8112 	size_t patch_sz = strlen(patch);
8113 
8114 	if (patch_sz != orig_sz) {
8115 		/* If patch line(s) are longer than original piece of verifier log,
8116 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8117 		 * starting from after to-be-replaced part of the log.
8118 		 *
8119 		 * If patch line(s) are shorter than original piece of verifier log,
8120 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8121 		 * starting from after to-be-replaced part of the log
8122 		 *
8123 		 * We need to be careful about not overflowing available
8124 		 * buf_sz capacity. If that's the case, we'll truncate the end
8125 		 * of the original log, as necessary.
8126 		 */
8127 		if (patch_sz > orig_sz) {
8128 			if (orig + patch_sz >= buf + buf_sz) {
8129 				/* patch is big enough to cover remaining space completely */
8130 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8131 				rem_sz = 0;
8132 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8133 				/* patch causes part of remaining log to be truncated */
8134 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8135 			}
8136 		}
8137 		/* shift remaining log to the right by calculated amount */
8138 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8139 	}
8140 
8141 	memcpy(orig, patch, patch_sz);
8142 }
8143 
8144 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8145 				       char *buf, size_t buf_sz, size_t log_sz,
8146 				       char *line1, char *line2, char *line3)
8147 {
8148 	/* Expected log for failed and not properly guarded CO-RE relocation:
8149 	 * line1 -> 123: (85) call unknown#195896080
8150 	 * line2 -> invalid func unknown#195896080
8151 	 * line3 -> <anything else or end of buffer>
8152 	 *
8153 	 * "123" is the index of the instruction that was poisoned. We extract
8154 	 * instruction index to find corresponding CO-RE relocation and
8155 	 * replace this part of the log with more relevant information about
8156 	 * failed CO-RE relocation.
8157 	 */
8158 	const struct bpf_core_relo *relo;
8159 	struct bpf_core_spec spec;
8160 	char patch[512], spec_buf[256];
8161 	int insn_idx, err, spec_len;
8162 
8163 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8164 		return;
8165 
8166 	relo = find_relo_core(prog, insn_idx);
8167 	if (!relo)
8168 		return;
8169 
8170 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8171 	if (err)
8172 		return;
8173 
8174 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8175 	snprintf(patch, sizeof(patch),
8176 		 "%d: <invalid CO-RE relocation>\n"
8177 		 "failed to resolve CO-RE relocation %s%s\n",
8178 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8179 
8180 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8181 }
8182 
8183 static void fixup_log_missing_map_load(struct bpf_program *prog,
8184 				       char *buf, size_t buf_sz, size_t log_sz,
8185 				       char *line1, char *line2, char *line3)
8186 {
8187 	/* Expected log for failed and not properly guarded map reference:
8188 	 * line1 -> 123: (85) call unknown#2001000345
8189 	 * line2 -> invalid func unknown#2001000345
8190 	 * line3 -> <anything else or end of buffer>
8191 	 *
8192 	 * "123" is the index of the instruction that was poisoned.
8193 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8194 	 */
8195 	struct bpf_object *obj = prog->obj;
8196 	const struct bpf_map *map;
8197 	int insn_idx, map_idx;
8198 	char patch[128];
8199 
8200 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8201 		return;
8202 
8203 	map_idx -= POISON_LDIMM64_MAP_BASE;
8204 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8205 		return;
8206 	map = &obj->maps[map_idx];
8207 
8208 	snprintf(patch, sizeof(patch),
8209 		 "%d: <invalid BPF map reference>\n"
8210 		 "BPF map '%s' is referenced but wasn't created\n",
8211 		 insn_idx, map->name);
8212 
8213 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8214 }
8215 
8216 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8217 					 char *buf, size_t buf_sz, size_t log_sz,
8218 					 char *line1, char *line2, char *line3)
8219 {
8220 	/* Expected log for failed and not properly guarded kfunc call:
8221 	 * line1 -> 123: (85) call unknown#2002000345
8222 	 * line2 -> invalid func unknown#2002000345
8223 	 * line3 -> <anything else or end of buffer>
8224 	 *
8225 	 * "123" is the index of the instruction that was poisoned.
8226 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8227 	 */
8228 	struct bpf_object *obj = prog->obj;
8229 	const struct extern_desc *ext;
8230 	int insn_idx, ext_idx;
8231 	char patch[128];
8232 
8233 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8234 		return;
8235 
8236 	ext_idx -= POISON_CALL_KFUNC_BASE;
8237 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8238 		return;
8239 	ext = &obj->externs[ext_idx];
8240 
8241 	snprintf(patch, sizeof(patch),
8242 		 "%d: <invalid kfunc call>\n"
8243 		 "kfunc '%s' is referenced but wasn't resolved\n",
8244 		 insn_idx, ext->name);
8245 
8246 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8247 }
8248 
8249 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8250 {
8251 	/* look for familiar error patterns in last N lines of the log */
8252 	const size_t max_last_line_cnt = 10;
8253 	char *prev_line, *cur_line, *next_line;
8254 	size_t log_sz;
8255 	int i;
8256 
8257 	if (!buf)
8258 		return;
8259 
8260 	log_sz = strlen(buf) + 1;
8261 	next_line = buf + log_sz - 1;
8262 
8263 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8264 		cur_line = find_prev_line(buf, next_line);
8265 		if (!cur_line)
8266 			return;
8267 
8268 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8269 			prev_line = find_prev_line(buf, cur_line);
8270 			if (!prev_line)
8271 				continue;
8272 
8273 			/* failed CO-RE relocation case */
8274 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8275 						   prev_line, cur_line, next_line);
8276 			return;
8277 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8278 			prev_line = find_prev_line(buf, cur_line);
8279 			if (!prev_line)
8280 				continue;
8281 
8282 			/* reference to uncreated BPF map */
8283 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8284 						   prev_line, cur_line, next_line);
8285 			return;
8286 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8287 			prev_line = find_prev_line(buf, cur_line);
8288 			if (!prev_line)
8289 				continue;
8290 
8291 			/* reference to unresolved kfunc */
8292 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8293 						     prev_line, cur_line, next_line);
8294 			return;
8295 		}
8296 	}
8297 }
8298 
8299 static int bpf_program_record_relos(struct bpf_program *prog)
8300 {
8301 	struct bpf_object *obj = prog->obj;
8302 	int i;
8303 
8304 	for (i = 0; i < prog->nr_reloc; i++) {
8305 		struct reloc_desc *relo = &prog->reloc_desc[i];
8306 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8307 		int kind;
8308 
8309 		switch (relo->type) {
8310 		case RELO_EXTERN_LD64:
8311 			if (ext->type != EXT_KSYM)
8312 				continue;
8313 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8314 				BTF_KIND_VAR : BTF_KIND_FUNC;
8315 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8316 					       ext->is_weak, !ext->ksym.type_id,
8317 					       true, kind, relo->insn_idx);
8318 			break;
8319 		case RELO_EXTERN_CALL:
8320 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8321 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8322 					       relo->insn_idx);
8323 			break;
8324 		case RELO_CORE: {
8325 			struct bpf_core_relo cr = {
8326 				.insn_off = relo->insn_idx * 8,
8327 				.type_id = relo->core_relo->type_id,
8328 				.access_str_off = relo->core_relo->access_str_off,
8329 				.kind = relo->core_relo->kind,
8330 			};
8331 
8332 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8333 			break;
8334 		}
8335 		default:
8336 			continue;
8337 		}
8338 	}
8339 	return 0;
8340 }
8341 
8342 static int
8343 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8344 {
8345 	struct bpf_program *prog;
8346 	size_t i;
8347 	int err;
8348 
8349 	for (i = 0; i < obj->nr_programs; i++) {
8350 		prog = &obj->programs[i];
8351 		if (prog_is_subprog(obj, prog))
8352 			continue;
8353 		if (!prog->autoload) {
8354 			pr_debug("prog '%s': skipped loading\n", prog->name);
8355 			continue;
8356 		}
8357 		prog->log_level |= log_level;
8358 
8359 		if (obj->gen_loader)
8360 			bpf_program_record_relos(prog);
8361 
8362 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8363 					   obj->license, obj->kern_version, &prog->fd);
8364 		if (err) {
8365 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8366 			return err;
8367 		}
8368 	}
8369 
8370 	bpf_object__free_relocs(obj);
8371 	return 0;
8372 }
8373 
8374 static int bpf_object_prepare_progs(struct bpf_object *obj)
8375 {
8376 	struct bpf_program *prog;
8377 	size_t i;
8378 	int err;
8379 
8380 	for (i = 0; i < obj->nr_programs; i++) {
8381 		prog = &obj->programs[i];
8382 		err = bpf_object__sanitize_prog(obj, prog);
8383 		if (err)
8384 			return err;
8385 	}
8386 	return 0;
8387 }
8388 
8389 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8390 
8391 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8392 {
8393 	struct bpf_program *prog;
8394 	int err;
8395 
8396 	bpf_object__for_each_program(prog, obj) {
8397 		prog->sec_def = find_sec_def(prog->sec_name);
8398 		if (!prog->sec_def) {
8399 			/* couldn't guess, but user might manually specify */
8400 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8401 				prog->name, prog->sec_name);
8402 			continue;
8403 		}
8404 
8405 		prog->type = prog->sec_def->prog_type;
8406 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8407 
8408 		/* sec_def can have custom callback which should be called
8409 		 * after bpf_program is initialized to adjust its properties
8410 		 */
8411 		if (prog->sec_def->prog_setup_fn) {
8412 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8413 			if (err < 0) {
8414 				pr_warn("prog '%s': failed to initialize: %s\n",
8415 					prog->name, errstr(err));
8416 				return err;
8417 			}
8418 		}
8419 	}
8420 
8421 	return 0;
8422 }
8423 
8424 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8425 					  const char *obj_name,
8426 					  const struct bpf_object_open_opts *opts)
8427 {
8428 	const char *kconfig, *btf_tmp_path, *token_path;
8429 	struct bpf_object *obj;
8430 	int err;
8431 	char *log_buf;
8432 	size_t log_size;
8433 	__u32 log_level;
8434 
8435 	if (obj_buf && !obj_name)
8436 		return ERR_PTR(-EINVAL);
8437 
8438 	if (elf_version(EV_CURRENT) == EV_NONE) {
8439 		pr_warn("failed to init libelf for %s\n",
8440 			path ? : "(mem buf)");
8441 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8442 	}
8443 
8444 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8445 		return ERR_PTR(-EINVAL);
8446 
8447 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8448 	if (obj_buf) {
8449 		path = obj_name;
8450 		pr_debug("loading object '%s' from buffer\n", obj_name);
8451 	} else {
8452 		pr_debug("loading object from %s\n", path);
8453 	}
8454 
8455 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8456 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8457 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8458 	if (log_size > UINT_MAX)
8459 		return ERR_PTR(-EINVAL);
8460 	if (log_size && !log_buf)
8461 		return ERR_PTR(-EINVAL);
8462 
8463 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8464 	/* if user didn't specify bpf_token_path explicitly, check if
8465 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8466 	 * option
8467 	 */
8468 	if (!token_path)
8469 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8470 	if (token_path && strlen(token_path) >= PATH_MAX)
8471 		return ERR_PTR(-ENAMETOOLONG);
8472 
8473 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8474 	if (IS_ERR(obj))
8475 		return obj;
8476 
8477 	obj->log_buf = log_buf;
8478 	obj->log_size = log_size;
8479 	obj->log_level = log_level;
8480 
8481 	if (token_path) {
8482 		obj->token_path = strdup(token_path);
8483 		if (!obj->token_path) {
8484 			err = -ENOMEM;
8485 			goto out;
8486 		}
8487 	}
8488 
8489 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8490 	if (btf_tmp_path) {
8491 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8492 			err = -ENAMETOOLONG;
8493 			goto out;
8494 		}
8495 		obj->btf_custom_path = strdup(btf_tmp_path);
8496 		if (!obj->btf_custom_path) {
8497 			err = -ENOMEM;
8498 			goto out;
8499 		}
8500 	}
8501 
8502 	kconfig = OPTS_GET(opts, kconfig, NULL);
8503 	if (kconfig) {
8504 		obj->kconfig = strdup(kconfig);
8505 		if (!obj->kconfig) {
8506 			err = -ENOMEM;
8507 			goto out;
8508 		}
8509 	}
8510 
8511 	err = bpf_object__elf_init(obj);
8512 	err = err ? : bpf_object__elf_collect(obj);
8513 	err = err ? : bpf_object__collect_externs(obj);
8514 	err = err ? : bpf_object_fixup_btf(obj);
8515 	err = err ? : bpf_object__init_maps(obj, opts);
8516 	err = err ? : bpf_object_init_progs(obj, opts);
8517 	err = err ? : bpf_object__collect_relos(obj);
8518 	if (err)
8519 		goto out;
8520 
8521 	bpf_object__elf_finish(obj);
8522 
8523 	return obj;
8524 out:
8525 	bpf_object__close(obj);
8526 	return ERR_PTR(err);
8527 }
8528 
8529 struct bpf_object *
8530 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8531 {
8532 	if (!path)
8533 		return libbpf_err_ptr(-EINVAL);
8534 
8535 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8536 }
8537 
8538 struct bpf_object *bpf_object__open(const char *path)
8539 {
8540 	return bpf_object__open_file(path, NULL);
8541 }
8542 
8543 struct bpf_object *
8544 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8545 		     const struct bpf_object_open_opts *opts)
8546 {
8547 	char tmp_name[64];
8548 
8549 	if (!obj_buf || obj_buf_sz == 0)
8550 		return libbpf_err_ptr(-EINVAL);
8551 
8552 	/* create a (quite useless) default "name" for this memory buffer object */
8553 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8554 
8555 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8556 }
8557 
8558 static int bpf_object_unload(struct bpf_object *obj)
8559 {
8560 	size_t i;
8561 
8562 	if (!obj)
8563 		return libbpf_err(-EINVAL);
8564 
8565 	for (i = 0; i < obj->nr_maps; i++) {
8566 		zclose(obj->maps[i].fd);
8567 		if (obj->maps[i].st_ops)
8568 			zfree(&obj->maps[i].st_ops->kern_vdata);
8569 	}
8570 
8571 	for (i = 0; i < obj->nr_programs; i++)
8572 		bpf_program__unload(&obj->programs[i]);
8573 
8574 	return 0;
8575 }
8576 
8577 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8578 {
8579 	struct bpf_map *m;
8580 
8581 	bpf_object__for_each_map(m, obj) {
8582 		if (!bpf_map__is_internal(m))
8583 			continue;
8584 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8585 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8586 	}
8587 
8588 	return 0;
8589 }
8590 
8591 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8592 			     const char *sym_name, void *ctx);
8593 
8594 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8595 {
8596 	char sym_type, sym_name[500];
8597 	unsigned long long sym_addr;
8598 	int ret, err = 0;
8599 	FILE *f;
8600 
8601 	f = fopen("/proc/kallsyms", "re");
8602 	if (!f) {
8603 		err = -errno;
8604 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8605 		return err;
8606 	}
8607 
8608 	while (true) {
8609 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8610 			     &sym_addr, &sym_type, sym_name);
8611 		if (ret == EOF && feof(f))
8612 			break;
8613 		if (ret != 3) {
8614 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8615 			err = -EINVAL;
8616 			break;
8617 		}
8618 
8619 		err = cb(sym_addr, sym_type, sym_name, ctx);
8620 		if (err)
8621 			break;
8622 	}
8623 
8624 	fclose(f);
8625 	return err;
8626 }
8627 
8628 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8629 		       const char *sym_name, void *ctx)
8630 {
8631 	struct bpf_object *obj = ctx;
8632 	const struct btf_type *t;
8633 	struct extern_desc *ext;
8634 	const char *res;
8635 
8636 	res = strstr(sym_name, ".llvm.");
8637 	if (sym_type == 'd' && res)
8638 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8639 	else
8640 		ext = find_extern_by_name(obj, sym_name);
8641 	if (!ext || ext->type != EXT_KSYM)
8642 		return 0;
8643 
8644 	t = btf__type_by_id(obj->btf, ext->btf_id);
8645 	if (!btf_is_var(t))
8646 		return 0;
8647 
8648 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8649 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8650 			sym_name, ext->ksym.addr, sym_addr);
8651 		return -EINVAL;
8652 	}
8653 	if (!ext->is_set) {
8654 		ext->is_set = true;
8655 		ext->ksym.addr = sym_addr;
8656 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8657 	}
8658 	return 0;
8659 }
8660 
8661 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8662 {
8663 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8664 }
8665 
8666 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8667 			    __u16 kind, struct btf **res_btf,
8668 			    struct module_btf **res_mod_btf)
8669 {
8670 	struct module_btf *mod_btf;
8671 	struct btf *btf;
8672 	int i, id, err;
8673 
8674 	btf = obj->btf_vmlinux;
8675 	mod_btf = NULL;
8676 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8677 
8678 	if (id == -ENOENT) {
8679 		err = load_module_btfs(obj);
8680 		if (err)
8681 			return err;
8682 
8683 		for (i = 0; i < obj->btf_module_cnt; i++) {
8684 			/* we assume module_btf's BTF FD is always >0 */
8685 			mod_btf = &obj->btf_modules[i];
8686 			btf = mod_btf->btf;
8687 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8688 			if (id != -ENOENT)
8689 				break;
8690 		}
8691 	}
8692 	if (id <= 0)
8693 		return -ESRCH;
8694 
8695 	*res_btf = btf;
8696 	*res_mod_btf = mod_btf;
8697 	return id;
8698 }
8699 
8700 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8701 					       struct extern_desc *ext)
8702 {
8703 	const struct btf_type *targ_var, *targ_type;
8704 	__u32 targ_type_id, local_type_id;
8705 	struct module_btf *mod_btf = NULL;
8706 	const char *targ_var_name;
8707 	struct btf *btf = NULL;
8708 	int id, err;
8709 
8710 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8711 	if (id < 0) {
8712 		if (id == -ESRCH && ext->is_weak)
8713 			return 0;
8714 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8715 			ext->name);
8716 		return id;
8717 	}
8718 
8719 	/* find local type_id */
8720 	local_type_id = ext->ksym.type_id;
8721 
8722 	/* find target type_id */
8723 	targ_var = btf__type_by_id(btf, id);
8724 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8725 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8726 
8727 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8728 					btf, targ_type_id);
8729 	if (err <= 0) {
8730 		const struct btf_type *local_type;
8731 		const char *targ_name, *local_name;
8732 
8733 		local_type = btf__type_by_id(obj->btf, local_type_id);
8734 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8735 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8736 
8737 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%u] %s %s, but kernel has [%u] %s %s\n",
8738 			ext->name, local_type_id,
8739 			btf_kind_str(local_type), local_name, targ_type_id,
8740 			btf_kind_str(targ_type), targ_name);
8741 		return -EINVAL;
8742 	}
8743 
8744 	ext->is_set = true;
8745 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8746 	ext->ksym.kernel_btf_id = id;
8747 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8748 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8749 
8750 	return 0;
8751 }
8752 
8753 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8754 						struct extern_desc *ext)
8755 {
8756 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8757 	struct module_btf *mod_btf = NULL;
8758 	const struct btf_type *kern_func;
8759 	struct btf *kern_btf = NULL;
8760 	int ret;
8761 
8762 	local_func_proto_id = ext->ksym.type_id;
8763 
8764 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8765 				    &mod_btf);
8766 	if (kfunc_id < 0) {
8767 		if (kfunc_id == -ESRCH && ext->is_weak)
8768 			return 0;
8769 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8770 			ext->name);
8771 		return kfunc_id;
8772 	}
8773 
8774 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8775 	kfunc_proto_id = kern_func->type;
8776 
8777 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8778 					kern_btf, kfunc_proto_id);
8779 	if (ret <= 0) {
8780 		if (ext->is_weak)
8781 			return 0;
8782 
8783 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8784 			ext->name, local_func_proto_id,
8785 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8786 		return -EINVAL;
8787 	}
8788 
8789 	/* set index for module BTF fd in fd_array, if unset */
8790 	if (mod_btf && !mod_btf->fd_array_idx) {
8791 		/* insn->off is s16 */
8792 		if (obj->fd_array_cnt == INT16_MAX) {
8793 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8794 				ext->name, mod_btf->fd_array_idx);
8795 			return -E2BIG;
8796 		}
8797 		/* Cannot use index 0 for module BTF fd */
8798 		if (!obj->fd_array_cnt)
8799 			obj->fd_array_cnt = 1;
8800 
8801 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8802 					obj->fd_array_cnt + 1);
8803 		if (ret)
8804 			return ret;
8805 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8806 		/* we assume module BTF FD is always >0 */
8807 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8808 	}
8809 
8810 	ext->is_set = true;
8811 	ext->ksym.kernel_btf_id = kfunc_id;
8812 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8813 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8814 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8815 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8816 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8817 	 */
8818 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8819 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8820 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8821 
8822 	return 0;
8823 }
8824 
8825 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8826 {
8827 	const struct btf_type *t;
8828 	struct extern_desc *ext;
8829 	int i, err;
8830 
8831 	for (i = 0; i < obj->nr_extern; i++) {
8832 		ext = &obj->externs[i];
8833 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8834 			continue;
8835 
8836 		if (obj->gen_loader) {
8837 			ext->is_set = true;
8838 			ext->ksym.kernel_btf_obj_fd = 0;
8839 			ext->ksym.kernel_btf_id = 0;
8840 			continue;
8841 		}
8842 		t = btf__type_by_id(obj->btf, ext->btf_id);
8843 		if (btf_is_var(t))
8844 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8845 		else
8846 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8847 		if (err)
8848 			return err;
8849 	}
8850 	return 0;
8851 }
8852 
8853 static int bpf_object__resolve_externs(struct bpf_object *obj,
8854 				       const char *extra_kconfig)
8855 {
8856 	bool need_config = false, need_kallsyms = false;
8857 	bool need_vmlinux_btf = false;
8858 	struct extern_desc *ext;
8859 	void *kcfg_data = NULL;
8860 	int err, i;
8861 
8862 	if (obj->nr_extern == 0)
8863 		return 0;
8864 
8865 	if (obj->kconfig_map_idx >= 0)
8866 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8867 
8868 	for (i = 0; i < obj->nr_extern; i++) {
8869 		ext = &obj->externs[i];
8870 
8871 		if (ext->type == EXT_KSYM) {
8872 			if (ext->ksym.type_id)
8873 				need_vmlinux_btf = true;
8874 			else
8875 				need_kallsyms = true;
8876 			continue;
8877 		} else if (ext->type == EXT_KCFG) {
8878 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8879 			__u64 value = 0;
8880 
8881 			/* Kconfig externs need actual /proc/config.gz */
8882 			if (str_has_pfx(ext->name, "CONFIG_")) {
8883 				need_config = true;
8884 				continue;
8885 			}
8886 
8887 			/* Virtual kcfg externs are customly handled by libbpf */
8888 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8889 				value = get_kernel_version();
8890 				if (!value) {
8891 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8892 					return -EINVAL;
8893 				}
8894 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8895 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8896 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8897 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8898 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8899 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8900 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8901 				 * customly by libbpf (their values don't come from Kconfig).
8902 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8903 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8904 				 * externs.
8905 				 */
8906 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8907 				return -EINVAL;
8908 			}
8909 
8910 			err = set_kcfg_value_num(ext, ext_ptr, value);
8911 			if (err)
8912 				return err;
8913 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8914 				 ext->name, (unsigned long long)value);
8915 		} else {
8916 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8917 			return -EINVAL;
8918 		}
8919 	}
8920 	if (need_config && extra_kconfig) {
8921 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8922 		if (err)
8923 			return -EINVAL;
8924 		need_config = false;
8925 		for (i = 0; i < obj->nr_extern; i++) {
8926 			ext = &obj->externs[i];
8927 			if (ext->type == EXT_KCFG && !ext->is_set) {
8928 				need_config = true;
8929 				break;
8930 			}
8931 		}
8932 	}
8933 	if (need_config) {
8934 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8935 		if (err)
8936 			return -EINVAL;
8937 	}
8938 	if (need_kallsyms) {
8939 		err = bpf_object__read_kallsyms_file(obj);
8940 		if (err)
8941 			return -EINVAL;
8942 	}
8943 	if (need_vmlinux_btf) {
8944 		err = bpf_object__resolve_ksyms_btf_id(obj);
8945 		if (err)
8946 			return -EINVAL;
8947 	}
8948 	for (i = 0; i < obj->nr_extern; i++) {
8949 		ext = &obj->externs[i];
8950 
8951 		if (!ext->is_set && !ext->is_weak) {
8952 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8953 			return -ESRCH;
8954 		} else if (!ext->is_set) {
8955 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8956 				 ext->name);
8957 		}
8958 	}
8959 
8960 	return 0;
8961 }
8962 
8963 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8964 {
8965 	const struct btf_type *type;
8966 	struct bpf_struct_ops *st_ops;
8967 	__u32 i;
8968 
8969 	st_ops = map->st_ops;
8970 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8971 	for (i = 0; i < btf_vlen(type); i++) {
8972 		struct bpf_program *prog = st_ops->progs[i];
8973 		void *kern_data;
8974 		int prog_fd;
8975 
8976 		if (!prog)
8977 			continue;
8978 
8979 		prog_fd = bpf_program__fd(prog);
8980 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8981 		*(unsigned long *)kern_data = prog_fd;
8982 	}
8983 }
8984 
8985 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8986 {
8987 	struct bpf_map *map;
8988 	int i;
8989 
8990 	for (i = 0; i < obj->nr_maps; i++) {
8991 		map = &obj->maps[i];
8992 
8993 		if (!bpf_map__is_struct_ops(map))
8994 			continue;
8995 
8996 		if (!map->autocreate)
8997 			continue;
8998 
8999 		bpf_map_prepare_vdata(map);
9000 	}
9001 
9002 	return 0;
9003 }
9004 
9005 static void bpf_object_unpin(struct bpf_object *obj)
9006 {
9007 	int i;
9008 
9009 	/* unpin any maps that were auto-pinned during load */
9010 	for (i = 0; i < obj->nr_maps; i++)
9011 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9012 			bpf_map__unpin(&obj->maps[i], NULL);
9013 }
9014 
9015 static void bpf_object_cleanup_btf(struct bpf_object *obj)
9016 {
9017 	int i;
9018 
9019 	/* clean up module BTFs */
9020 	for (i = 0; i < obj->btf_module_cnt; i++) {
9021 		close(obj->btf_modules[i].fd);
9022 		btf__free(obj->btf_modules[i].btf);
9023 		free(obj->btf_modules[i].name);
9024 	}
9025 	obj->btf_module_cnt = 0;
9026 	obj->btf_module_cap = 0;
9027 	obj->btf_modules_loaded = false;
9028 	zfree(&obj->btf_modules);
9029 
9030 	/* clean up vmlinux BTF */
9031 	btf__free(obj->btf_vmlinux);
9032 	obj->btf_vmlinux = NULL;
9033 }
9034 
9035 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
9036 {
9037 	/* clean up fd_array */
9038 	zfree(&obj->fd_array);
9039 
9040 	/* clean up BTF */
9041 	bpf_object_cleanup_btf(obj);
9042 }
9043 
9044 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
9045 {
9046 	int err;
9047 
9048 	if (obj->state >= OBJ_PREPARED) {
9049 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
9050 		return -EINVAL;
9051 	}
9052 
9053 	err = bpf_object_prepare_token(obj);
9054 	err = err ? : bpf_object__probe_loading(obj);
9055 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
9056 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
9057 	err = err ? : bpf_object__sanitize_maps(obj);
9058 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
9059 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
9060 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
9061 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
9062 	err = err ? : bpf_object__create_maps(obj);
9063 	err = err ? : bpf_object_prepare_progs(obj);
9064 
9065 	if (err) {
9066 		bpf_object_unpin(obj);
9067 		bpf_object_unload(obj);
9068 		obj->state = OBJ_LOADED;
9069 		return err;
9070 	}
9071 
9072 	obj->state = OBJ_PREPARED;
9073 	return 0;
9074 }
9075 
9076 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
9077 {
9078 	int err;
9079 
9080 	if (!obj)
9081 		return libbpf_err(-EINVAL);
9082 
9083 	if (obj->state >= OBJ_LOADED) {
9084 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9085 		return libbpf_err(-EINVAL);
9086 	}
9087 
9088 	/* Disallow kernel loading programs of non-native endianness but
9089 	 * permit cross-endian creation of "light skeleton".
9090 	 */
9091 	if (obj->gen_loader) {
9092 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
9093 	} else if (!is_native_endianness(obj)) {
9094 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9095 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9096 	}
9097 
9098 	if (obj->state < OBJ_PREPARED) {
9099 		err = bpf_object_prepare(obj, target_btf_path);
9100 		if (err)
9101 			return libbpf_err(err);
9102 	}
9103 	err = bpf_object__load_progs(obj, extra_log_level);
9104 	err = err ? : bpf_object_init_prog_arrays(obj);
9105 	err = err ? : bpf_object_prepare_struct_ops(obj);
9106 
9107 	if (obj->gen_loader) {
9108 		/* reset FDs */
9109 		if (obj->btf)
9110 			btf__set_fd(obj->btf, -1);
9111 		if (!err)
9112 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9113 	}
9114 
9115 	bpf_object_post_load_cleanup(obj);
9116 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9117 
9118 	if (err) {
9119 		bpf_object_unpin(obj);
9120 		bpf_object_unload(obj);
9121 		pr_warn("failed to load object '%s'\n", obj->path);
9122 		return libbpf_err(err);
9123 	}
9124 
9125 	return 0;
9126 }
9127 
9128 int bpf_object__prepare(struct bpf_object *obj)
9129 {
9130 	return libbpf_err(bpf_object_prepare(obj, NULL));
9131 }
9132 
9133 int bpf_object__load(struct bpf_object *obj)
9134 {
9135 	return bpf_object_load(obj, 0, NULL);
9136 }
9137 
9138 static int make_parent_dir(const char *path)
9139 {
9140 	char *dname, *dir;
9141 	int err = 0;
9142 
9143 	dname = strdup(path);
9144 	if (dname == NULL)
9145 		return -ENOMEM;
9146 
9147 	dir = dirname(dname);
9148 	if (mkdir(dir, 0700) && errno != EEXIST)
9149 		err = -errno;
9150 
9151 	free(dname);
9152 	if (err) {
9153 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9154 	}
9155 	return err;
9156 }
9157 
9158 static int check_path(const char *path)
9159 {
9160 	struct statfs st_fs;
9161 	char *dname, *dir;
9162 	int err = 0;
9163 
9164 	if (path == NULL)
9165 		return -EINVAL;
9166 
9167 	dname = strdup(path);
9168 	if (dname == NULL)
9169 		return -ENOMEM;
9170 
9171 	dir = dirname(dname);
9172 	if (statfs(dir, &st_fs)) {
9173 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9174 		err = -errno;
9175 	}
9176 	free(dname);
9177 
9178 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9179 		pr_warn("specified path %s is not on BPF FS\n", path);
9180 		err = -EINVAL;
9181 	}
9182 
9183 	return err;
9184 }
9185 
9186 int bpf_program__pin(struct bpf_program *prog, const char *path)
9187 {
9188 	int err;
9189 
9190 	if (prog->fd < 0) {
9191 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9192 		return libbpf_err(-EINVAL);
9193 	}
9194 
9195 	err = make_parent_dir(path);
9196 	if (err)
9197 		return libbpf_err(err);
9198 
9199 	err = check_path(path);
9200 	if (err)
9201 		return libbpf_err(err);
9202 
9203 	if (bpf_obj_pin(prog->fd, path)) {
9204 		err = -errno;
9205 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9206 		return libbpf_err(err);
9207 	}
9208 
9209 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9210 	return 0;
9211 }
9212 
9213 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9214 {
9215 	int err;
9216 
9217 	if (prog->fd < 0) {
9218 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9219 		return libbpf_err(-EINVAL);
9220 	}
9221 
9222 	err = check_path(path);
9223 	if (err)
9224 		return libbpf_err(err);
9225 
9226 	err = unlink(path);
9227 	if (err)
9228 		return libbpf_err(-errno);
9229 
9230 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9231 	return 0;
9232 }
9233 
9234 int bpf_map__pin(struct bpf_map *map, const char *path)
9235 {
9236 	int err;
9237 
9238 	if (map == NULL) {
9239 		pr_warn("invalid map pointer\n");
9240 		return libbpf_err(-EINVAL);
9241 	}
9242 
9243 	if (map->fd < 0) {
9244 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9245 		return libbpf_err(-EINVAL);
9246 	}
9247 
9248 	if (map->pin_path) {
9249 		if (path && strcmp(path, map->pin_path)) {
9250 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9251 				bpf_map__name(map), map->pin_path, path);
9252 			return libbpf_err(-EINVAL);
9253 		} else if (map->pinned) {
9254 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9255 				 bpf_map__name(map), map->pin_path);
9256 			return 0;
9257 		}
9258 	} else {
9259 		if (!path) {
9260 			pr_warn("missing a path to pin map '%s' at\n",
9261 				bpf_map__name(map));
9262 			return libbpf_err(-EINVAL);
9263 		} else if (map->pinned) {
9264 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9265 			return libbpf_err(-EEXIST);
9266 		}
9267 
9268 		map->pin_path = strdup(path);
9269 		if (!map->pin_path) {
9270 			err = -errno;
9271 			goto out_err;
9272 		}
9273 	}
9274 
9275 	err = make_parent_dir(map->pin_path);
9276 	if (err)
9277 		return libbpf_err(err);
9278 
9279 	err = check_path(map->pin_path);
9280 	if (err)
9281 		return libbpf_err(err);
9282 
9283 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9284 		err = -errno;
9285 		goto out_err;
9286 	}
9287 
9288 	map->pinned = true;
9289 	pr_debug("pinned map '%s'\n", map->pin_path);
9290 
9291 	return 0;
9292 
9293 out_err:
9294 	pr_warn("failed to pin map: %s\n", errstr(err));
9295 	return libbpf_err(err);
9296 }
9297 
9298 int bpf_map__unpin(struct bpf_map *map, const char *path)
9299 {
9300 	int err;
9301 
9302 	if (map == NULL) {
9303 		pr_warn("invalid map pointer\n");
9304 		return libbpf_err(-EINVAL);
9305 	}
9306 
9307 	if (map->pin_path) {
9308 		if (path && strcmp(path, map->pin_path)) {
9309 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9310 				bpf_map__name(map), map->pin_path, path);
9311 			return libbpf_err(-EINVAL);
9312 		}
9313 		path = map->pin_path;
9314 	} else if (!path) {
9315 		pr_warn("no path to unpin map '%s' from\n",
9316 			bpf_map__name(map));
9317 		return libbpf_err(-EINVAL);
9318 	}
9319 
9320 	err = check_path(path);
9321 	if (err)
9322 		return libbpf_err(err);
9323 
9324 	err = unlink(path);
9325 	if (err != 0)
9326 		return libbpf_err(-errno);
9327 
9328 	map->pinned = false;
9329 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9330 
9331 	return 0;
9332 }
9333 
9334 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9335 {
9336 	char *new = NULL;
9337 
9338 	if (path) {
9339 		new = strdup(path);
9340 		if (!new)
9341 			return libbpf_err(-errno);
9342 	}
9343 
9344 	free(map->pin_path);
9345 	map->pin_path = new;
9346 	return 0;
9347 }
9348 
9349 __alias(bpf_map__pin_path)
9350 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9351 
9352 const char *bpf_map__pin_path(const struct bpf_map *map)
9353 {
9354 	return map->pin_path;
9355 }
9356 
9357 bool bpf_map__is_pinned(const struct bpf_map *map)
9358 {
9359 	return map->pinned;
9360 }
9361 
9362 static void sanitize_pin_path(char *s)
9363 {
9364 	/* bpffs disallows periods in path names */
9365 	while (*s) {
9366 		if (*s == '.')
9367 			*s = '_';
9368 		s++;
9369 	}
9370 }
9371 
9372 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9373 {
9374 	struct bpf_map *map;
9375 	int err;
9376 
9377 	if (!obj)
9378 		return libbpf_err(-ENOENT);
9379 
9380 	if (obj->state < OBJ_PREPARED) {
9381 		pr_warn("object not yet loaded; load it first\n");
9382 		return libbpf_err(-ENOENT);
9383 	}
9384 
9385 	bpf_object__for_each_map(map, obj) {
9386 		char *pin_path = NULL;
9387 		char buf[PATH_MAX];
9388 
9389 		if (!map->autocreate)
9390 			continue;
9391 
9392 		if (path) {
9393 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9394 			if (err)
9395 				goto err_unpin_maps;
9396 			sanitize_pin_path(buf);
9397 			pin_path = buf;
9398 		} else if (!map->pin_path) {
9399 			continue;
9400 		}
9401 
9402 		err = bpf_map__pin(map, pin_path);
9403 		if (err)
9404 			goto err_unpin_maps;
9405 	}
9406 
9407 	return 0;
9408 
9409 err_unpin_maps:
9410 	while ((map = bpf_object__prev_map(obj, map))) {
9411 		if (!map->pin_path)
9412 			continue;
9413 
9414 		bpf_map__unpin(map, NULL);
9415 	}
9416 
9417 	return libbpf_err(err);
9418 }
9419 
9420 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9421 {
9422 	struct bpf_map *map;
9423 	int err;
9424 
9425 	if (!obj)
9426 		return libbpf_err(-ENOENT);
9427 
9428 	bpf_object__for_each_map(map, obj) {
9429 		char *pin_path = NULL;
9430 		char buf[PATH_MAX];
9431 
9432 		if (path) {
9433 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9434 			if (err)
9435 				return libbpf_err(err);
9436 			sanitize_pin_path(buf);
9437 			pin_path = buf;
9438 		} else if (!map->pin_path) {
9439 			continue;
9440 		}
9441 
9442 		err = bpf_map__unpin(map, pin_path);
9443 		if (err)
9444 			return libbpf_err(err);
9445 	}
9446 
9447 	return 0;
9448 }
9449 
9450 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9451 {
9452 	struct bpf_program *prog;
9453 	char buf[PATH_MAX];
9454 	int err;
9455 
9456 	if (!obj)
9457 		return libbpf_err(-ENOENT);
9458 
9459 	if (obj->state < OBJ_LOADED) {
9460 		pr_warn("object not yet loaded; load it first\n");
9461 		return libbpf_err(-ENOENT);
9462 	}
9463 
9464 	bpf_object__for_each_program(prog, obj) {
9465 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9466 		if (err)
9467 			goto err_unpin_programs;
9468 
9469 		err = bpf_program__pin(prog, buf);
9470 		if (err)
9471 			goto err_unpin_programs;
9472 	}
9473 
9474 	return 0;
9475 
9476 err_unpin_programs:
9477 	while ((prog = bpf_object__prev_program(obj, prog))) {
9478 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9479 			continue;
9480 
9481 		bpf_program__unpin(prog, buf);
9482 	}
9483 
9484 	return libbpf_err(err);
9485 }
9486 
9487 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9488 {
9489 	struct bpf_program *prog;
9490 	int err;
9491 
9492 	if (!obj)
9493 		return libbpf_err(-ENOENT);
9494 
9495 	bpf_object__for_each_program(prog, obj) {
9496 		char buf[PATH_MAX];
9497 
9498 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9499 		if (err)
9500 			return libbpf_err(err);
9501 
9502 		err = bpf_program__unpin(prog, buf);
9503 		if (err)
9504 			return libbpf_err(err);
9505 	}
9506 
9507 	return 0;
9508 }
9509 
9510 int bpf_object__pin(struct bpf_object *obj, const char *path)
9511 {
9512 	int err;
9513 
9514 	err = bpf_object__pin_maps(obj, path);
9515 	if (err)
9516 		return libbpf_err(err);
9517 
9518 	err = bpf_object__pin_programs(obj, path);
9519 	if (err) {
9520 		bpf_object__unpin_maps(obj, path);
9521 		return libbpf_err(err);
9522 	}
9523 
9524 	return 0;
9525 }
9526 
9527 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9528 {
9529 	int err;
9530 
9531 	err = bpf_object__unpin_programs(obj, path);
9532 	if (err)
9533 		return libbpf_err(err);
9534 
9535 	err = bpf_object__unpin_maps(obj, path);
9536 	if (err)
9537 		return libbpf_err(err);
9538 
9539 	return 0;
9540 }
9541 
9542 static void bpf_map__destroy(struct bpf_map *map)
9543 {
9544 	if (map->inner_map) {
9545 		bpf_map__destroy(map->inner_map);
9546 		zfree(&map->inner_map);
9547 	}
9548 
9549 	zfree(&map->init_slots);
9550 	map->init_slots_sz = 0;
9551 
9552 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9553 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9554 	map->mmaped = NULL;
9555 
9556 	if (map->st_ops) {
9557 		zfree(&map->st_ops->data);
9558 		zfree(&map->st_ops->progs);
9559 		zfree(&map->st_ops->kern_func_off);
9560 		zfree(&map->st_ops);
9561 	}
9562 
9563 	zfree(&map->name);
9564 	zfree(&map->real_name);
9565 	zfree(&map->pin_path);
9566 
9567 	if (map->fd >= 0)
9568 		zclose(map->fd);
9569 }
9570 
9571 void bpf_object__close(struct bpf_object *obj)
9572 {
9573 	size_t i;
9574 
9575 	if (IS_ERR_OR_NULL(obj))
9576 		return;
9577 
9578 	/*
9579 	 * if user called bpf_object__prepare() without ever getting to
9580 	 * bpf_object__load(), we need to clean up stuff that is normally
9581 	 * cleaned up at the end of loading step
9582 	 */
9583 	bpf_object_post_load_cleanup(obj);
9584 
9585 	usdt_manager_free(obj->usdt_man);
9586 	obj->usdt_man = NULL;
9587 
9588 	bpf_gen__free(obj->gen_loader);
9589 	bpf_object__elf_finish(obj);
9590 	bpf_object_unload(obj);
9591 	btf__free(obj->btf);
9592 	btf__free(obj->btf_vmlinux);
9593 	btf_ext__free(obj->btf_ext);
9594 
9595 	for (i = 0; i < obj->nr_maps; i++)
9596 		bpf_map__destroy(&obj->maps[i]);
9597 
9598 	zfree(&obj->btf_custom_path);
9599 	zfree(&obj->kconfig);
9600 
9601 	for (i = 0; i < obj->nr_extern; i++) {
9602 		zfree(&obj->externs[i].name);
9603 		zfree(&obj->externs[i].essent_name);
9604 	}
9605 
9606 	zfree(&obj->externs);
9607 	obj->nr_extern = 0;
9608 
9609 	zfree(&obj->maps);
9610 	obj->nr_maps = 0;
9611 
9612 	if (obj->programs && obj->nr_programs) {
9613 		for (i = 0; i < obj->nr_programs; i++)
9614 			bpf_program__exit(&obj->programs[i]);
9615 	}
9616 	zfree(&obj->programs);
9617 
9618 	zfree(&obj->feat_cache);
9619 	zfree(&obj->token_path);
9620 	if (obj->token_fd > 0)
9621 		close(obj->token_fd);
9622 
9623 	zfree(&obj->arena_data);
9624 
9625 	zfree(&obj->jumptables_data);
9626 	obj->jumptables_data_sz = 0;
9627 
9628 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9629 		close(obj->jumptable_maps[i].fd);
9630 	zfree(&obj->jumptable_maps);
9631 
9632 	free(obj);
9633 }
9634 
9635 const char *bpf_object__name(const struct bpf_object *obj)
9636 {
9637 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9638 }
9639 
9640 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9641 {
9642 	return obj ? obj->kern_version : 0;
9643 }
9644 
9645 int bpf_object__token_fd(const struct bpf_object *obj)
9646 {
9647 	return obj->token_fd ?: -1;
9648 }
9649 
9650 struct btf *bpf_object__btf(const struct bpf_object *obj)
9651 {
9652 	return obj ? obj->btf : NULL;
9653 }
9654 
9655 int bpf_object__btf_fd(const struct bpf_object *obj)
9656 {
9657 	return obj->btf ? btf__fd(obj->btf) : -1;
9658 }
9659 
9660 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9661 {
9662 	if (obj->state >= OBJ_LOADED)
9663 		return libbpf_err(-EINVAL);
9664 
9665 	obj->kern_version = kern_version;
9666 
9667 	return 0;
9668 }
9669 
9670 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9671 {
9672 	struct bpf_gen *gen;
9673 
9674 	if (!opts)
9675 		return libbpf_err(-EFAULT);
9676 	if (!OPTS_VALID(opts, gen_loader_opts))
9677 		return libbpf_err(-EINVAL);
9678 	gen = calloc(1, sizeof(*gen));
9679 	if (!gen)
9680 		return libbpf_err(-ENOMEM);
9681 	gen->opts = opts;
9682 	gen->swapped_endian = !is_native_endianness(obj);
9683 	obj->gen_loader = gen;
9684 	return 0;
9685 }
9686 
9687 static struct bpf_program *
9688 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9689 		    bool forward)
9690 {
9691 	size_t nr_programs = obj->nr_programs;
9692 	ssize_t idx;
9693 
9694 	if (!nr_programs)
9695 		return NULL;
9696 
9697 	if (!p)
9698 		/* Iter from the beginning */
9699 		return forward ? &obj->programs[0] :
9700 			&obj->programs[nr_programs - 1];
9701 
9702 	if (p->obj != obj) {
9703 		pr_warn("error: program handler doesn't match object\n");
9704 		return errno = EINVAL, NULL;
9705 	}
9706 
9707 	idx = (p - obj->programs) + (forward ? 1 : -1);
9708 	if (idx >= obj->nr_programs || idx < 0)
9709 		return NULL;
9710 	return &obj->programs[idx];
9711 }
9712 
9713 struct bpf_program *
9714 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9715 {
9716 	struct bpf_program *prog = prev;
9717 
9718 	do {
9719 		prog = __bpf_program__iter(prog, obj, true);
9720 	} while (prog && prog_is_subprog(obj, prog));
9721 
9722 	return prog;
9723 }
9724 
9725 struct bpf_program *
9726 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9727 {
9728 	struct bpf_program *prog = next;
9729 
9730 	do {
9731 		prog = __bpf_program__iter(prog, obj, false);
9732 	} while (prog && prog_is_subprog(obj, prog));
9733 
9734 	return prog;
9735 }
9736 
9737 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9738 {
9739 	prog->prog_ifindex = ifindex;
9740 }
9741 
9742 const char *bpf_program__name(const struct bpf_program *prog)
9743 {
9744 	return prog->name;
9745 }
9746 
9747 const char *bpf_program__section_name(const struct bpf_program *prog)
9748 {
9749 	return prog->sec_name;
9750 }
9751 
9752 bool bpf_program__autoload(const struct bpf_program *prog)
9753 {
9754 	return prog->autoload;
9755 }
9756 
9757 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9758 {
9759 	if (prog->obj->state >= OBJ_LOADED)
9760 		return libbpf_err(-EINVAL);
9761 
9762 	prog->autoload = autoload;
9763 	return 0;
9764 }
9765 
9766 bool bpf_program__autoattach(const struct bpf_program *prog)
9767 {
9768 	return prog->autoattach;
9769 }
9770 
9771 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9772 {
9773 	prog->autoattach = autoattach;
9774 }
9775 
9776 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9777 {
9778 	return prog->insns;
9779 }
9780 
9781 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9782 {
9783 	return prog->insns_cnt;
9784 }
9785 
9786 int bpf_program__set_insns(struct bpf_program *prog,
9787 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9788 {
9789 	struct bpf_insn *insns;
9790 
9791 	if (prog->obj->state >= OBJ_LOADED)
9792 		return libbpf_err(-EBUSY);
9793 
9794 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9795 	/* NULL is a valid return from reallocarray if the new count is zero */
9796 	if (!insns && new_insn_cnt) {
9797 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9798 		return libbpf_err(-ENOMEM);
9799 	}
9800 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9801 
9802 	prog->insns = insns;
9803 	prog->insns_cnt = new_insn_cnt;
9804 	return 0;
9805 }
9806 
9807 int bpf_program__fd(const struct bpf_program *prog)
9808 {
9809 	if (!prog)
9810 		return libbpf_err(-EINVAL);
9811 
9812 	if (prog->fd < 0)
9813 		return libbpf_err(-ENOENT);
9814 
9815 	return prog->fd;
9816 }
9817 
9818 __alias(bpf_program__type)
9819 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9820 
9821 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9822 {
9823 	return prog->type;
9824 }
9825 
9826 static size_t custom_sec_def_cnt;
9827 static struct bpf_sec_def *custom_sec_defs;
9828 static struct bpf_sec_def custom_fallback_def;
9829 static bool has_custom_fallback_def;
9830 static int last_custom_sec_def_handler_id;
9831 
9832 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9833 {
9834 	if (prog->obj->state >= OBJ_LOADED)
9835 		return libbpf_err(-EBUSY);
9836 
9837 	/* if type is not changed, do nothing */
9838 	if (prog->type == type)
9839 		return 0;
9840 
9841 	prog->type = type;
9842 
9843 	/* If a program type was changed, we need to reset associated SEC()
9844 	 * handler, as it will be invalid now. The only exception is a generic
9845 	 * fallback handler, which by definition is program type-agnostic and
9846 	 * is a catch-all custom handler, optionally set by the application,
9847 	 * so should be able to handle any type of BPF program.
9848 	 */
9849 	if (prog->sec_def != &custom_fallback_def)
9850 		prog->sec_def = NULL;
9851 	return 0;
9852 }
9853 
9854 __alias(bpf_program__expected_attach_type)
9855 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9856 
9857 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9858 {
9859 	return prog->expected_attach_type;
9860 }
9861 
9862 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9863 					   enum bpf_attach_type type)
9864 {
9865 	if (prog->obj->state >= OBJ_LOADED)
9866 		return libbpf_err(-EBUSY);
9867 
9868 	prog->expected_attach_type = type;
9869 	return 0;
9870 }
9871 
9872 __u32 bpf_program__flags(const struct bpf_program *prog)
9873 {
9874 	return prog->prog_flags;
9875 }
9876 
9877 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9878 {
9879 	if (prog->obj->state >= OBJ_LOADED)
9880 		return libbpf_err(-EBUSY);
9881 
9882 	prog->prog_flags = flags;
9883 	return 0;
9884 }
9885 
9886 __u32 bpf_program__log_level(const struct bpf_program *prog)
9887 {
9888 	return prog->log_level;
9889 }
9890 
9891 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9892 {
9893 	if (prog->obj->state >= OBJ_LOADED)
9894 		return libbpf_err(-EBUSY);
9895 
9896 	prog->log_level = log_level;
9897 	return 0;
9898 }
9899 
9900 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9901 {
9902 	*log_size = prog->log_size;
9903 	return prog->log_buf;
9904 }
9905 
9906 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9907 {
9908 	if (log_size && !log_buf)
9909 		return libbpf_err(-EINVAL);
9910 	if (prog->log_size > UINT_MAX)
9911 		return libbpf_err(-EINVAL);
9912 	if (prog->obj->state >= OBJ_LOADED)
9913 		return libbpf_err(-EBUSY);
9914 
9915 	prog->log_buf = log_buf;
9916 	prog->log_size = log_size;
9917 	return 0;
9918 }
9919 
9920 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9921 {
9922 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9923 		return libbpf_err_ptr(-EOPNOTSUPP);
9924 	return prog->func_info;
9925 }
9926 
9927 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9928 {
9929 	return prog->func_info_cnt;
9930 }
9931 
9932 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9933 {
9934 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9935 		return libbpf_err_ptr(-EOPNOTSUPP);
9936 	return prog->line_info;
9937 }
9938 
9939 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9940 {
9941 	return prog->line_info_cnt;
9942 }
9943 
9944 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
9945 {
9946 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
9947 	struct bpf_object *obj;
9948 	const void *info;
9949 	__u32 info_cnt, info_rec_size;
9950 	int err, fd, prog_btf_fd;
9951 
9952 	if (!prog)
9953 		return libbpf_err(-EINVAL);
9954 
9955 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
9956 		return libbpf_err(-EINVAL);
9957 
9958 	obj = prog->obj;
9959 	if (obj->state < OBJ_PREPARED)
9960 		return libbpf_err(-EINVAL);
9961 
9962 	/*
9963 	 * Caller-provided opts take priority; fall back to
9964 	 * prog/object defaults when the caller leaves them zero.
9965 	 */
9966 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
9967 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
9968 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
9969 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
9970 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
9971 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
9972 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
9973 	if (attr.token_fd)
9974 		attr.prog_flags |= BPF_F_TOKEN_FD;
9975 
9976 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
9977 	if (!prog_btf_fd && obj->btf)
9978 		prog_btf_fd = btf__fd(obj->btf);
9979 
9980 	/* BTF func/line info: only pass if kernel supports it */
9981 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
9982 		attr.prog_btf_fd = prog_btf_fd;
9983 
9984 		/* func_info/line_info triples: all-or-nothing from caller */
9985 		info = OPTS_GET(opts, func_info, NULL);
9986 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
9987 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
9988 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9989 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
9990 				prog->name);
9991 			return libbpf_err(-EINVAL);
9992 		}
9993 		attr.func_info = info ?: prog->func_info;
9994 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
9995 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
9996 
9997 		info = OPTS_GET(opts, line_info, NULL);
9998 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
9999 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
10000 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10001 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
10002 				prog->name);
10003 			return libbpf_err(-EINVAL);
10004 		}
10005 		attr.line_info = info ?: prog->line_info;
10006 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
10007 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
10008 	}
10009 
10010 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
10011 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
10012 	attr.log_size = OPTS_GET(opts, log_size, 0);
10013 	attr.log_level = OPTS_GET(opts, log_level, 0);
10014 
10015 	/*
10016 	 * Fields below may be mutated by prog_prepare_load_fn:
10017 	 * Seed them from prog/obj defaults here;
10018 	 * Later override with caller-provided opts.
10019 	 */
10020 	attr.expected_attach_type = prog->expected_attach_type;
10021 	attr.attach_btf_id = prog->attach_btf_id;
10022 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
10023 
10024 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
10025 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
10026 		if (err)
10027 			return libbpf_err(err);
10028 	}
10029 
10030 	/* Re-apply caller overrides for output fields */
10031 	if (OPTS_GET(opts, expected_attach_type, 0))
10032 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
10033 	if (OPTS_GET(opts, attach_btf_id, 0))
10034 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
10035 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
10036 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
10037 
10038 	/*
10039 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
10040 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
10041 	 * required maps themselves using bpf_prog_bind_map().
10042 	 */
10043 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
10044 			   &attr);
10045 
10046 	return libbpf_err(fd);
10047 }
10048 
10049 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
10050 	.sec = (char *)sec_pfx,						    \
10051 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
10052 	.expected_attach_type = atype,					    \
10053 	.cookie = (long)(flags),					    \
10054 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
10055 	__VA_ARGS__							    \
10056 }
10057 
10058 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10059 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10060 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10061 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10062 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10063 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10064 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10065 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10066 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10067 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10068 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10069 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10070 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10071 
10072 static const struct bpf_sec_def section_defs[] = {
10073 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
10074 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
10075 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
10076 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
10077 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
10078 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
10079 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
10080 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
10081 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
10082 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10083 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10084 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10085 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10086 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10087 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10088 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10089 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10090 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10091 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10092 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10093 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10094 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10095 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10096 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10097 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10098 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10099 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10100 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10101 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10102 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10103 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10104 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10105 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10106 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10107 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10108 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10109 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10110 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10111 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10112 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10113 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10114 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10115 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10116 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10117 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10118 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10119 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10120 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10121 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10122 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10123 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10124 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
10125 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10126 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
10127 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
10128 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10129 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10130 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10131 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10132 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10133 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10134 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10135 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10136 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10137 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10138 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10139 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10140 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10141 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10142 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10143 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10144 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10145 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10146 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10147 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10148 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10149 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10150 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10151 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10152 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10153 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10154 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10155 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10156 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10157 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10158 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10159 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10160 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10161 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10162 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10163 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10164 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10165 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10166 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10167 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10168 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10169 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10170 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10171 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10172 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10173 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10174 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10175 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10176 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10177 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10178 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10179 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10180 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10181 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10182 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10183 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10184 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10185 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10186 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10187 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10188 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10189 };
10190 
10191 int libbpf_register_prog_handler(const char *sec,
10192 				 enum bpf_prog_type prog_type,
10193 				 enum bpf_attach_type exp_attach_type,
10194 				 const struct libbpf_prog_handler_opts *opts)
10195 {
10196 	struct bpf_sec_def *sec_def;
10197 
10198 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10199 		return libbpf_err(-EINVAL);
10200 
10201 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10202 		return libbpf_err(-E2BIG);
10203 
10204 	if (sec) {
10205 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10206 					      sizeof(*sec_def));
10207 		if (!sec_def)
10208 			return libbpf_err(-ENOMEM);
10209 
10210 		custom_sec_defs = sec_def;
10211 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10212 	} else {
10213 		if (has_custom_fallback_def)
10214 			return libbpf_err(-EBUSY);
10215 
10216 		sec_def = &custom_fallback_def;
10217 	}
10218 
10219 	sec_def->sec = sec ? strdup(sec) : NULL;
10220 	if (sec && !sec_def->sec)
10221 		return libbpf_err(-ENOMEM);
10222 
10223 	sec_def->prog_type = prog_type;
10224 	sec_def->expected_attach_type = exp_attach_type;
10225 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10226 
10227 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10228 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10229 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10230 
10231 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10232 
10233 	if (sec)
10234 		custom_sec_def_cnt++;
10235 	else
10236 		has_custom_fallback_def = true;
10237 
10238 	return sec_def->handler_id;
10239 }
10240 
10241 int libbpf_unregister_prog_handler(int handler_id)
10242 {
10243 	struct bpf_sec_def *sec_defs;
10244 	int i;
10245 
10246 	if (handler_id <= 0)
10247 		return libbpf_err(-EINVAL);
10248 
10249 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10250 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10251 		has_custom_fallback_def = false;
10252 		return 0;
10253 	}
10254 
10255 	for (i = 0; i < custom_sec_def_cnt; i++) {
10256 		if (custom_sec_defs[i].handler_id == handler_id)
10257 			break;
10258 	}
10259 
10260 	if (i == custom_sec_def_cnt)
10261 		return libbpf_err(-ENOENT);
10262 
10263 	free(custom_sec_defs[i].sec);
10264 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10265 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10266 	custom_sec_def_cnt--;
10267 
10268 	/* try to shrink the array, but it's ok if we couldn't */
10269 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10270 	/* if new count is zero, reallocarray can return a valid NULL result;
10271 	 * in this case the previous pointer will be freed, so we *have to*
10272 	 * reassign old pointer to the new value (even if it's NULL)
10273 	 */
10274 	if (sec_defs || custom_sec_def_cnt == 0)
10275 		custom_sec_defs = sec_defs;
10276 
10277 	return 0;
10278 }
10279 
10280 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10281 {
10282 	size_t len = strlen(sec_def->sec);
10283 
10284 	/* "type/" always has to have proper SEC("type/extras") form */
10285 	if (sec_def->sec[len - 1] == '/') {
10286 		if (str_has_pfx(sec_name, sec_def->sec))
10287 			return true;
10288 		return false;
10289 	}
10290 
10291 	/* "type+" means it can be either exact SEC("type") or
10292 	 * well-formed SEC("type/extras") with proper '/' separator
10293 	 */
10294 	if (sec_def->sec[len - 1] == '+') {
10295 		len--;
10296 		/* not even a prefix */
10297 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10298 			return false;
10299 		/* exact match or has '/' separator */
10300 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10301 			return true;
10302 		return false;
10303 	}
10304 
10305 	return strcmp(sec_name, sec_def->sec) == 0;
10306 }
10307 
10308 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10309 {
10310 	const struct bpf_sec_def *sec_def;
10311 	int i, n;
10312 
10313 	n = custom_sec_def_cnt;
10314 	for (i = 0; i < n; i++) {
10315 		sec_def = &custom_sec_defs[i];
10316 		if (sec_def_matches(sec_def, sec_name))
10317 			return sec_def;
10318 	}
10319 
10320 	n = ARRAY_SIZE(section_defs);
10321 	for (i = 0; i < n; i++) {
10322 		sec_def = &section_defs[i];
10323 		if (sec_def_matches(sec_def, sec_name))
10324 			return sec_def;
10325 	}
10326 
10327 	if (has_custom_fallback_def)
10328 		return &custom_fallback_def;
10329 
10330 	return NULL;
10331 }
10332 
10333 #define MAX_TYPE_NAME_SIZE 32
10334 
10335 static char *libbpf_get_type_names(bool attach_type)
10336 {
10337 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10338 	char *buf;
10339 
10340 	buf = malloc(len);
10341 	if (!buf)
10342 		return NULL;
10343 
10344 	buf[0] = '\0';
10345 	/* Forge string buf with all available names */
10346 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10347 		const struct bpf_sec_def *sec_def = &section_defs[i];
10348 
10349 		if (attach_type) {
10350 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10351 				continue;
10352 
10353 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10354 				continue;
10355 		}
10356 
10357 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10358 			free(buf);
10359 			return NULL;
10360 		}
10361 		strcat(buf, " ");
10362 		strcat(buf, section_defs[i].sec);
10363 	}
10364 
10365 	return buf;
10366 }
10367 
10368 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10369 			     enum bpf_attach_type *expected_attach_type)
10370 {
10371 	const struct bpf_sec_def *sec_def;
10372 	char *type_names;
10373 
10374 	if (!name)
10375 		return libbpf_err(-EINVAL);
10376 
10377 	sec_def = find_sec_def(name);
10378 	if (sec_def) {
10379 		*prog_type = sec_def->prog_type;
10380 		*expected_attach_type = sec_def->expected_attach_type;
10381 		return 0;
10382 	}
10383 
10384 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10385 	type_names = libbpf_get_type_names(false);
10386 	if (type_names != NULL) {
10387 		pr_debug("supported section(type) names are:%s\n", type_names);
10388 		free(type_names);
10389 	}
10390 
10391 	return libbpf_err(-ESRCH);
10392 }
10393 
10394 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10395 {
10396 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10397 		return NULL;
10398 
10399 	return attach_type_name[t];
10400 }
10401 
10402 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10403 {
10404 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10405 		return NULL;
10406 
10407 	return link_type_name[t];
10408 }
10409 
10410 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10411 {
10412 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10413 		return NULL;
10414 
10415 	return map_type_name[t];
10416 }
10417 
10418 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10419 {
10420 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10421 		return NULL;
10422 
10423 	return prog_type_name[t];
10424 }
10425 
10426 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10427 						     int sec_idx,
10428 						     size_t offset)
10429 {
10430 	struct bpf_map *map;
10431 	size_t i;
10432 
10433 	for (i = 0; i < obj->nr_maps; i++) {
10434 		map = &obj->maps[i];
10435 		if (!bpf_map__is_struct_ops(map))
10436 			continue;
10437 		if (map->sec_idx == sec_idx &&
10438 		    map->sec_offset <= offset &&
10439 		    offset - map->sec_offset < map->def.value_size)
10440 			return map;
10441 	}
10442 
10443 	return NULL;
10444 }
10445 
10446 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10447  * st_ops->data for shadow type.
10448  */
10449 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10450 					    Elf64_Shdr *shdr, Elf_Data *data)
10451 {
10452 	const struct btf_type *type;
10453 	const struct btf_member *member;
10454 	struct bpf_struct_ops *st_ops;
10455 	struct bpf_program *prog;
10456 	unsigned int shdr_idx;
10457 	const struct btf *btf;
10458 	struct bpf_map *map;
10459 	unsigned int moff, insn_idx;
10460 	const char *name;
10461 	__u32 member_idx;
10462 	Elf64_Sym *sym;
10463 	Elf64_Rel *rel;
10464 	int i, nrels;
10465 
10466 	btf = obj->btf;
10467 	nrels = shdr->sh_size / shdr->sh_entsize;
10468 	for (i = 0; i < nrels; i++) {
10469 		rel = elf_rel_by_idx(data, i);
10470 		if (!rel) {
10471 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10472 			return -LIBBPF_ERRNO__FORMAT;
10473 		}
10474 
10475 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10476 		if (!sym) {
10477 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10478 				(size_t)ELF64_R_SYM(rel->r_info));
10479 			return -LIBBPF_ERRNO__FORMAT;
10480 		}
10481 
10482 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10483 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10484 		if (!map) {
10485 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10486 				(size_t)rel->r_offset);
10487 			return -EINVAL;
10488 		}
10489 
10490 		moff = rel->r_offset - map->sec_offset;
10491 		shdr_idx = sym->st_shndx;
10492 		st_ops = map->st_ops;
10493 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %u (\'%s\')\n",
10494 			 map->name,
10495 			 (long long)(rel->r_info >> 32),
10496 			 (long long)sym->st_value,
10497 			 shdr_idx, (size_t)rel->r_offset,
10498 			 map->sec_offset, sym->st_name, name);
10499 
10500 		if (shdr_idx >= SHN_LORESERVE) {
10501 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10502 				map->name, (size_t)rel->r_offset, shdr_idx);
10503 			return -LIBBPF_ERRNO__RELOC;
10504 		}
10505 		if (sym->st_value % BPF_INSN_SZ) {
10506 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10507 				map->name, (unsigned long long)sym->st_value);
10508 			return -LIBBPF_ERRNO__FORMAT;
10509 		}
10510 		insn_idx = sym->st_value / BPF_INSN_SZ;
10511 
10512 		type = btf__type_by_id(btf, st_ops->type_id);
10513 		member = find_member_by_offset(type, moff * 8);
10514 		if (!member) {
10515 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10516 				map->name, moff);
10517 			return -EINVAL;
10518 		}
10519 		member_idx = member - btf_members(type);
10520 		name = btf__name_by_offset(btf, member->name_off);
10521 
10522 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10523 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10524 				map->name, name);
10525 			return -EINVAL;
10526 		}
10527 
10528 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10529 		if (!prog) {
10530 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10531 				map->name, shdr_idx, name);
10532 			return -EINVAL;
10533 		}
10534 
10535 		/* prevent the use of BPF prog with invalid type */
10536 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10537 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10538 				map->name, prog->name);
10539 			return -EINVAL;
10540 		}
10541 
10542 		st_ops->progs[member_idx] = prog;
10543 
10544 		/* st_ops->data will be exposed to users, being returned by
10545 		 * bpf_map__initial_value() as a pointer to the shadow
10546 		 * type. All function pointers in the original struct type
10547 		 * should be converted to a pointer to struct bpf_program
10548 		 * in the shadow type.
10549 		 */
10550 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10551 	}
10552 
10553 	return 0;
10554 }
10555 
10556 #define BTF_TRACE_PREFIX "btf_trace_"
10557 #define BTF_LSM_PREFIX "bpf_lsm_"
10558 #define BTF_ITER_PREFIX "bpf_iter_"
10559 #define BTF_MAX_NAME_SIZE 128
10560 
10561 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10562 				const char **prefix, int *kind)
10563 {
10564 	switch (attach_type) {
10565 	case BPF_TRACE_RAW_TP:
10566 		*prefix = BTF_TRACE_PREFIX;
10567 		*kind = BTF_KIND_TYPEDEF;
10568 		break;
10569 	case BPF_LSM_MAC:
10570 	case BPF_LSM_CGROUP:
10571 		*prefix = BTF_LSM_PREFIX;
10572 		*kind = BTF_KIND_FUNC;
10573 		break;
10574 	case BPF_TRACE_ITER:
10575 		*prefix = BTF_ITER_PREFIX;
10576 		*kind = BTF_KIND_FUNC;
10577 		break;
10578 	default:
10579 		*prefix = "";
10580 		*kind = BTF_KIND_FUNC;
10581 	}
10582 }
10583 
10584 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10585 				   const char *name, __u32 kind)
10586 {
10587 	char btf_type_name[BTF_MAX_NAME_SIZE];
10588 	int ret;
10589 
10590 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10591 		       "%s%s", prefix, name);
10592 	/* snprintf returns the number of characters written excluding the
10593 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10594 	 * indicates truncation.
10595 	 */
10596 	if (ret < 0 || ret >= sizeof(btf_type_name))
10597 		return -ENAMETOOLONG;
10598 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10599 }
10600 
10601 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10602 				     enum bpf_attach_type attach_type)
10603 {
10604 	const char *prefix;
10605 	int kind;
10606 
10607 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10608 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10609 }
10610 
10611 int libbpf_find_vmlinux_btf_id(const char *name,
10612 			       enum bpf_attach_type attach_type)
10613 {
10614 	struct btf *btf;
10615 	int err;
10616 
10617 	btf = btf__load_vmlinux_btf();
10618 	err = libbpf_get_error(btf);
10619 	if (err) {
10620 		pr_warn("vmlinux BTF is not found\n");
10621 		return libbpf_err(err);
10622 	}
10623 
10624 	err = find_attach_btf_id(btf, name, attach_type);
10625 	if (err <= 0)
10626 		pr_warn("%s is not found in vmlinux BTF\n", name);
10627 
10628 	btf__free(btf);
10629 	return libbpf_err(err);
10630 }
10631 
10632 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10633 {
10634 	struct bpf_prog_info info;
10635 	__u32 info_len = sizeof(info);
10636 	struct btf *btf;
10637 	int err;
10638 
10639 	memset(&info, 0, info_len);
10640 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10641 	if (err) {
10642 		pr_warn("failed bpf_prog_get_info_by_fd for FD %u: %s\n",
10643 			attach_prog_fd, errstr(err));
10644 		return err;
10645 	}
10646 
10647 	err = -EINVAL;
10648 	if (!info.btf_id) {
10649 		pr_warn("The target program doesn't have BTF\n");
10650 		goto out;
10651 	}
10652 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10653 	err = libbpf_get_error(btf);
10654 	if (err) {
10655 		pr_warn("Failed to get BTF %u of the program: %s\n", info.btf_id, errstr(err));
10656 		goto out;
10657 	}
10658 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10659 	btf__free(btf);
10660 	if (err <= 0) {
10661 		pr_warn("%s is not found in prog's BTF\n", name);
10662 		goto out;
10663 	}
10664 out:
10665 	return err;
10666 }
10667 
10668 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10669 			      enum bpf_attach_type attach_type,
10670 			      int *btf_obj_fd, int *btf_type_id)
10671 {
10672 	int ret, i, mod_len = 0;
10673 	const char *fn_name, *mod_name = NULL;
10674 
10675 	fn_name = strchr(attach_name, ':');
10676 	if (fn_name) {
10677 		mod_name = attach_name;
10678 		mod_len = fn_name - mod_name;
10679 		fn_name++;
10680 	}
10681 
10682 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10683 		ret = find_attach_btf_id(obj->btf_vmlinux,
10684 					 mod_name ? fn_name : attach_name,
10685 					 attach_type);
10686 		if (ret > 0) {
10687 			*btf_obj_fd = 0; /* vmlinux BTF */
10688 			*btf_type_id = ret;
10689 			return 0;
10690 		}
10691 		if (ret != -ENOENT)
10692 			return ret;
10693 	}
10694 
10695 	ret = load_module_btfs(obj);
10696 	if (ret)
10697 		return ret;
10698 
10699 	for (i = 0; i < obj->btf_module_cnt; i++) {
10700 		const struct module_btf *mod = &obj->btf_modules[i];
10701 
10702 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10703 			continue;
10704 
10705 		ret = find_attach_btf_id(mod->btf,
10706 					 mod_name ? fn_name : attach_name,
10707 					 attach_type);
10708 		if (ret > 0) {
10709 			*btf_obj_fd = mod->fd;
10710 			*btf_type_id = ret;
10711 			return 0;
10712 		}
10713 		if (ret == -ENOENT)
10714 			continue;
10715 
10716 		return ret;
10717 	}
10718 
10719 	return -ESRCH;
10720 }
10721 
10722 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10723 				     int *btf_obj_fd, int *btf_type_id)
10724 {
10725 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10726 	__u32 attach_prog_fd = prog->attach_prog_fd;
10727 	int err = 0;
10728 
10729 	/* BPF program's BTF ID */
10730 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10731 		if (!attach_prog_fd) {
10732 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10733 			return -EINVAL;
10734 		}
10735 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10736 		if (err < 0) {
10737 			pr_warn("prog '%s': failed to find BPF program (FD %u) BTF ID for '%s': %s\n",
10738 				prog->name, attach_prog_fd, attach_name, errstr(err));
10739 			return err;
10740 		}
10741 		*btf_obj_fd = 0;
10742 		*btf_type_id = err;
10743 		return 0;
10744 	}
10745 
10746 	/* kernel/module BTF ID */
10747 	if (prog->obj->gen_loader) {
10748 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10749 		*btf_obj_fd = 0;
10750 		*btf_type_id = 1;
10751 	} else {
10752 		err = find_kernel_btf_id(prog->obj, attach_name,
10753 					 attach_type, btf_obj_fd,
10754 					 btf_type_id);
10755 	}
10756 	if (err) {
10757 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10758 			prog->name, attach_name, errstr(err));
10759 		return err;
10760 	}
10761 	return 0;
10762 }
10763 
10764 int libbpf_attach_type_by_name(const char *name,
10765 			       enum bpf_attach_type *attach_type)
10766 {
10767 	char *type_names;
10768 	const struct bpf_sec_def *sec_def;
10769 
10770 	if (!name)
10771 		return libbpf_err(-EINVAL);
10772 
10773 	sec_def = find_sec_def(name);
10774 	if (!sec_def) {
10775 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10776 		type_names = libbpf_get_type_names(true);
10777 		if (type_names != NULL) {
10778 			pr_debug("attachable section(type) names are:%s\n", type_names);
10779 			free(type_names);
10780 		}
10781 
10782 		return libbpf_err(-EINVAL);
10783 	}
10784 
10785 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10786 		return libbpf_err(-EINVAL);
10787 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10788 		return libbpf_err(-EINVAL);
10789 
10790 	*attach_type = sec_def->expected_attach_type;
10791 	return 0;
10792 }
10793 
10794 int bpf_map__fd(const struct bpf_map *map)
10795 {
10796 	if (!map)
10797 		return libbpf_err(-EINVAL);
10798 	if (!map_is_created(map))
10799 		return -1;
10800 	return map->fd;
10801 }
10802 
10803 static bool map_uses_real_name(const struct bpf_map *map)
10804 {
10805 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10806 	 * their user-visible name differs from kernel-visible name. Users see
10807 	 * such map's corresponding ELF section name as a map name.
10808 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10809 	 * maps to know which name has to be returned to the user.
10810 	 */
10811 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10812 		return true;
10813 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10814 		return true;
10815 	return false;
10816 }
10817 
10818 const char *bpf_map__name(const struct bpf_map *map)
10819 {
10820 	if (!map)
10821 		return NULL;
10822 
10823 	if (map_uses_real_name(map))
10824 		return map->real_name;
10825 
10826 	return map->name;
10827 }
10828 
10829 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10830 {
10831 	return map->def.type;
10832 }
10833 
10834 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10835 {
10836 	if (map_is_created(map))
10837 		return libbpf_err(-EBUSY);
10838 	map->def.type = type;
10839 	return 0;
10840 }
10841 
10842 __u32 bpf_map__map_flags(const struct bpf_map *map)
10843 {
10844 	return map->def.map_flags;
10845 }
10846 
10847 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10848 {
10849 	if (map_is_created(map))
10850 		return libbpf_err(-EBUSY);
10851 	map->def.map_flags = flags;
10852 	return 0;
10853 }
10854 
10855 __u64 bpf_map__map_extra(const struct bpf_map *map)
10856 {
10857 	return map->map_extra;
10858 }
10859 
10860 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10861 {
10862 	if (map_is_created(map))
10863 		return libbpf_err(-EBUSY);
10864 	map->map_extra = map_extra;
10865 	return 0;
10866 }
10867 
10868 __u32 bpf_map__numa_node(const struct bpf_map *map)
10869 {
10870 	return map->numa_node;
10871 }
10872 
10873 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10874 {
10875 	if (map_is_created(map))
10876 		return libbpf_err(-EBUSY);
10877 	map->numa_node = numa_node;
10878 	return 0;
10879 }
10880 
10881 __u32 bpf_map__key_size(const struct bpf_map *map)
10882 {
10883 	return map->def.key_size;
10884 }
10885 
10886 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10887 {
10888 	if (map_is_created(map))
10889 		return libbpf_err(-EBUSY);
10890 	map->def.key_size = size;
10891 	return 0;
10892 }
10893 
10894 __u32 bpf_map__value_size(const struct bpf_map *map)
10895 {
10896 	return map->def.value_size;
10897 }
10898 
10899 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10900 {
10901 	struct btf *btf;
10902 	struct btf_type *datasec_type, *var_type;
10903 	struct btf_var_secinfo *var;
10904 	const struct btf_type *array_type;
10905 	const struct btf_array *array;
10906 	int vlen, element_sz, new_array_id;
10907 	__u32 nr_elements;
10908 
10909 	/* check btf existence */
10910 	btf = bpf_object__btf(map->obj);
10911 	if (!btf)
10912 		return -ENOENT;
10913 
10914 	/* verify map is datasec */
10915 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10916 	if (!btf_is_datasec(datasec_type)) {
10917 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10918 			bpf_map__name(map));
10919 		return -EINVAL;
10920 	}
10921 
10922 	/* verify datasec has at least one var */
10923 	vlen = btf_vlen(datasec_type);
10924 	if (vlen == 0) {
10925 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10926 			bpf_map__name(map));
10927 		return -EINVAL;
10928 	}
10929 
10930 	/* verify last var in the datasec is an array */
10931 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10932 	var_type = btf_type_by_id(btf, var->type);
10933 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10934 	if (!btf_is_array(array_type)) {
10935 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10936 			bpf_map__name(map));
10937 		return -EINVAL;
10938 	}
10939 
10940 	/* verify request size aligns with array */
10941 	array = btf_array(array_type);
10942 	element_sz = btf__resolve_size(btf, array->type);
10943 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10944 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10945 			bpf_map__name(map), element_sz, size);
10946 		return -EINVAL;
10947 	}
10948 
10949 	/* create a new array based on the existing array, but with new length */
10950 	nr_elements = (size - var->offset) / element_sz;
10951 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10952 	if (new_array_id < 0)
10953 		return new_array_id;
10954 
10955 	/* adding a new btf type invalidates existing pointers to btf objects,
10956 	 * so refresh pointers before proceeding
10957 	 */
10958 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10959 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10960 	var_type = btf_type_by_id(btf, var->type);
10961 
10962 	/* finally update btf info */
10963 	datasec_type->size = size;
10964 	var->size = size - var->offset;
10965 	var_type->type = new_array_id;
10966 
10967 	return 0;
10968 }
10969 
10970 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10971 {
10972 	if (map_is_created(map))
10973 		return libbpf_err(-EBUSY);
10974 
10975 	if (map->mmaped) {
10976 		size_t mmap_old_sz, mmap_new_sz;
10977 		int err;
10978 
10979 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10980 			return libbpf_err(-EOPNOTSUPP);
10981 
10982 		mmap_old_sz = bpf_map_mmap_sz(map);
10983 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10984 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10985 		if (err) {
10986 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10987 				bpf_map__name(map), errstr(err));
10988 			return libbpf_err(err);
10989 		}
10990 		err = map_btf_datasec_resize(map, size);
10991 		if (err && err != -ENOENT) {
10992 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10993 				bpf_map__name(map), errstr(err));
10994 			map->btf_value_type_id = 0;
10995 			map->btf_key_type_id = 0;
10996 		}
10997 	}
10998 
10999 	map->def.value_size = size;
11000 	return 0;
11001 }
11002 
11003 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
11004 {
11005 	return map ? map->btf_key_type_id : 0;
11006 }
11007 
11008 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
11009 {
11010 	return map ? map->btf_value_type_id : 0;
11011 }
11012 
11013 int bpf_map__set_initial_value(struct bpf_map *map,
11014 			       const void *data, size_t size)
11015 {
11016 	size_t actual_sz;
11017 
11018 	if (map_is_created(map))
11019 		return libbpf_err(-EBUSY);
11020 
11021 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
11022 		return libbpf_err(-EINVAL);
11023 
11024 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11025 		actual_sz = map->obj->arena_data_sz;
11026 	else
11027 		actual_sz = map->def.value_size;
11028 	if (size != actual_sz)
11029 		return libbpf_err(-EINVAL);
11030 
11031 	memcpy(map->mmaped, data, size);
11032 	return 0;
11033 }
11034 
11035 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
11036 {
11037 	if (bpf_map__is_struct_ops(map)) {
11038 		if (psize)
11039 			*psize = map->def.value_size;
11040 		return map->st_ops->data;
11041 	}
11042 
11043 	if (!map->mmaped)
11044 		return NULL;
11045 
11046 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11047 		*psize = map->obj->arena_data_sz;
11048 	else
11049 		*psize = map->def.value_size;
11050 
11051 	return map->mmaped;
11052 }
11053 
11054 bool bpf_map__is_internal(const struct bpf_map *map)
11055 {
11056 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
11057 }
11058 
11059 __u32 bpf_map__ifindex(const struct bpf_map *map)
11060 {
11061 	return map->map_ifindex;
11062 }
11063 
11064 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
11065 {
11066 	if (map_is_created(map))
11067 		return libbpf_err(-EBUSY);
11068 	map->map_ifindex = ifindex;
11069 	return 0;
11070 }
11071 
11072 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
11073 {
11074 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
11075 		pr_warn("error: unsupported map type\n");
11076 		return libbpf_err(-EINVAL);
11077 	}
11078 	if (map->inner_map_fd != -1) {
11079 		pr_warn("error: inner_map_fd already specified\n");
11080 		return libbpf_err(-EINVAL);
11081 	}
11082 	if (map->inner_map) {
11083 		bpf_map__destroy(map->inner_map);
11084 		zfree(&map->inner_map);
11085 	}
11086 	map->inner_map_fd = fd;
11087 	return 0;
11088 }
11089 
11090 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
11091 {
11092 	if (map_is_created(map)) {
11093 		pr_warn("exclusive programs must be set before map creation\n");
11094 		return libbpf_err(-EINVAL);
11095 	}
11096 
11097 	if (map->obj != prog->obj) {
11098 		pr_warn("excl_prog and map must be from the same bpf object\n");
11099 		return libbpf_err(-EINVAL);
11100 	}
11101 
11102 	map->excl_prog = prog;
11103 	return 0;
11104 }
11105 
11106 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11107 {
11108 	return map->excl_prog;
11109 }
11110 
11111 static struct bpf_map *
11112 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11113 {
11114 	ssize_t idx;
11115 	struct bpf_map *s, *e;
11116 
11117 	if (!obj || !obj->maps)
11118 		return errno = EINVAL, NULL;
11119 
11120 	s = obj->maps;
11121 	e = obj->maps + obj->nr_maps;
11122 
11123 	if ((m < s) || (m >= e)) {
11124 		pr_warn("error in %s: map handler doesn't belong to object\n",
11125 			 __func__);
11126 		return errno = EINVAL, NULL;
11127 	}
11128 
11129 	idx = (m - obj->maps) + i;
11130 	if (idx >= obj->nr_maps || idx < 0)
11131 		return NULL;
11132 	return &obj->maps[idx];
11133 }
11134 
11135 struct bpf_map *
11136 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11137 {
11138 	if (prev == NULL && obj != NULL)
11139 		return obj->maps;
11140 
11141 	return __bpf_map__iter(prev, obj, 1);
11142 }
11143 
11144 struct bpf_map *
11145 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11146 {
11147 	if (next == NULL && obj != NULL) {
11148 		if (!obj->nr_maps)
11149 			return NULL;
11150 		return obj->maps + obj->nr_maps - 1;
11151 	}
11152 
11153 	return __bpf_map__iter(next, obj, -1);
11154 }
11155 
11156 struct bpf_map *
11157 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11158 {
11159 	struct bpf_map *pos;
11160 
11161 	bpf_object__for_each_map(pos, obj) {
11162 		/* if it's a special internal map name (which always starts
11163 		 * with dot) then check if that special name matches the
11164 		 * real map name (ELF section name)
11165 		 */
11166 		if (name[0] == '.') {
11167 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11168 				return pos;
11169 			continue;
11170 		}
11171 		/* otherwise map name has to be an exact match */
11172 		if (map_uses_real_name(pos)) {
11173 			if (strcmp(pos->real_name, name) == 0)
11174 				return pos;
11175 			continue;
11176 		}
11177 		if (strcmp(pos->name, name) == 0)
11178 			return pos;
11179 	}
11180 	return errno = ENOENT, NULL;
11181 }
11182 
11183 int
11184 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11185 {
11186 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11187 }
11188 
11189 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11190 			   size_t value_sz, bool check_value_sz, __u64 flags)
11191 {
11192 	if (!map_is_created(map)) /* map is not yet created */
11193 		return -ENOENT;
11194 
11195 	if (map->def.key_size != key_sz) {
11196 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11197 			map->name, key_sz, map->def.key_size);
11198 		return -EINVAL;
11199 	}
11200 
11201 	if (map->fd < 0) {
11202 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11203 		return -EINVAL;
11204 	}
11205 
11206 	if (!check_value_sz)
11207 		return 0;
11208 
11209 	switch (map->def.type) {
11210 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11211 	case BPF_MAP_TYPE_PERCPU_HASH:
11212 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11213 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11214 		int num_cpu = libbpf_num_possible_cpus();
11215 		size_t elem_sz = roundup(map->def.value_size, 8);
11216 
11217 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11218 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11219 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11220 					map->name);
11221 				return -EINVAL;
11222 			}
11223 			if (map->def.value_size != value_sz) {
11224 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11225 					map->name, value_sz, map->def.value_size);
11226 				return -EINVAL;
11227 			}
11228 			break;
11229 		}
11230 
11231 		if (value_sz != num_cpu * elem_sz) {
11232 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zu\n",
11233 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11234 			return -EINVAL;
11235 		}
11236 		break;
11237 	}
11238 	default:
11239 		if (map->def.value_size != value_sz) {
11240 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11241 				map->name, value_sz, map->def.value_size);
11242 			return -EINVAL;
11243 		}
11244 		break;
11245 	}
11246 	return 0;
11247 }
11248 
11249 int bpf_map__lookup_elem(const struct bpf_map *map,
11250 			 const void *key, size_t key_sz,
11251 			 void *value, size_t value_sz, __u64 flags)
11252 {
11253 	int err;
11254 
11255 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11256 	if (err)
11257 		return libbpf_err(err);
11258 
11259 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11260 }
11261 
11262 int bpf_map__update_elem(const struct bpf_map *map,
11263 			 const void *key, size_t key_sz,
11264 			 const void *value, size_t value_sz, __u64 flags)
11265 {
11266 	int err;
11267 
11268 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11269 	if (err)
11270 		return libbpf_err(err);
11271 
11272 	return bpf_map_update_elem(map->fd, key, value, flags);
11273 }
11274 
11275 int bpf_map__delete_elem(const struct bpf_map *map,
11276 			 const void *key, size_t key_sz, __u64 flags)
11277 {
11278 	int err;
11279 
11280 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11281 	if (err)
11282 		return libbpf_err(err);
11283 
11284 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11285 }
11286 
11287 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11288 				    const void *key, size_t key_sz,
11289 				    void *value, size_t value_sz, __u64 flags)
11290 {
11291 	int err;
11292 
11293 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11294 	if (err)
11295 		return libbpf_err(err);
11296 
11297 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11298 }
11299 
11300 int bpf_map__get_next_key(const struct bpf_map *map,
11301 			  const void *cur_key, void *next_key, size_t key_sz)
11302 {
11303 	int err;
11304 
11305 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11306 	if (err)
11307 		return libbpf_err(err);
11308 
11309 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11310 }
11311 
11312 long libbpf_get_error(const void *ptr)
11313 {
11314 	if (!IS_ERR_OR_NULL(ptr))
11315 		return 0;
11316 
11317 	if (IS_ERR(ptr))
11318 		errno = -PTR_ERR(ptr);
11319 
11320 	/* If ptr == NULL, then errno should be already set by the failing
11321 	 * API, because libbpf never returns NULL on success and it now always
11322 	 * sets errno on error. So no extra errno handling for ptr == NULL
11323 	 * case.
11324 	 */
11325 	return -errno;
11326 }
11327 
11328 /* Replace link's underlying BPF program with the new one */
11329 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11330 {
11331 	int ret;
11332 	int prog_fd = bpf_program__fd(prog);
11333 
11334 	if (prog_fd < 0) {
11335 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11336 			prog->name);
11337 		return libbpf_err(-EINVAL);
11338 	}
11339 
11340 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11341 	return libbpf_err_errno(ret);
11342 }
11343 
11344 /* Release "ownership" of underlying BPF resource (typically, BPF program
11345  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11346  * link, when destructed through bpf_link__destroy() call won't attempt to
11347  * detach/unregisted that BPF resource. This is useful in situations where,
11348  * say, attached BPF program has to outlive userspace program that attached it
11349  * in the system. Depending on type of BPF program, though, there might be
11350  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11351  * exit of userspace program doesn't trigger automatic detachment and clean up
11352  * inside the kernel.
11353  */
11354 void bpf_link__disconnect(struct bpf_link *link)
11355 {
11356 	link->disconnected = true;
11357 }
11358 
11359 int bpf_link__destroy(struct bpf_link *link)
11360 {
11361 	int err = 0;
11362 
11363 	if (IS_ERR_OR_NULL(link))
11364 		return 0;
11365 
11366 	if (!link->disconnected && link->detach)
11367 		err = link->detach(link);
11368 	if (link->pin_path)
11369 		free(link->pin_path);
11370 	if (link->dealloc)
11371 		link->dealloc(link);
11372 	else
11373 		free(link);
11374 
11375 	return libbpf_err(err);
11376 }
11377 
11378 int bpf_link__fd(const struct bpf_link *link)
11379 {
11380 	return link->fd;
11381 }
11382 
11383 const char *bpf_link__pin_path(const struct bpf_link *link)
11384 {
11385 	return link->pin_path;
11386 }
11387 
11388 static int bpf_link__detach_fd(struct bpf_link *link)
11389 {
11390 	return libbpf_err_errno(close(link->fd));
11391 }
11392 
11393 struct bpf_link *bpf_link__open(const char *path)
11394 {
11395 	struct bpf_link *link;
11396 	int fd;
11397 
11398 	fd = bpf_obj_get(path);
11399 	if (fd < 0) {
11400 		fd = -errno;
11401 		pr_warn("failed to open link at %s: %d\n", path, fd);
11402 		return libbpf_err_ptr(fd);
11403 	}
11404 
11405 	link = calloc(1, sizeof(*link));
11406 	if (!link) {
11407 		close(fd);
11408 		return libbpf_err_ptr(-ENOMEM);
11409 	}
11410 	link->detach = &bpf_link__detach_fd;
11411 	link->fd = fd;
11412 
11413 	link->pin_path = strdup(path);
11414 	if (!link->pin_path) {
11415 		bpf_link__destroy(link);
11416 		return libbpf_err_ptr(-ENOMEM);
11417 	}
11418 
11419 	return link;
11420 }
11421 
11422 int bpf_link__detach(struct bpf_link *link)
11423 {
11424 	return bpf_link_detach(link->fd) ? -errno : 0;
11425 }
11426 
11427 int bpf_link__pin(struct bpf_link *link, const char *path)
11428 {
11429 	int err;
11430 
11431 	if (link->pin_path)
11432 		return libbpf_err(-EBUSY);
11433 	err = make_parent_dir(path);
11434 	if (err)
11435 		return libbpf_err(err);
11436 	err = check_path(path);
11437 	if (err)
11438 		return libbpf_err(err);
11439 
11440 	link->pin_path = strdup(path);
11441 	if (!link->pin_path)
11442 		return libbpf_err(-ENOMEM);
11443 
11444 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11445 		err = -errno;
11446 		zfree(&link->pin_path);
11447 		return libbpf_err(err);
11448 	}
11449 
11450 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11451 	return 0;
11452 }
11453 
11454 int bpf_link__unpin(struct bpf_link *link)
11455 {
11456 	int err;
11457 
11458 	if (!link->pin_path)
11459 		return libbpf_err(-EINVAL);
11460 
11461 	err = unlink(link->pin_path);
11462 	if (err != 0)
11463 		return -errno;
11464 
11465 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11466 	zfree(&link->pin_path);
11467 	return 0;
11468 }
11469 
11470 struct bpf_link_perf {
11471 	struct bpf_link link;
11472 	int perf_event_fd;
11473 	/* legacy kprobe support: keep track of probe identifier and type */
11474 	char *legacy_probe_name;
11475 	bool legacy_is_kprobe;
11476 	bool legacy_is_retprobe;
11477 };
11478 
11479 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11480 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11481 
11482 static int bpf_link_perf_detach(struct bpf_link *link)
11483 {
11484 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11485 	int err = 0;
11486 
11487 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11488 		err = -errno;
11489 
11490 	if (perf_link->perf_event_fd != link->fd)
11491 		close(perf_link->perf_event_fd);
11492 	close(link->fd);
11493 
11494 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11495 	if (perf_link->legacy_probe_name) {
11496 		if (perf_link->legacy_is_kprobe) {
11497 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11498 							 perf_link->legacy_is_retprobe);
11499 		} else {
11500 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11501 							 perf_link->legacy_is_retprobe);
11502 		}
11503 	}
11504 
11505 	return err;
11506 }
11507 
11508 static void bpf_link_perf_dealloc(struct bpf_link *link)
11509 {
11510 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11511 
11512 	free(perf_link->legacy_probe_name);
11513 	free(perf_link);
11514 }
11515 
11516 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11517 						     const struct bpf_perf_event_opts *opts)
11518 {
11519 	struct bpf_link_perf *link;
11520 	int prog_fd, link_fd = -1, err;
11521 	bool force_ioctl_attach;
11522 
11523 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11524 		return libbpf_err_ptr(-EINVAL);
11525 
11526 	if (pfd < 0) {
11527 		pr_warn("prog '%s': invalid perf event FD %d\n",
11528 			prog->name, pfd);
11529 		return libbpf_err_ptr(-EINVAL);
11530 	}
11531 	prog_fd = bpf_program__fd(prog);
11532 	if (prog_fd < 0) {
11533 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11534 			prog->name);
11535 		return libbpf_err_ptr(-EINVAL);
11536 	}
11537 
11538 	link = calloc(1, sizeof(*link));
11539 	if (!link)
11540 		return libbpf_err_ptr(-ENOMEM);
11541 	link->link.detach = &bpf_link_perf_detach;
11542 	link->link.dealloc = &bpf_link_perf_dealloc;
11543 	link->perf_event_fd = pfd;
11544 
11545 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11546 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11547 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11548 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11549 
11550 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11551 		if (link_fd < 0) {
11552 			err = -errno;
11553 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11554 				prog->name, pfd, errstr(err));
11555 			goto err_out;
11556 		}
11557 		link->link.fd = link_fd;
11558 	} else {
11559 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11560 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11561 			err = -EOPNOTSUPP;
11562 			goto err_out;
11563 		}
11564 
11565 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11566 			err = -errno;
11567 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11568 				prog->name, pfd, errstr(err));
11569 			if (err == -EPROTO)
11570 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11571 					prog->name, pfd);
11572 			goto err_out;
11573 		}
11574 		link->link.fd = pfd;
11575 	}
11576 
11577 	if (!OPTS_GET(opts, dont_enable, false)) {
11578 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11579 			err = -errno;
11580 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11581 				prog->name, pfd, errstr(err));
11582 			goto err_out;
11583 		}
11584 	}
11585 
11586 	return &link->link;
11587 err_out:
11588 	if (link_fd >= 0)
11589 		close(link_fd);
11590 	free(link);
11591 	return libbpf_err_ptr(err);
11592 }
11593 
11594 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11595 {
11596 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11597 }
11598 
11599 /*
11600  * this function is expected to parse integer in the range of [0, 2^31-1] from
11601  * given file using scanf format string fmt. If actual parsed value is
11602  * negative, the result might be indistinguishable from error
11603  */
11604 static int parse_uint_from_file(const char *file, const char *fmt)
11605 {
11606 	int err, ret;
11607 	FILE *f;
11608 
11609 	f = fopen(file, "re");
11610 	if (!f) {
11611 		err = -errno;
11612 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11613 		return err;
11614 	}
11615 	err = fscanf(f, fmt, &ret);
11616 	if (err != 1) {
11617 		err = err == EOF ? -EIO : -errno;
11618 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11619 		fclose(f);
11620 		return err;
11621 	}
11622 	fclose(f);
11623 	return ret;
11624 }
11625 
11626 static int determine_kprobe_perf_type(void)
11627 {
11628 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11629 
11630 	return parse_uint_from_file(file, "%d\n");
11631 }
11632 
11633 static int determine_uprobe_perf_type(void)
11634 {
11635 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11636 
11637 	return parse_uint_from_file(file, "%d\n");
11638 }
11639 
11640 static int determine_kprobe_retprobe_bit(void)
11641 {
11642 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11643 
11644 	return parse_uint_from_file(file, "config:%d\n");
11645 }
11646 
11647 static int determine_uprobe_retprobe_bit(void)
11648 {
11649 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11650 
11651 	return parse_uint_from_file(file, "config:%d\n");
11652 }
11653 
11654 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11655 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11656 
11657 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11658 				 uint64_t offset, int pid, size_t ref_ctr_off)
11659 {
11660 	const size_t attr_sz = sizeof(struct perf_event_attr);
11661 	struct perf_event_attr attr;
11662 	int type, pfd;
11663 
11664 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11665 		return -EINVAL;
11666 
11667 	memset(&attr, 0, attr_sz);
11668 
11669 	type = uprobe ? determine_uprobe_perf_type()
11670 		      : determine_kprobe_perf_type();
11671 	if (type < 0) {
11672 		pr_warn("failed to determine %s perf type: %s\n",
11673 			uprobe ? "uprobe" : "kprobe",
11674 			errstr(type));
11675 		return type;
11676 	}
11677 	if (retprobe) {
11678 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11679 				 : determine_kprobe_retprobe_bit();
11680 
11681 		if (bit < 0) {
11682 			pr_warn("failed to determine %s retprobe bit: %s\n",
11683 				uprobe ? "uprobe" : "kprobe",
11684 				errstr(bit));
11685 			return bit;
11686 		}
11687 		attr.config |= 1 << bit;
11688 	}
11689 	attr.size = attr_sz;
11690 	attr.type = type;
11691 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11692 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11693 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11694 
11695 	/* pid filter is meaningful only for uprobes */
11696 	pfd = syscall(__NR_perf_event_open, &attr,
11697 		      pid < 0 ? -1 : pid /* pid */,
11698 		      pid == -1 ? 0 : -1 /* cpu */,
11699 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11700 	return pfd >= 0 ? pfd : -errno;
11701 }
11702 
11703 static int append_to_file(const char *file, const char *fmt, ...)
11704 {
11705 	int fd, n, err = 0;
11706 	va_list ap;
11707 	char buf[1024];
11708 
11709 	va_start(ap, fmt);
11710 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11711 	va_end(ap);
11712 
11713 	if (n < 0 || n >= sizeof(buf))
11714 		return -EINVAL;
11715 
11716 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11717 	if (fd < 0)
11718 		return -errno;
11719 
11720 	if (write(fd, buf, n) < 0)
11721 		err = -errno;
11722 
11723 	close(fd);
11724 	return err;
11725 }
11726 
11727 #define DEBUGFS "/sys/kernel/debug/tracing"
11728 #define TRACEFS "/sys/kernel/tracing"
11729 
11730 static bool use_debugfs(void)
11731 {
11732 	static int has_debugfs = -1;
11733 
11734 	if (has_debugfs < 0)
11735 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11736 
11737 	return has_debugfs == 1;
11738 }
11739 
11740 static const char *tracefs_path(void)
11741 {
11742 	return use_debugfs() ? DEBUGFS : TRACEFS;
11743 }
11744 
11745 static const char *tracefs_kprobe_events(void)
11746 {
11747 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11748 }
11749 
11750 static const char *tracefs_uprobe_events(void)
11751 {
11752 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11753 }
11754 
11755 static const char *tracefs_available_filter_functions(void)
11756 {
11757 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11758 			     : TRACEFS"/available_filter_functions";
11759 }
11760 
11761 static const char *tracefs_available_filter_functions_addrs(void)
11762 {
11763 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11764 			     : TRACEFS"/available_filter_functions_addrs";
11765 }
11766 
11767 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11768 					const char *name, size_t offset)
11769 {
11770 	static int index = 0;
11771 	int i;
11772 
11773 	snprintf(buf, buf_sz, "libbpf_%d_%d_%s_0x%zx", getpid(),
11774 		 __sync_fetch_and_add(&index, 1), name, offset);
11775 
11776 	/* sanitize name in the probe name */
11777 	for (i = 0; buf[i]; i++) {
11778 		if (!isalnum(buf[i]))
11779 			buf[i] = '_';
11780 	}
11781 }
11782 
11783 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11784 				   const char *kfunc_name, size_t offset)
11785 {
11786 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11787 			      retprobe ? 'r' : 'p',
11788 			      retprobe ? "kretprobes" : "kprobes",
11789 			      probe_name, kfunc_name, offset);
11790 }
11791 
11792 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11793 {
11794 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11795 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11796 }
11797 
11798 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11799 {
11800 	char file[256];
11801 
11802 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11803 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11804 
11805 	return parse_uint_from_file(file, "%d\n");
11806 }
11807 
11808 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11809 					 const char *kfunc_name, size_t offset, int pid)
11810 {
11811 	const size_t attr_sz = sizeof(struct perf_event_attr);
11812 	struct perf_event_attr attr;
11813 	int type, pfd, err;
11814 
11815 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11816 	if (err < 0) {
11817 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11818 			kfunc_name, offset,
11819 			errstr(err));
11820 		return err;
11821 	}
11822 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11823 	if (type < 0) {
11824 		err = type;
11825 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11826 			kfunc_name, offset,
11827 			errstr(err));
11828 		goto err_clean_legacy;
11829 	}
11830 
11831 	memset(&attr, 0, attr_sz);
11832 	attr.size = attr_sz;
11833 	attr.config = type;
11834 	attr.type = PERF_TYPE_TRACEPOINT;
11835 
11836 	pfd = syscall(__NR_perf_event_open, &attr,
11837 		      pid < 0 ? -1 : pid, /* pid */
11838 		      pid == -1 ? 0 : -1, /* cpu */
11839 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11840 	if (pfd < 0) {
11841 		err = -errno;
11842 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11843 			errstr(err));
11844 		goto err_clean_legacy;
11845 	}
11846 	return pfd;
11847 
11848 err_clean_legacy:
11849 	/* Clear the newly added legacy kprobe_event */
11850 	remove_kprobe_event_legacy(probe_name, retprobe);
11851 	return err;
11852 }
11853 
11854 static const char *arch_specific_syscall_pfx(void)
11855 {
11856 #if defined(__x86_64__)
11857 	return "x64";
11858 #elif defined(__i386__)
11859 	return "ia32";
11860 #elif defined(__s390x__)
11861 	return "s390x";
11862 #elif defined(__arm__)
11863 	return "arm";
11864 #elif defined(__aarch64__)
11865 	return "arm64";
11866 #elif defined(__mips__)
11867 	return "mips";
11868 #elif defined(__riscv)
11869 	return "riscv";
11870 #elif defined(__powerpc__)
11871 	return "powerpc";
11872 #elif defined(__powerpc64__)
11873 	return "powerpc64";
11874 #else
11875 	return NULL;
11876 #endif
11877 }
11878 
11879 int probe_kern_syscall_wrapper(int token_fd)
11880 {
11881 	char syscall_name[64];
11882 	const char *ksys_pfx;
11883 
11884 	ksys_pfx = arch_specific_syscall_pfx();
11885 	if (!ksys_pfx)
11886 		return 0;
11887 
11888 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11889 
11890 	if (determine_kprobe_perf_type() >= 0) {
11891 		int pfd;
11892 
11893 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11894 		if (pfd >= 0)
11895 			close(pfd);
11896 
11897 		return pfd >= 0 ? 1 : 0;
11898 	} else { /* legacy mode */
11899 		char probe_name[MAX_EVENT_NAME_LEN];
11900 
11901 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11902 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11903 			return 0;
11904 
11905 		(void)remove_kprobe_event_legacy(probe_name, false);
11906 		return 1;
11907 	}
11908 }
11909 
11910 struct bpf_link *
11911 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11912 				const char *func_name,
11913 				const struct bpf_kprobe_opts *opts)
11914 {
11915 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11916 	enum probe_attach_mode attach_mode;
11917 	char *legacy_probe = NULL;
11918 	struct bpf_link *link;
11919 	size_t offset;
11920 	bool retprobe, legacy;
11921 	int pfd, err;
11922 
11923 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11924 		return libbpf_err_ptr(-EINVAL);
11925 
11926 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11927 	retprobe = OPTS_GET(opts, retprobe, false);
11928 	offset = OPTS_GET(opts, offset, 0);
11929 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11930 
11931 	legacy = determine_kprobe_perf_type() < 0;
11932 	switch (attach_mode) {
11933 	case PROBE_ATTACH_MODE_LEGACY:
11934 		legacy = true;
11935 		pe_opts.force_ioctl_attach = true;
11936 		break;
11937 	case PROBE_ATTACH_MODE_PERF:
11938 		if (legacy)
11939 			return libbpf_err_ptr(-ENOTSUP);
11940 		pe_opts.force_ioctl_attach = true;
11941 		break;
11942 	case PROBE_ATTACH_MODE_LINK:
11943 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11944 			return libbpf_err_ptr(-ENOTSUP);
11945 		break;
11946 	case PROBE_ATTACH_MODE_DEFAULT:
11947 		break;
11948 	default:
11949 		return libbpf_err_ptr(-EINVAL);
11950 	}
11951 	if (!func_name && legacy)
11952 		return libbpf_err_ptr(-EOPNOTSUPP);
11953 
11954 	if (!legacy) {
11955 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11956 					    func_name, offset,
11957 					    -1 /* pid */, 0 /* ref_ctr_off */);
11958 	} else {
11959 		char probe_name[MAX_EVENT_NAME_LEN];
11960 
11961 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11962 					    func_name, offset);
11963 
11964 		legacy_probe = strdup(probe_name);
11965 		if (!legacy_probe)
11966 			return libbpf_err_ptr(-ENOMEM);
11967 
11968 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11969 						    offset, -1 /* pid */);
11970 	}
11971 	if (pfd < 0) {
11972 		err = pfd;
11973 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
11974 			prog->name, retprobe ? "kretprobe" : "kprobe",
11975 			func_name ?: "", func_name ? "+" : "",
11976 			offset, errstr(err));
11977 		goto err_out;
11978 	}
11979 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11980 	err = libbpf_get_error(link);
11981 	if (err) {
11982 		close(pfd);
11983 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
11984 			prog->name, retprobe ? "kretprobe" : "kprobe",
11985 			func_name ?: "", func_name ? "+" : "",
11986 			offset, errstr(err));
11987 		goto err_clean_legacy;
11988 	}
11989 	if (legacy) {
11990 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11991 
11992 		perf_link->legacy_probe_name = legacy_probe;
11993 		perf_link->legacy_is_kprobe = true;
11994 		perf_link->legacy_is_retprobe = retprobe;
11995 	}
11996 
11997 	return link;
11998 
11999 err_clean_legacy:
12000 	if (legacy)
12001 		remove_kprobe_event_legacy(legacy_probe, retprobe);
12002 err_out:
12003 	free(legacy_probe);
12004 	return libbpf_err_ptr(err);
12005 }
12006 
12007 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
12008 					    bool retprobe,
12009 					    const char *func_name)
12010 {
12011 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
12012 		.retprobe = retprobe,
12013 	);
12014 
12015 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
12016 }
12017 
12018 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
12019 					      const char *syscall_name,
12020 					      const struct bpf_ksyscall_opts *opts)
12021 {
12022 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
12023 	char func_name[128];
12024 
12025 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
12026 		return libbpf_err_ptr(-EINVAL);
12027 
12028 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
12029 		/* arch_specific_syscall_pfx() should never return NULL here
12030 		 * because it is guarded by kernel_supports(). However, since
12031 		 * compiler does not know that we have an explicit conditional
12032 		 * as well.
12033 		 */
12034 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
12035 			 arch_specific_syscall_pfx() ? : "", syscall_name);
12036 	} else {
12037 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
12038 	}
12039 
12040 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
12041 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12042 
12043 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
12044 }
12045 
12046 /* Adapted from perf/util/string.c */
12047 bool glob_match(const char *str, const char *pat)
12048 {
12049 	while (*str && *pat && *pat != '*') {
12050 		if (*pat == '?') {      /* Matches any single character */
12051 			str++;
12052 			pat++;
12053 			continue;
12054 		}
12055 		if (*str != *pat)
12056 			return false;
12057 		str++;
12058 		pat++;
12059 	}
12060 	/* Check wild card */
12061 	if (*pat == '*') {
12062 		while (*pat == '*')
12063 			pat++;
12064 		if (!*pat) /* Tail wild card matches all */
12065 			return true;
12066 		while (*str)
12067 			if (glob_match(str++, pat))
12068 				return true;
12069 	}
12070 	return !*str && !*pat;
12071 }
12072 
12073 struct kprobe_multi_resolve {
12074 	const char *pattern;
12075 	unsigned long *addrs;
12076 	size_t cap;
12077 	size_t cnt;
12078 };
12079 
12080 struct avail_kallsyms_data {
12081 	char **syms;
12082 	size_t cnt;
12083 	struct kprobe_multi_resolve *res;
12084 };
12085 
12086 static int avail_func_cmp(const void *a, const void *b)
12087 {
12088 	return strcmp(*(const char **)a, *(const char **)b);
12089 }
12090 
12091 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
12092 			     const char *sym_name, void *ctx)
12093 {
12094 	struct avail_kallsyms_data *data = ctx;
12095 	struct kprobe_multi_resolve *res = data->res;
12096 	int err;
12097 
12098 	if (!glob_match(sym_name, res->pattern))
12099 		return 0;
12100 
12101 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12102 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12103 		 * function names reported in available_filter_functions, but
12104 		 * don't do so for kallsyms. While this is clearly a kernel
12105 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12106 		 * make multi-kprobe usability a bit better: if no match is
12107 		 * found, we will strip .llvm. suffix and try one more time.
12108 		 *
12109 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12110 		 */
12111 		char sym_trim[256], *psym_trim = sym_trim;
12112 		const char *sym_sfx;
12113 
12114 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12115 			return 0;
12116 
12117 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12118 		 * coercion differences and get proper `const char **` pointer
12119 		 * which avail_func_cmp() expects
12120 		 */
12121 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12122 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12123 			return 0;
12124 	}
12125 
12126 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12127 	if (err)
12128 		return err;
12129 
12130 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12131 	return 0;
12132 }
12133 
12134 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12135 {
12136 	const char *available_functions_file = tracefs_available_filter_functions();
12137 	struct avail_kallsyms_data data;
12138 	char sym_name[500];
12139 	FILE *f;
12140 	int err = 0, ret, i;
12141 	char **syms = NULL;
12142 	size_t cap = 0, cnt = 0;
12143 
12144 	f = fopen(available_functions_file, "re");
12145 	if (!f) {
12146 		err = -errno;
12147 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12148 		return err;
12149 	}
12150 
12151 	while (true) {
12152 		char *name;
12153 
12154 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12155 		if (ret == EOF && feof(f))
12156 			break;
12157 
12158 		if (ret != 1) {
12159 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12160 			err = -EINVAL;
12161 			goto cleanup;
12162 		}
12163 
12164 		if (!glob_match(sym_name, res->pattern))
12165 			continue;
12166 
12167 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12168 		if (err)
12169 			goto cleanup;
12170 
12171 		name = strdup(sym_name);
12172 		if (!name) {
12173 			err = -errno;
12174 			goto cleanup;
12175 		}
12176 
12177 		syms[cnt++] = name;
12178 	}
12179 
12180 	/* no entries found, bail out */
12181 	if (cnt == 0) {
12182 		err = -ENOENT;
12183 		goto cleanup;
12184 	}
12185 
12186 	/* sort available functions */
12187 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12188 
12189 	data.syms = syms;
12190 	data.res = res;
12191 	data.cnt = cnt;
12192 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12193 
12194 	if (res->cnt == 0)
12195 		err = -ENOENT;
12196 
12197 cleanup:
12198 	for (i = 0; i < cnt; i++)
12199 		free((char *)syms[i]);
12200 	free(syms);
12201 
12202 	fclose(f);
12203 	return err;
12204 }
12205 
12206 static bool has_available_filter_functions_addrs(void)
12207 {
12208 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12209 }
12210 
12211 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12212 {
12213 	const char *available_path = tracefs_available_filter_functions_addrs();
12214 	char sym_name[500];
12215 	FILE *f;
12216 	int ret, err = 0;
12217 	unsigned long long sym_addr;
12218 
12219 	f = fopen(available_path, "re");
12220 	if (!f) {
12221 		err = -errno;
12222 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12223 		return err;
12224 	}
12225 
12226 	while (true) {
12227 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12228 		if (ret == EOF && feof(f))
12229 			break;
12230 
12231 		if (ret != 2) {
12232 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12233 				ret);
12234 			err = -EINVAL;
12235 			goto cleanup;
12236 		}
12237 
12238 		if (!glob_match(sym_name, res->pattern))
12239 			continue;
12240 
12241 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12242 					sizeof(*res->addrs), res->cnt + 1);
12243 		if (err)
12244 			goto cleanup;
12245 
12246 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12247 	}
12248 
12249 	if (res->cnt == 0)
12250 		err = -ENOENT;
12251 
12252 cleanup:
12253 	fclose(f);
12254 	return err;
12255 }
12256 
12257 struct bpf_link *
12258 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12259 				      const char *pattern,
12260 				      const struct bpf_kprobe_multi_opts *opts)
12261 {
12262 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12263 	struct kprobe_multi_resolve res = {
12264 		.pattern = pattern,
12265 	};
12266 	enum bpf_attach_type attach_type;
12267 	struct bpf_link *link = NULL;
12268 	const unsigned long *addrs;
12269 	int err, link_fd, prog_fd;
12270 	bool retprobe, session, unique_match;
12271 	const __u64 *cookies;
12272 	const char **syms;
12273 	size_t cnt;
12274 
12275 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12276 		return libbpf_err_ptr(-EINVAL);
12277 
12278 	prog_fd = bpf_program__fd(prog);
12279 	if (prog_fd < 0) {
12280 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12281 			prog->name);
12282 		return libbpf_err_ptr(-EINVAL);
12283 	}
12284 
12285 	syms    = OPTS_GET(opts, syms, false);
12286 	addrs   = OPTS_GET(opts, addrs, false);
12287 	cnt     = OPTS_GET(opts, cnt, false);
12288 	cookies = OPTS_GET(opts, cookies, false);
12289 	unique_match = OPTS_GET(opts, unique_match, false);
12290 
12291 	if (!pattern && !addrs && !syms)
12292 		return libbpf_err_ptr(-EINVAL);
12293 	if (pattern && (addrs || syms || cookies || cnt))
12294 		return libbpf_err_ptr(-EINVAL);
12295 	if (!pattern && !cnt)
12296 		return libbpf_err_ptr(-EINVAL);
12297 	if (!pattern && unique_match)
12298 		return libbpf_err_ptr(-EINVAL);
12299 	if (addrs && syms)
12300 		return libbpf_err_ptr(-EINVAL);
12301 
12302 	/*
12303 	 * Exact function name (no wildcards) without unique_match:
12304 	 * bypass kallsyms parsing and pass the symbol directly to the
12305 	 * kernel via syms[] array.  When unique_match is set, fall
12306 	 * through to the slow path which detects duplicate symbols.
12307 	 */
12308 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12309 		syms = &pattern;
12310 		cnt = 1;
12311 	} else if (pattern) {
12312 		if (has_available_filter_functions_addrs())
12313 			err = libbpf_available_kprobes_parse(&res);
12314 		else
12315 			err = libbpf_available_kallsyms_parse(&res);
12316 		if (err)
12317 			goto error;
12318 
12319 		if (unique_match && res.cnt != 1) {
12320 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12321 				prog->name, pattern, res.cnt);
12322 			err = -EINVAL;
12323 			goto error;
12324 		}
12325 
12326 		addrs = res.addrs;
12327 		cnt = res.cnt;
12328 	}
12329 
12330 	retprobe = OPTS_GET(opts, retprobe, false);
12331 	session  = OPTS_GET(opts, session, false);
12332 
12333 	if (retprobe && session)
12334 		return libbpf_err_ptr(-EINVAL);
12335 
12336 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12337 
12338 	lopts.kprobe_multi.syms = syms;
12339 	lopts.kprobe_multi.addrs = addrs;
12340 	lopts.kprobe_multi.cookies = cookies;
12341 	lopts.kprobe_multi.cnt = cnt;
12342 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12343 
12344 	link = calloc(1, sizeof(*link));
12345 	if (!link) {
12346 		err = -ENOMEM;
12347 		goto error;
12348 	}
12349 	link->detach = &bpf_link__detach_fd;
12350 
12351 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12352 	if (link_fd < 0) {
12353 		err = -errno;
12354 		/*
12355 		 * Normalize error code: when exact name bypasses kallsyms
12356 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
12357 		 * Convert to ENOENT for API consistency with the pattern
12358 		 * matching path which returns ENOENT from userspace.
12359 		 */
12360 		if (err == -ESRCH)
12361 			err = -ENOENT;
12362 		pr_warn("prog '%s': failed to attach: %s\n",
12363 			prog->name, errstr(err));
12364 		goto error;
12365 	}
12366 	link->fd = link_fd;
12367 	free(res.addrs);
12368 	return link;
12369 
12370 error:
12371 	free(link);
12372 	free(res.addrs);
12373 	return libbpf_err_ptr(err);
12374 }
12375 
12376 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12377 {
12378 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12379 	long offset = 0;
12380 	const char *func_name;
12381 	char *func;
12382 	int n;
12383 
12384 	*link = NULL;
12385 
12386 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12387 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12388 		return 0;
12389 
12390 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12391 	if (opts.retprobe)
12392 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12393 	else
12394 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12395 
12396 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12397 	if (n < 1) {
12398 		pr_warn("kprobe name is invalid: %s\n", func_name);
12399 		return -EINVAL;
12400 	}
12401 
12402 	if (offset < 0) {
12403 		free(func);
12404 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
12405 		return -EINVAL;
12406 	}
12407 
12408 	if (opts.retprobe && offset != 0) {
12409 		free(func);
12410 		pr_warn("kretprobes do not support offset specification\n");
12411 		return -EINVAL;
12412 	}
12413 
12414 	opts.offset = offset;
12415 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12416 	free(func);
12417 	return libbpf_get_error(*link);
12418 }
12419 
12420 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12421 {
12422 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12423 	const char *syscall_name;
12424 
12425 	*link = NULL;
12426 
12427 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12428 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12429 		return 0;
12430 
12431 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12432 	if (opts.retprobe)
12433 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12434 	else
12435 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12436 
12437 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12438 	return *link ? 0 : -errno;
12439 }
12440 
12441 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12442 {
12443 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12444 	const char *spec;
12445 	char *pattern;
12446 	int n;
12447 
12448 	*link = NULL;
12449 
12450 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12451 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12452 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12453 		return 0;
12454 
12455 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12456 	if (opts.retprobe)
12457 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12458 	else
12459 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12460 
12461 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12462 	if (n < 1) {
12463 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12464 		return -EINVAL;
12465 	}
12466 
12467 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12468 	free(pattern);
12469 	return libbpf_get_error(*link);
12470 }
12471 
12472 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12473 				 struct bpf_link **link)
12474 {
12475 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12476 	const char *spec;
12477 	char *pattern;
12478 	int n;
12479 
12480 	*link = NULL;
12481 
12482 	/* no auto-attach for SEC("kprobe.session") */
12483 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12484 		return 0;
12485 
12486 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12487 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12488 	if (n < 1) {
12489 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12490 		return -EINVAL;
12491 	}
12492 
12493 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12494 	free(pattern);
12495 	return *link ? 0 : -errno;
12496 }
12497 
12498 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12499 {
12500 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12501 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12502 	int n, ret = -EINVAL;
12503 
12504 	*link = NULL;
12505 
12506 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12507 		   &probe_type, &binary_path, &func_name);
12508 	switch (n) {
12509 	case 1:
12510 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12511 		ret = 0;
12512 		break;
12513 	case 3:
12514 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12515 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12516 
12517 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12518 		ret = libbpf_get_error(*link);
12519 		break;
12520 	default:
12521 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12522 			prog->sec_name);
12523 		break;
12524 	}
12525 	free(probe_type);
12526 	free(binary_path);
12527 	free(func_name);
12528 	return ret;
12529 }
12530 
12531 #define MAX_BPF_FUNC_ARGS 12
12532 
12533 static bool btf_type_is_modifier(const struct btf_type *t)
12534 {
12535 	switch (BTF_INFO_KIND(t->info)) {
12536 	case BTF_KIND_TYPEDEF:
12537 	case BTF_KIND_VOLATILE:
12538 	case BTF_KIND_CONST:
12539 	case BTF_KIND_RESTRICT:
12540 	case BTF_KIND_TYPE_TAG:
12541 		return true;
12542 	default:
12543 		return false;
12544 	}
12545 }
12546 
12547 #define MAX_RESOLVE_DEPTH 32
12548 
12549 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
12550 			     const struct btf_type **ret_type)
12551 {
12552 	const struct btf_type *t;
12553 	int i;
12554 
12555 	*ret_type = btf__type_by_id(btf, 0);
12556 	if (!type_id)
12557 		return 0;
12558 	t = btf__type_by_id(btf, type_id);
12559 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
12560 		t = btf__type_by_id(btf, t->type);
12561 	if (!t || i == MAX_RESOLVE_DEPTH)
12562 		return -EINVAL;
12563 	*ret_type = t;
12564 	if (btf_is_ptr(t))
12565 		return btf__pointer_size(btf);
12566 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
12567 		return t->size;
12568 	return -EINVAL;
12569 }
12570 
12571 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
12572 {
12573 	const struct btf_param *args;
12574 	const struct btf_type *proto;
12575 	__u32 i, nargs;
12576 	int ret;
12577 
12578 	if (!btf_is_func(t))
12579 		return false;
12580 	proto = btf__type_by_id(btf, t->type);
12581 	if (!proto || !btf_is_func_proto(proto))
12582 		return false;
12583 
12584 	args = (const struct btf_param *)(proto + 1);
12585 	nargs = btf_vlen(proto);
12586 	if (nargs > MAX_BPF_FUNC_ARGS)
12587 		return false;
12588 
12589 	/* No support for struct return type. */
12590 	ret = btf_get_type_size(btf, proto->type, &t);
12591 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
12592 		return false;
12593 
12594 	for (i = 0; i < nargs; i++) {
12595 		/* No support for variable args. */
12596 		if (i == nargs - 1 && args[i].type == 0)
12597 			return false;
12598 		ret = btf_get_type_size(btf, args[i].type, &t);
12599 		/* No support of struct argument size greater than 16 bytes. */
12600 		if (ret < 0 || ret > 16)
12601 			return false;
12602 		/* No support for void argument. */
12603 		if (ret == 0)
12604 			return false;
12605 	}
12606 
12607 	return true;
12608 }
12609 
12610 static int
12611 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
12612 {
12613 	__u32 type_id, nr_types = btf__type_cnt(btf);
12614 	size_t cap = 0, cnt = 0;
12615 
12616 	if (!pattern)
12617 		return -EINVAL;
12618 
12619 	for (type_id = 1; type_id < nr_types; type_id++) {
12620 		const struct btf_type *t = btf__type_by_id(btf, type_id);
12621 		const char *name;
12622 		int err;
12623 
12624 		if (btf_kind(t) != BTF_KIND_FUNC)
12625 			continue;
12626 		name = btf__name_by_offset(btf, t->name_off);
12627 		if (!name)
12628 			continue;
12629 
12630 		if (!glob_match(name, pattern))
12631 			continue;
12632 		if (!btf_type_is_traceable_func(btf, t))
12633 			continue;
12634 
12635 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
12636 		if (err) {
12637 			free(*ids);
12638 			return -ENOMEM;
12639 		}
12640 		(*ids)[cnt++] = type_id;
12641 	}
12642 
12643 	return cnt;
12644 }
12645 
12646 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
12647 {
12648 	struct bpf_object *obj = prog->obj;
12649 	const struct module_btf *mod;
12650 	struct btf *btf = NULL;
12651 	const char *sep;
12652 	int err;
12653 
12654 	err = bpf_object__load_vmlinux_btf(obj, true);
12655 	if (err)
12656 		return err;
12657 
12658 	/* In case we have module specified, we will find its btf and use that. */
12659 	sep = strchr(pattern, ':');
12660 	if (sep) {
12661 		mod = find_attach_module(obj, pattern);
12662 		if (!mod) {
12663 			err = -EINVAL;
12664 			goto cleanup;
12665 		}
12666 		btf = mod->btf;
12667 		pattern = sep + 1;
12668 	} else {
12669 		/* Program is loaded for kernel module. */
12670 		if (prog->attach_btf_obj_fd) {
12671 			err = -EINVAL;
12672 			goto cleanup;
12673 		}
12674 		btf = obj->btf_vmlinux;
12675 	}
12676 
12677 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
12678 
12679 cleanup:
12680 	bpf_object_cleanup_btf(obj);
12681 	return err;
12682 }
12683 
12684 struct bpf_link *
12685 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
12686 				  const struct bpf_tracing_multi_opts *opts)
12687 {
12688 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12689 	int prog_fd, link_fd, err, cnt;
12690 	__u32 *free_ids = NULL;
12691 	struct bpf_link *link;
12692 	const __u64 *cookies;
12693 	const __u32 *ids;
12694 
12695 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
12696 		return libbpf_err_ptr(-EINVAL);
12697 
12698 	prog_fd = bpf_program__fd(prog);
12699 	if (prog_fd < 0) {
12700 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12701 			prog->name);
12702 		return libbpf_err_ptr(-EINVAL);
12703 	}
12704 
12705 	cnt = OPTS_GET(opts, cnt, 0);
12706 	ids = OPTS_GET(opts, ids, NULL);
12707 	cookies = OPTS_GET(opts, cookies, NULL);
12708 
12709 	if (!!ids != !!cnt)
12710 		return libbpf_err_ptr(-EINVAL);
12711 	if (pattern && (ids || cookies))
12712 		return libbpf_err_ptr(-EINVAL);
12713 	if (!pattern && !ids)
12714 		return libbpf_err_ptr(-EINVAL);
12715 
12716 	if (pattern) {
12717 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
12718 		if (cnt < 0)
12719 			return libbpf_err_ptr(cnt);
12720 		if (cnt == 0)
12721 			return libbpf_err_ptr(-EINVAL);
12722 		ids = (const __u32 *) free_ids;
12723 	}
12724 
12725 	lopts.tracing_multi.ids = ids;
12726 	lopts.tracing_multi.cookies = cookies;
12727 	lopts.tracing_multi.cnt = cnt;
12728 
12729 	link = calloc(1, sizeof(*link));
12730 	if (!link) {
12731 		err = -ENOMEM;
12732 		goto error;
12733 	}
12734 	link->detach = &bpf_link__detach_fd;
12735 
12736 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
12737 	if (link_fd < 0) {
12738 		err = -errno;
12739 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
12740 		goto error;
12741 	}
12742 	link->fd = link_fd;
12743 	free(free_ids);
12744 	return link;
12745 
12746 error:
12747 	free(link);
12748 	free(free_ids);
12749 	return libbpf_err_ptr(err);
12750 }
12751 
12752 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12753 {
12754 	static const char *const prefixes[] = {
12755 		"fentry.multi",
12756 		"fexit.multi",
12757 		"fsession.multi",
12758 		"fentry.multi.s",
12759 		"fexit.multi.s",
12760 		"fsession.multi.s",
12761 	};
12762 	const char *spec = NULL;
12763 	char *pattern;
12764 	size_t i;
12765 	int n;
12766 
12767 	*link = NULL;
12768 
12769 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12770 		size_t pfx_len;
12771 
12772 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12773 			continue;
12774 
12775 		pfx_len = strlen(prefixes[i]);
12776 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
12777 		if (prog->sec_name[pfx_len] == '\0')
12778 			return 0;
12779 
12780 		if (prog->sec_name[pfx_len] != '/')
12781 			continue;
12782 
12783 		spec = prog->sec_name + pfx_len + 1;
12784 		break;
12785 	}
12786 
12787 	if (!spec) {
12788 		pr_warn("prog '%s': invalid section name '%s'\n",
12789 			prog->name, prog->sec_name);
12790 		return -EINVAL;
12791 	}
12792 
12793 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
12794 	if (n < 1) {
12795 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
12796 		return -EINVAL;
12797 	}
12798 
12799 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
12800 	free(pattern);
12801 	return libbpf_get_error(*link);
12802 }
12803 
12804 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12805 					  const char *binary_path, size_t offset)
12806 {
12807 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12808 			      retprobe ? 'r' : 'p',
12809 			      retprobe ? "uretprobes" : "uprobes",
12810 			      probe_name, binary_path, offset);
12811 }
12812 
12813 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12814 {
12815 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12816 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12817 }
12818 
12819 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12820 {
12821 	char file[512];
12822 
12823 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12824 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12825 
12826 	return parse_uint_from_file(file, "%d\n");
12827 }
12828 
12829 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12830 					 const char *binary_path, size_t offset, int pid)
12831 {
12832 	const size_t attr_sz = sizeof(struct perf_event_attr);
12833 	struct perf_event_attr attr;
12834 	int type, pfd, err;
12835 
12836 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12837 	if (err < 0) {
12838 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12839 			binary_path, (size_t)offset, errstr(err));
12840 		return err;
12841 	}
12842 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12843 	if (type < 0) {
12844 		err = type;
12845 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12846 			binary_path, offset, errstr(err));
12847 		goto err_clean_legacy;
12848 	}
12849 
12850 	memset(&attr, 0, attr_sz);
12851 	attr.size = attr_sz;
12852 	attr.config = type;
12853 	attr.type = PERF_TYPE_TRACEPOINT;
12854 
12855 	pfd = syscall(__NR_perf_event_open, &attr,
12856 		      pid < 0 ? -1 : pid, /* pid */
12857 		      pid == -1 ? 0 : -1, /* cpu */
12858 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12859 	if (pfd < 0) {
12860 		err = -errno;
12861 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12862 		goto err_clean_legacy;
12863 	}
12864 	return pfd;
12865 
12866 err_clean_legacy:
12867 	/* Clear the newly added legacy uprobe_event */
12868 	remove_uprobe_event_legacy(probe_name, retprobe);
12869 	return err;
12870 }
12871 
12872 /* Find offset of function name in archive specified by path. Currently
12873  * supported are .zip files that do not compress their contents, as used on
12874  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12875  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12876  * library functions.
12877  *
12878  * An overview of the APK format specifically provided here:
12879  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12880  */
12881 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12882 					      const char *func_name)
12883 {
12884 	struct zip_archive *archive;
12885 	struct zip_entry entry;
12886 	long ret;
12887 	Elf *elf;
12888 
12889 	archive = zip_archive_open(archive_path);
12890 	if (IS_ERR(archive)) {
12891 		ret = PTR_ERR(archive);
12892 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12893 		return ret;
12894 	}
12895 
12896 	ret = zip_archive_find_entry(archive, file_name, &entry);
12897 	if (ret) {
12898 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12899 			archive_path, ret);
12900 		goto out;
12901 	}
12902 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12903 		 (unsigned long)entry.data_offset);
12904 
12905 	if (entry.compression) {
12906 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12907 			archive_path);
12908 		ret = -LIBBPF_ERRNO__FORMAT;
12909 		goto out;
12910 	}
12911 
12912 	elf = elf_memory((void *)entry.data, entry.data_length);
12913 	if (!elf) {
12914 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12915 			elf_errmsg(-1));
12916 		ret = -LIBBPF_ERRNO__LIBELF;
12917 		goto out;
12918 	}
12919 
12920 	ret = elf_find_func_offset(elf, file_name, func_name);
12921 	if (ret > 0) {
12922 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12923 			 func_name, file_name, archive_path, entry.data_offset, (unsigned long)ret,
12924 			 (unsigned long)(ret + entry.data_offset));
12925 		ret += entry.data_offset;
12926 	}
12927 	elf_end(elf);
12928 
12929 out:
12930 	zip_archive_close(archive);
12931 	return ret;
12932 }
12933 
12934 static const char *arch_specific_lib_paths(void)
12935 {
12936 	/*
12937 	 * Based on https://packages.debian.org/sid/libc6.
12938 	 *
12939 	 * Assume that the traced program is built for the same architecture
12940 	 * as libbpf, which should cover the vast majority of cases.
12941 	 */
12942 #if defined(__x86_64__)
12943 	return "/lib/x86_64-linux-gnu";
12944 #elif defined(__i386__)
12945 	return "/lib/i386-linux-gnu";
12946 #elif defined(__s390x__)
12947 	return "/lib/s390x-linux-gnu";
12948 #elif defined(__arm__) && defined(__SOFTFP__)
12949 	return "/lib/arm-linux-gnueabi";
12950 #elif defined(__arm__) && !defined(__SOFTFP__)
12951 	return "/lib/arm-linux-gnueabihf";
12952 #elif defined(__aarch64__)
12953 	return "/lib/aarch64-linux-gnu";
12954 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12955 	return "/lib/mips64el-linux-gnuabi64";
12956 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12957 	return "/lib/mipsel-linux-gnu";
12958 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12959 	return "/lib/powerpc64le-linux-gnu";
12960 #elif defined(__sparc__) && defined(__arch64__)
12961 	return "/lib/sparc64-linux-gnu";
12962 #elif defined(__riscv) && __riscv_xlen == 64
12963 	return "/lib/riscv64-linux-gnu";
12964 #else
12965 	return NULL;
12966 #endif
12967 }
12968 
12969 /* Get full path to program/shared library. */
12970 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12971 {
12972 	const char *search_paths[4] = {};
12973 	int i, perm;
12974 
12975 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12976 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12977 		search_paths[1] = "/usr/lib64:/usr/lib";
12978 		search_paths[2] = arch_specific_lib_paths();
12979 		search_paths[3] = "/lib64:/lib";
12980 		perm = R_OK;
12981 	} else {
12982 		search_paths[0] = getenv("PATH");
12983 		search_paths[1] = "/usr/bin:/usr/sbin";
12984 		perm = R_OK | X_OK;
12985 	}
12986 
12987 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12988 		const char *s;
12989 
12990 		if (!search_paths[i])
12991 			continue;
12992 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12993 			const char *next_path;
12994 			int seg_len;
12995 
12996 			if (s[0] == ':')
12997 				s++;
12998 			next_path = strchr(s, ':');
12999 			seg_len = next_path ? next_path - s : strlen(s);
13000 			if (!seg_len)
13001 				continue;
13002 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
13003 			/* ensure it has required permissions */
13004 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
13005 				continue;
13006 			pr_debug("resolved '%s' to '%s'\n", file, result);
13007 			return 0;
13008 		}
13009 	}
13010 	return -ENOENT;
13011 }
13012 
13013 struct bpf_link *
13014 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
13015 				 pid_t pid,
13016 				 const char *path,
13017 				 const char *func_pattern,
13018 				 const struct bpf_uprobe_multi_opts *opts)
13019 {
13020 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
13021 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13022 	unsigned long *resolved_offsets = NULL;
13023 	enum bpf_attach_type attach_type;
13024 	int err = 0, link_fd, prog_fd;
13025 	struct bpf_link *link = NULL;
13026 	char full_path[PATH_MAX];
13027 	bool retprobe, session;
13028 	const __u64 *cookies;
13029 	const char **syms;
13030 	size_t cnt;
13031 
13032 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
13033 		return libbpf_err_ptr(-EINVAL);
13034 
13035 	prog_fd = bpf_program__fd(prog);
13036 	if (prog_fd < 0) {
13037 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13038 			prog->name);
13039 		return libbpf_err_ptr(-EINVAL);
13040 	}
13041 
13042 	syms = OPTS_GET(opts, syms, NULL);
13043 	offsets = OPTS_GET(opts, offsets, NULL);
13044 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
13045 	cookies = OPTS_GET(opts, cookies, NULL);
13046 	cnt = OPTS_GET(opts, cnt, 0);
13047 	retprobe = OPTS_GET(opts, retprobe, false);
13048 	session  = OPTS_GET(opts, session, false);
13049 
13050 	/*
13051 	 * User can specify 2 mutually exclusive set of inputs:
13052 	 *
13053 	 * 1) use only path/func_pattern/pid arguments
13054 	 *
13055 	 * 2) use path/pid with allowed combinations of:
13056 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
13057 	 *
13058 	 *    - syms and offsets are mutually exclusive
13059 	 *    - ref_ctr_offsets and cookies are optional
13060 	 *
13061 	 * Any other usage results in error.
13062 	 */
13063 
13064 	if (!path)
13065 		return libbpf_err_ptr(-EINVAL);
13066 	if (!func_pattern && cnt == 0)
13067 		return libbpf_err_ptr(-EINVAL);
13068 
13069 	if (func_pattern) {
13070 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
13071 			return libbpf_err_ptr(-EINVAL);
13072 	} else {
13073 		if (!!syms == !!offsets)
13074 			return libbpf_err_ptr(-EINVAL);
13075 	}
13076 
13077 	if (retprobe && session)
13078 		return libbpf_err_ptr(-EINVAL);
13079 
13080 	if (func_pattern) {
13081 		if (!strchr(path, '/')) {
13082 			err = resolve_full_path(path, full_path, sizeof(full_path));
13083 			if (err) {
13084 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13085 					prog->name, path, errstr(err));
13086 				return libbpf_err_ptr(err);
13087 			}
13088 			path = full_path;
13089 		}
13090 
13091 		err = elf_resolve_pattern_offsets(path, func_pattern,
13092 						  &resolved_offsets, &cnt);
13093 		if (err < 0)
13094 			return libbpf_err_ptr(err);
13095 		offsets = resolved_offsets;
13096 	} else if (syms) {
13097 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
13098 		if (err < 0)
13099 			return libbpf_err_ptr(err);
13100 		offsets = resolved_offsets;
13101 	}
13102 
13103 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
13104 
13105 	lopts.uprobe_multi.path = path;
13106 	lopts.uprobe_multi.offsets = offsets;
13107 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
13108 	lopts.uprobe_multi.cookies = cookies;
13109 	lopts.uprobe_multi.cnt = cnt;
13110 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
13111 
13112 	if (pid == 0)
13113 		pid = getpid();
13114 	if (pid > 0)
13115 		lopts.uprobe_multi.pid = pid;
13116 
13117 	link = calloc(1, sizeof(*link));
13118 	if (!link) {
13119 		err = -ENOMEM;
13120 		goto error;
13121 	}
13122 	link->detach = &bpf_link__detach_fd;
13123 
13124 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13125 	if (link_fd < 0) {
13126 		err = -errno;
13127 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
13128 			prog->name, errstr(err));
13129 		goto error;
13130 	}
13131 	link->fd = link_fd;
13132 	free(resolved_offsets);
13133 	return link;
13134 
13135 error:
13136 	free(resolved_offsets);
13137 	free(link);
13138 	return libbpf_err_ptr(err);
13139 }
13140 
13141 LIBBPF_API struct bpf_link *
13142 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
13143 				const char *binary_path, size_t func_offset,
13144 				const struct bpf_uprobe_opts *opts)
13145 {
13146 	const char *archive_path = NULL, *archive_sep = NULL;
13147 	char *legacy_probe = NULL;
13148 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13149 	enum probe_attach_mode attach_mode;
13150 	char full_path[PATH_MAX];
13151 	struct bpf_link *link;
13152 	size_t ref_ctr_off;
13153 	int pfd, err;
13154 	bool retprobe, legacy;
13155 	const char *func_name;
13156 
13157 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13158 		return libbpf_err_ptr(-EINVAL);
13159 
13160 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
13161 	retprobe = OPTS_GET(opts, retprobe, false);
13162 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
13163 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13164 
13165 	if (!binary_path)
13166 		return libbpf_err_ptr(-EINVAL);
13167 
13168 	/* Check if "binary_path" refers to an archive. */
13169 	archive_sep = strstr(binary_path, "!/");
13170 	if (archive_sep) {
13171 		full_path[0] = '\0';
13172 		libbpf_strlcpy(full_path, binary_path,
13173 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
13174 		archive_path = full_path;
13175 		binary_path = archive_sep + 2;
13176 	} else if (!strchr(binary_path, '/')) {
13177 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
13178 		if (err) {
13179 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13180 				prog->name, binary_path, errstr(err));
13181 			return libbpf_err_ptr(err);
13182 		}
13183 		binary_path = full_path;
13184 	}
13185 	func_name = OPTS_GET(opts, func_name, NULL);
13186 	if (func_name) {
13187 		long sym_off;
13188 
13189 		if (archive_path) {
13190 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
13191 								    func_name);
13192 			binary_path = archive_path;
13193 		} else {
13194 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
13195 		}
13196 		if (sym_off < 0)
13197 			return libbpf_err_ptr(sym_off);
13198 		func_offset += sym_off;
13199 	}
13200 
13201 	legacy = determine_uprobe_perf_type() < 0;
13202 	switch (attach_mode) {
13203 	case PROBE_ATTACH_MODE_LEGACY:
13204 		legacy = true;
13205 		pe_opts.force_ioctl_attach = true;
13206 		break;
13207 	case PROBE_ATTACH_MODE_PERF:
13208 		if (legacy)
13209 			return libbpf_err_ptr(-ENOTSUP);
13210 		pe_opts.force_ioctl_attach = true;
13211 		break;
13212 	case PROBE_ATTACH_MODE_LINK:
13213 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
13214 			return libbpf_err_ptr(-ENOTSUP);
13215 		break;
13216 	case PROBE_ATTACH_MODE_DEFAULT:
13217 		break;
13218 	default:
13219 		return libbpf_err_ptr(-EINVAL);
13220 	}
13221 
13222 	if (!legacy) {
13223 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
13224 					    func_offset, pid, ref_ctr_off);
13225 	} else {
13226 		char probe_name[MAX_EVENT_NAME_LEN];
13227 
13228 		if (ref_ctr_off)
13229 			return libbpf_err_ptr(-EINVAL);
13230 
13231 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
13232 					    strrchr(binary_path, '/') ? : binary_path,
13233 					    func_offset);
13234 
13235 		legacy_probe = strdup(probe_name);
13236 		if (!legacy_probe)
13237 			return libbpf_err_ptr(-ENOMEM);
13238 
13239 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
13240 						    binary_path, func_offset, pid);
13241 	}
13242 	if (pfd < 0) {
13243 		err = pfd;
13244 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
13245 			prog->name, retprobe ? "uretprobe" : "uprobe",
13246 			binary_path, func_offset,
13247 			errstr(err));
13248 		goto err_out;
13249 	}
13250 
13251 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13252 	err = libbpf_get_error(link);
13253 	if (err) {
13254 		close(pfd);
13255 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
13256 			prog->name, retprobe ? "uretprobe" : "uprobe",
13257 			binary_path, func_offset,
13258 			errstr(err));
13259 		goto err_clean_legacy;
13260 	}
13261 	if (legacy) {
13262 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
13263 
13264 		perf_link->legacy_probe_name = legacy_probe;
13265 		perf_link->legacy_is_kprobe = false;
13266 		perf_link->legacy_is_retprobe = retprobe;
13267 	}
13268 	return link;
13269 
13270 err_clean_legacy:
13271 	if (legacy)
13272 		remove_uprobe_event_legacy(legacy_probe, retprobe);
13273 err_out:
13274 	free(legacy_probe);
13275 	return libbpf_err_ptr(err);
13276 }
13277 
13278 /* Format of u[ret]probe section definition supporting auto-attach:
13279  * u[ret]probe/binary:function[+offset]
13280  *
13281  * binary can be an absolute/relative path or a filename; the latter is resolved to a
13282  * full binary path via bpf_program__attach_uprobe_opts.
13283  *
13284  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
13285  * specified (and auto-attach is not possible) or the above format is specified for
13286  * auto-attach.
13287  */
13288 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13289 {
13290 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
13291 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
13292 	int n, c, ret = -EINVAL;
13293 	long offset = 0;
13294 
13295 	*link = NULL;
13296 
13297 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13298 		   &probe_type, &binary_path, &func_name);
13299 	switch (n) {
13300 	case 1:
13301 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13302 		ret = 0;
13303 		break;
13304 	case 2:
13305 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
13306 			prog->name, prog->sec_name);
13307 		break;
13308 	case 3:
13309 		/* check if user specifies `+offset`, if yes, this should be
13310 		 * the last part of the string, make sure sscanf read to EOL
13311 		 */
13312 		func_off = strrchr(func_name, '+');
13313 		if (func_off) {
13314 			n = sscanf(func_off, "+%li%n", &offset, &c);
13315 			if (n == 1 && *(func_off + c) == '\0')
13316 				func_off[0] = '\0';
13317 			else
13318 				offset = 0;
13319 		}
13320 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
13321 				strcmp(probe_type, "uretprobe.s") == 0;
13322 		if (opts.retprobe && offset != 0) {
13323 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
13324 				prog->name);
13325 			break;
13326 		}
13327 		opts.func_name = func_name;
13328 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
13329 		ret = libbpf_get_error(*link);
13330 		break;
13331 	default:
13332 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13333 			prog->sec_name);
13334 		break;
13335 	}
13336 	free(probe_type);
13337 	free(binary_path);
13338 	free(func_name);
13339 
13340 	return ret;
13341 }
13342 
13343 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
13344 					    bool retprobe, pid_t pid,
13345 					    const char *binary_path,
13346 					    size_t func_offset)
13347 {
13348 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
13349 
13350 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
13351 }
13352 
13353 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
13354 					  pid_t pid, const char *binary_path,
13355 					  const char *usdt_provider, const char *usdt_name,
13356 					  const struct bpf_usdt_opts *opts)
13357 {
13358 	char resolved_path[512];
13359 	struct bpf_object *obj = prog->obj;
13360 	struct bpf_link *link;
13361 	__u64 usdt_cookie;
13362 	int err;
13363 
13364 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13365 		return libbpf_err_ptr(-EINVAL);
13366 
13367 	if (bpf_program__fd(prog) < 0) {
13368 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13369 			prog->name);
13370 		return libbpf_err_ptr(-EINVAL);
13371 	}
13372 
13373 	if (!binary_path)
13374 		return libbpf_err_ptr(-EINVAL);
13375 
13376 	if (!strchr(binary_path, '/')) {
13377 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
13378 		if (err) {
13379 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13380 				prog->name, binary_path, errstr(err));
13381 			return libbpf_err_ptr(err);
13382 		}
13383 		binary_path = resolved_path;
13384 	}
13385 
13386 	/* USDT manager is instantiated lazily on first USDT attach. It will
13387 	 * be destroyed together with BPF object in bpf_object__close().
13388 	 */
13389 	if (IS_ERR(obj->usdt_man))
13390 		return libbpf_ptr(obj->usdt_man);
13391 	if (!obj->usdt_man) {
13392 		obj->usdt_man = usdt_manager_new(obj);
13393 		if (IS_ERR(obj->usdt_man))
13394 			return libbpf_ptr(obj->usdt_man);
13395 	}
13396 
13397 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
13398 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
13399 					usdt_provider, usdt_name, usdt_cookie);
13400 	err = libbpf_get_error(link);
13401 	if (err)
13402 		return libbpf_err_ptr(err);
13403 	return link;
13404 }
13405 
13406 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13407 {
13408 	char *path = NULL, *provider = NULL, *name = NULL;
13409 	const char *sec_name;
13410 	int n, err;
13411 
13412 	sec_name = bpf_program__section_name(prog);
13413 	if (strcmp(sec_name, "usdt") == 0) {
13414 		/* no auto-attach for just SEC("usdt") */
13415 		*link = NULL;
13416 		return 0;
13417 	}
13418 
13419 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
13420 	if (n != 3) {
13421 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
13422 			sec_name);
13423 		err = -EINVAL;
13424 	} else {
13425 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
13426 						 provider, name, NULL);
13427 		err = libbpf_get_error(*link);
13428 	}
13429 	free(path);
13430 	free(provider);
13431 	free(name);
13432 	return err;
13433 }
13434 
13435 static int determine_tracepoint_id(const char *tp_category,
13436 				   const char *tp_name)
13437 {
13438 	char file[PATH_MAX];
13439 	int ret;
13440 
13441 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13442 		       tracefs_path(), tp_category, tp_name);
13443 	if (ret < 0)
13444 		return -errno;
13445 	if (ret >= sizeof(file)) {
13446 		pr_debug("tracepoint %s/%s path is too long\n",
13447 			 tp_category, tp_name);
13448 		return -E2BIG;
13449 	}
13450 	return parse_uint_from_file(file, "%d\n");
13451 }
13452 
13453 static int perf_event_open_tracepoint(const char *tp_category,
13454 				      const char *tp_name)
13455 {
13456 	const size_t attr_sz = sizeof(struct perf_event_attr);
13457 	struct perf_event_attr attr;
13458 	int tp_id, pfd, err;
13459 
13460 	tp_id = determine_tracepoint_id(tp_category, tp_name);
13461 	if (tp_id < 0) {
13462 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
13463 			tp_category, tp_name,
13464 			errstr(tp_id));
13465 		return tp_id;
13466 	}
13467 
13468 	memset(&attr, 0, attr_sz);
13469 	attr.type = PERF_TYPE_TRACEPOINT;
13470 	attr.size = attr_sz;
13471 	attr.config = tp_id;
13472 
13473 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
13474 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
13475 	if (pfd < 0) {
13476 		err = -errno;
13477 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
13478 			tp_category, tp_name,
13479 			errstr(err));
13480 		return err;
13481 	}
13482 	return pfd;
13483 }
13484 
13485 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
13486 						     const char *tp_category,
13487 						     const char *tp_name,
13488 						     const struct bpf_tracepoint_opts *opts)
13489 {
13490 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13491 	struct bpf_link *link;
13492 	int pfd, err;
13493 
13494 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
13495 		return libbpf_err_ptr(-EINVAL);
13496 
13497 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13498 
13499 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
13500 	if (pfd < 0) {
13501 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
13502 			prog->name, tp_category, tp_name,
13503 			errstr(pfd));
13504 		return libbpf_err_ptr(pfd);
13505 	}
13506 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13507 	err = libbpf_get_error(link);
13508 	if (err) {
13509 		close(pfd);
13510 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
13511 			prog->name, tp_category, tp_name,
13512 			errstr(err));
13513 		return libbpf_err_ptr(err);
13514 	}
13515 	return link;
13516 }
13517 
13518 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
13519 						const char *tp_category,
13520 						const char *tp_name)
13521 {
13522 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
13523 }
13524 
13525 /*
13526  * Match section name against a prefix array. Returns pointer past
13527  * "prefix/" on match, empty string for bare sections (exact prefix
13528  * match), or NULL if no prefix matches.
13529  */
13530 static const char *sec_name_match_prefix(const char *sec_name,
13531 					 const char *const *prefixes,
13532 					 size_t n)
13533 {
13534 	size_t i;
13535 
13536 	for (i = 0; i < n; i++) {
13537 		size_t pfx_len;
13538 
13539 		if (!str_has_pfx(sec_name, prefixes[i]))
13540 			continue;
13541 
13542 		pfx_len = strlen(prefixes[i]);
13543 		if (sec_name[pfx_len] == '\0')
13544 			return sec_name + pfx_len;
13545 
13546 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
13547 			continue;
13548 
13549 		return sec_name + pfx_len + 1;
13550 	}
13551 	return NULL;
13552 }
13553 
13554 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13555 {
13556 	static const char *const prefixes[] = {
13557 		"tp.s",
13558 		"tp",
13559 		"tracepoint.s",
13560 		"tracepoint",
13561 	};
13562 	char *sec_name, *tp_cat, *tp_name;
13563 	const char *match;
13564 
13565 	*link = NULL;
13566 
13567 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13568 	if (!match) {
13569 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13570 		return -EINVAL;
13571 	}
13572 	if (!match[0]) /* bare section name no autoattach */
13573 		return 0;
13574 
13575 	sec_name = strdup(prog->sec_name);
13576 	if (!sec_name)
13577 		return -ENOMEM;
13578 
13579 	tp_cat = sec_name + (match - prog->sec_name);
13580 	tp_name = strchr(tp_cat, '/');
13581 	if (!tp_name) {
13582 		free(sec_name);
13583 		return -EINVAL;
13584 	}
13585 	*tp_name = '\0';
13586 	tp_name++;
13587 
13588 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
13589 	free(sec_name);
13590 	return libbpf_get_error(*link);
13591 }
13592 
13593 struct bpf_link *
13594 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
13595 					const char *tp_name,
13596 					struct bpf_raw_tracepoint_opts *opts)
13597 {
13598 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
13599 	struct bpf_link *link;
13600 	int prog_fd, pfd;
13601 
13602 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
13603 		return libbpf_err_ptr(-EINVAL);
13604 
13605 	prog_fd = bpf_program__fd(prog);
13606 	if (prog_fd < 0) {
13607 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13608 		return libbpf_err_ptr(-EINVAL);
13609 	}
13610 
13611 	link = calloc(1, sizeof(*link));
13612 	if (!link)
13613 		return libbpf_err_ptr(-ENOMEM);
13614 	link->detach = &bpf_link__detach_fd;
13615 
13616 	raw_opts.tp_name = tp_name;
13617 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13618 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13619 	if (pfd < 0) {
13620 		pfd = -errno;
13621 		free(link);
13622 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13623 			prog->name, tp_name, errstr(pfd));
13624 		return libbpf_err_ptr(pfd);
13625 	}
13626 	link->fd = pfd;
13627 	return link;
13628 }
13629 
13630 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13631 						    const char *tp_name)
13632 {
13633 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13634 }
13635 
13636 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13637 {
13638 	static const char *const prefixes[] = {
13639 		"raw_tp",
13640 		"raw_tracepoint",
13641 		"raw_tp.w",
13642 		"raw_tracepoint.w",
13643 		"raw_tp.s",
13644 		"raw_tracepoint.s",
13645 	};
13646 	const char *match;
13647 
13648 	*link = NULL;
13649 
13650 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13651 	if (!match) {
13652 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13653 		return -EINVAL;
13654 	}
13655 	if (!match[0])
13656 		return 0;
13657 
13658 	*link = bpf_program__attach_raw_tracepoint(prog, match);
13659 	return libbpf_get_error(*link);
13660 }
13661 
13662 /* Common logic for all BPF program types that attach to a btf_id */
13663 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13664 						   const struct bpf_trace_opts *opts)
13665 {
13666 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13667 	struct bpf_link *link;
13668 	int prog_fd, pfd;
13669 
13670 	if (!OPTS_VALID(opts, bpf_trace_opts))
13671 		return libbpf_err_ptr(-EINVAL);
13672 
13673 	prog_fd = bpf_program__fd(prog);
13674 	if (prog_fd < 0) {
13675 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13676 		return libbpf_err_ptr(-EINVAL);
13677 	}
13678 
13679 	link = calloc(1, sizeof(*link));
13680 	if (!link)
13681 		return libbpf_err_ptr(-ENOMEM);
13682 	link->detach = &bpf_link__detach_fd;
13683 
13684 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13685 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13686 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13687 	if (pfd < 0) {
13688 		pfd = -errno;
13689 		free(link);
13690 		pr_warn("prog '%s': failed to attach: %s\n",
13691 			prog->name, errstr(pfd));
13692 		return libbpf_err_ptr(pfd);
13693 	}
13694 	link->fd = pfd;
13695 	return link;
13696 }
13697 
13698 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13699 {
13700 	return bpf_program__attach_btf_id(prog, NULL);
13701 }
13702 
13703 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13704 						const struct bpf_trace_opts *opts)
13705 {
13706 	return bpf_program__attach_btf_id(prog, opts);
13707 }
13708 
13709 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13710 {
13711 	return bpf_program__attach_btf_id(prog, NULL);
13712 }
13713 
13714 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13715 {
13716 	*link = bpf_program__attach_trace(prog);
13717 	return libbpf_get_error(*link);
13718 }
13719 
13720 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13721 {
13722 	*link = bpf_program__attach_lsm(prog);
13723 	return libbpf_get_error(*link);
13724 }
13725 
13726 static struct bpf_link *
13727 bpf_program_attach_fd(const struct bpf_program *prog,
13728 		      int target_fd, const char *target_name,
13729 		      const struct bpf_link_create_opts *opts)
13730 {
13731 	enum bpf_attach_type attach_type;
13732 	struct bpf_link *link;
13733 	int prog_fd, link_fd;
13734 
13735 	prog_fd = bpf_program__fd(prog);
13736 	if (prog_fd < 0) {
13737 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13738 		return libbpf_err_ptr(-EINVAL);
13739 	}
13740 
13741 	link = calloc(1, sizeof(*link));
13742 	if (!link)
13743 		return libbpf_err_ptr(-ENOMEM);
13744 	link->detach = &bpf_link__detach_fd;
13745 
13746 	attach_type = bpf_program__expected_attach_type(prog);
13747 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13748 	if (link_fd < 0) {
13749 		link_fd = -errno;
13750 		free(link);
13751 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13752 			prog->name, target_name,
13753 			errstr(link_fd));
13754 		return libbpf_err_ptr(link_fd);
13755 	}
13756 	link->fd = link_fd;
13757 	return link;
13758 }
13759 
13760 struct bpf_link *
13761 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13762 {
13763 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13764 }
13765 
13766 struct bpf_link *
13767 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13768 {
13769 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13770 }
13771 
13772 struct bpf_link *
13773 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13774 {
13775 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13776 }
13777 
13778 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13779 {
13780 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13781 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13782 }
13783 
13784 struct bpf_link *
13785 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13786 				const struct bpf_cgroup_opts *opts)
13787 {
13788 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13789 	__u32 relative_id;
13790 	int relative_fd;
13791 
13792 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13793 		return libbpf_err_ptr(-EINVAL);
13794 
13795 	relative_id = OPTS_GET(opts, relative_id, 0);
13796 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13797 
13798 	if (relative_fd && relative_id) {
13799 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13800 			prog->name);
13801 		return libbpf_err_ptr(-EINVAL);
13802 	}
13803 
13804 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13805 	link_create_opts.cgroup.relative_fd = relative_fd;
13806 	link_create_opts.cgroup.relative_id = relative_id;
13807 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13808 
13809 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13810 }
13811 
13812 struct bpf_link *
13813 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13814 			const struct bpf_tcx_opts *opts)
13815 {
13816 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13817 	__u32 relative_id;
13818 	int relative_fd;
13819 
13820 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13821 		return libbpf_err_ptr(-EINVAL);
13822 
13823 	relative_id = OPTS_GET(opts, relative_id, 0);
13824 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13825 
13826 	/* validate we don't have unexpected combinations of non-zero fields */
13827 	if (!ifindex) {
13828 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13829 			prog->name);
13830 		return libbpf_err_ptr(-EINVAL);
13831 	}
13832 	if (relative_fd && relative_id) {
13833 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13834 			prog->name);
13835 		return libbpf_err_ptr(-EINVAL);
13836 	}
13837 
13838 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13839 	link_create_opts.tcx.relative_fd = relative_fd;
13840 	link_create_opts.tcx.relative_id = relative_id;
13841 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13842 
13843 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13844 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13845 }
13846 
13847 struct bpf_link *
13848 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13849 			   const struct bpf_netkit_opts *opts)
13850 {
13851 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13852 	__u32 relative_id;
13853 	int relative_fd;
13854 
13855 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13856 		return libbpf_err_ptr(-EINVAL);
13857 
13858 	relative_id = OPTS_GET(opts, relative_id, 0);
13859 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13860 
13861 	/* validate we don't have unexpected combinations of non-zero fields */
13862 	if (!ifindex) {
13863 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13864 			prog->name);
13865 		return libbpf_err_ptr(-EINVAL);
13866 	}
13867 	if (relative_fd && relative_id) {
13868 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13869 			prog->name);
13870 		return libbpf_err_ptr(-EINVAL);
13871 	}
13872 
13873 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13874 	link_create_opts.netkit.relative_fd = relative_fd;
13875 	link_create_opts.netkit.relative_id = relative_id;
13876 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13877 
13878 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13879 }
13880 
13881 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13882 					      int target_fd,
13883 					      const char *attach_func_name)
13884 {
13885 	int btf_id;
13886 
13887 	if (!!target_fd != !!attach_func_name) {
13888 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13889 			prog->name);
13890 		return libbpf_err_ptr(-EINVAL);
13891 	}
13892 
13893 	if (prog->type != BPF_PROG_TYPE_EXT) {
13894 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13895 			prog->name);
13896 		return libbpf_err_ptr(-EINVAL);
13897 	}
13898 
13899 	if (target_fd) {
13900 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13901 
13902 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13903 		if (btf_id < 0)
13904 			return libbpf_err_ptr(btf_id);
13905 
13906 		target_opts.target_btf_id = btf_id;
13907 
13908 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13909 					     &target_opts);
13910 	} else {
13911 		/* no target, so use raw_tracepoint_open for compatibility
13912 		 * with old kernels
13913 		 */
13914 		return bpf_program__attach_trace(prog);
13915 	}
13916 }
13917 
13918 struct bpf_link *
13919 bpf_program__attach_iter(const struct bpf_program *prog,
13920 			 const struct bpf_iter_attach_opts *opts)
13921 {
13922 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13923 	struct bpf_link *link;
13924 	int prog_fd, link_fd;
13925 	__u32 target_fd = 0;
13926 
13927 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13928 		return libbpf_err_ptr(-EINVAL);
13929 
13930 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13931 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13932 
13933 	prog_fd = bpf_program__fd(prog);
13934 	if (prog_fd < 0) {
13935 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13936 		return libbpf_err_ptr(-EINVAL);
13937 	}
13938 
13939 	link = calloc(1, sizeof(*link));
13940 	if (!link)
13941 		return libbpf_err_ptr(-ENOMEM);
13942 	link->detach = &bpf_link__detach_fd;
13943 
13944 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13945 				  &link_create_opts);
13946 	if (link_fd < 0) {
13947 		link_fd = -errno;
13948 		free(link);
13949 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13950 			prog->name, errstr(link_fd));
13951 		return libbpf_err_ptr(link_fd);
13952 	}
13953 	link->fd = link_fd;
13954 	return link;
13955 }
13956 
13957 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13958 {
13959 	*link = bpf_program__attach_iter(prog, NULL);
13960 	return libbpf_get_error(*link);
13961 }
13962 
13963 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13964 					       const struct bpf_netfilter_opts *opts)
13965 {
13966 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13967 	struct bpf_link *link;
13968 	int prog_fd, link_fd;
13969 
13970 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13971 		return libbpf_err_ptr(-EINVAL);
13972 
13973 	prog_fd = bpf_program__fd(prog);
13974 	if (prog_fd < 0) {
13975 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13976 		return libbpf_err_ptr(-EINVAL);
13977 	}
13978 
13979 	link = calloc(1, sizeof(*link));
13980 	if (!link)
13981 		return libbpf_err_ptr(-ENOMEM);
13982 
13983 	link->detach = &bpf_link__detach_fd;
13984 
13985 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13986 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13987 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13988 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13989 
13990 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13991 	if (link_fd < 0) {
13992 		link_fd = -errno;
13993 		free(link);
13994 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13995 			prog->name, errstr(link_fd));
13996 		return libbpf_err_ptr(link_fd);
13997 	}
13998 	link->fd = link_fd;
13999 
14000 	return link;
14001 }
14002 
14003 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
14004 {
14005 	struct bpf_link *link = NULL;
14006 	int err;
14007 
14008 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14009 		return libbpf_err_ptr(-EOPNOTSUPP);
14010 
14011 	if (bpf_program__fd(prog) < 0) {
14012 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14013 			prog->name);
14014 		return libbpf_err_ptr(-EINVAL);
14015 	}
14016 
14017 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
14018 	if (err)
14019 		return libbpf_err_ptr(err);
14020 
14021 	/* When calling bpf_program__attach() explicitly, auto-attach support
14022 	 * is expected to work, so NULL returned link is considered an error.
14023 	 * This is different for skeleton's attach, see comment in
14024 	 * bpf_object__attach_skeleton().
14025 	 */
14026 	if (!link)
14027 		return libbpf_err_ptr(-EOPNOTSUPP);
14028 
14029 	return link;
14030 }
14031 
14032 struct bpf_link_struct_ops {
14033 	struct bpf_link link;
14034 	int map_fd;
14035 };
14036 
14037 static int bpf_link__detach_struct_ops(struct bpf_link *link)
14038 {
14039 	struct bpf_link_struct_ops *st_link;
14040 	__u32 zero = 0;
14041 
14042 	st_link = container_of(link, struct bpf_link_struct_ops, link);
14043 
14044 	if (st_link->map_fd < 0)
14045 		/* w/o a real link */
14046 		return bpf_map_delete_elem(link->fd, &zero);
14047 
14048 	return close(link->fd);
14049 }
14050 
14051 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
14052 {
14053 	struct bpf_link_struct_ops *link;
14054 	__u32 zero = 0;
14055 	int err, fd;
14056 
14057 	if (!bpf_map__is_struct_ops(map)) {
14058 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14059 		return libbpf_err_ptr(-EINVAL);
14060 	}
14061 
14062 	if (map->fd < 0) {
14063 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14064 		return libbpf_err_ptr(-EINVAL);
14065 	}
14066 
14067 	link = calloc(1, sizeof(*link));
14068 	if (!link)
14069 		return libbpf_err_ptr(-EINVAL);
14070 
14071 	/* kern_vdata should be prepared during the loading phase. */
14072 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14073 	/* It can be EBUSY if the map has been used to create or
14074 	 * update a link before.  We don't allow updating the value of
14075 	 * a struct_ops once it is set.  That ensures that the value
14076 	 * never changed.  So, it is safe to skip EBUSY.
14077 	 */
14078 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
14079 		free(link);
14080 		return libbpf_err_ptr(err);
14081 	}
14082 
14083 	link->link.detach = bpf_link__detach_struct_ops;
14084 
14085 	if (!(map->def.map_flags & BPF_F_LINK)) {
14086 		/* w/o a real link */
14087 		link->link.fd = map->fd;
14088 		link->map_fd = -1;
14089 		return &link->link;
14090 	}
14091 
14092 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
14093 	if (fd < 0) {
14094 		free(link);
14095 		return libbpf_err_ptr(fd);
14096 	}
14097 
14098 	link->link.fd = fd;
14099 	link->map_fd = map->fd;
14100 
14101 	return &link->link;
14102 }
14103 
14104 /*
14105  * Swap the back struct_ops of a link with a new struct_ops map.
14106  */
14107 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
14108 {
14109 	struct bpf_link_struct_ops *st_ops_link;
14110 	__u32 zero = 0;
14111 	int err;
14112 
14113 	if (!bpf_map__is_struct_ops(map))
14114 		return libbpf_err(-EINVAL);
14115 
14116 	if (map->fd < 0) {
14117 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
14118 		return libbpf_err(-EINVAL);
14119 	}
14120 
14121 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
14122 	/* Ensure the type of a link is correct */
14123 	if (st_ops_link->map_fd < 0)
14124 		return libbpf_err(-EINVAL);
14125 
14126 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14127 	/* It can be EBUSY if the map has been used to create or
14128 	 * update a link before.  We don't allow updating the value of
14129 	 * a struct_ops once it is set.  That ensures that the value
14130 	 * never changed.  So, it is safe to skip EBUSY.
14131 	 */
14132 	if (err && err != -EBUSY)
14133 		return err;
14134 
14135 	err = bpf_link_update(link->fd, map->fd, NULL);
14136 	if (err < 0)
14137 		return err;
14138 
14139 	st_ops_link->map_fd = map->fd;
14140 
14141 	return 0;
14142 }
14143 
14144 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
14145 							  void *private_data);
14146 
14147 static enum bpf_perf_event_ret
14148 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
14149 		       void **copy_mem, size_t *copy_size,
14150 		       bpf_perf_event_print_t fn, void *private_data)
14151 {
14152 	struct perf_event_mmap_page *header = mmap_mem;
14153 	__u64 data_head = ring_buffer_read_head(header);
14154 	__u64 data_tail = header->data_tail;
14155 	void *base = ((__u8 *)header) + page_size;
14156 	int ret = LIBBPF_PERF_EVENT_CONT;
14157 	struct perf_event_header *ehdr;
14158 	size_t ehdr_size;
14159 
14160 	while (data_head != data_tail) {
14161 		ehdr = base + (data_tail & (mmap_size - 1));
14162 		ehdr_size = ehdr->size;
14163 
14164 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
14165 			void *copy_start = ehdr;
14166 			size_t len_first = base + mmap_size - copy_start;
14167 			size_t len_secnd = ehdr_size - len_first;
14168 
14169 			if (*copy_size < ehdr_size) {
14170 				free(*copy_mem);
14171 				*copy_mem = malloc(ehdr_size);
14172 				if (!*copy_mem) {
14173 					*copy_size = 0;
14174 					ret = LIBBPF_PERF_EVENT_ERROR;
14175 					break;
14176 				}
14177 				*copy_size = ehdr_size;
14178 			}
14179 
14180 			memcpy(*copy_mem, copy_start, len_first);
14181 			memcpy(*copy_mem + len_first, base, len_secnd);
14182 			ehdr = *copy_mem;
14183 		}
14184 
14185 		ret = fn(ehdr, private_data);
14186 		data_tail += ehdr_size;
14187 		if (ret != LIBBPF_PERF_EVENT_CONT)
14188 			break;
14189 	}
14190 
14191 	ring_buffer_write_tail(header, data_tail);
14192 	return libbpf_err(ret);
14193 }
14194 
14195 struct perf_buffer;
14196 
14197 struct perf_buffer_params {
14198 	struct perf_event_attr *attr;
14199 	/* if event_cb is specified, it takes precendence */
14200 	perf_buffer_event_fn event_cb;
14201 	/* sample_cb and lost_cb are higher-level common-case callbacks */
14202 	perf_buffer_sample_fn sample_cb;
14203 	perf_buffer_lost_fn lost_cb;
14204 	void *ctx;
14205 	int cpu_cnt;
14206 	int *cpus;
14207 	int *map_keys;
14208 };
14209 
14210 struct perf_cpu_buf {
14211 	struct perf_buffer *pb;
14212 	void *base; /* mmap()'ed memory */
14213 	void *buf; /* for reconstructing segmented data */
14214 	size_t buf_size;
14215 	int fd;
14216 	int cpu;
14217 	int map_key;
14218 };
14219 
14220 struct perf_buffer {
14221 	perf_buffer_event_fn event_cb;
14222 	perf_buffer_sample_fn sample_cb;
14223 	perf_buffer_lost_fn lost_cb;
14224 	void *ctx; /* passed into callbacks */
14225 
14226 	size_t page_size;
14227 	size_t mmap_size;
14228 	struct perf_cpu_buf **cpu_bufs;
14229 	struct epoll_event *events;
14230 	int cpu_cnt; /* number of allocated CPU buffers */
14231 	int epoll_fd; /* perf event FD */
14232 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
14233 };
14234 
14235 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
14236 				      struct perf_cpu_buf *cpu_buf)
14237 {
14238 	if (!cpu_buf)
14239 		return;
14240 	if (cpu_buf->base &&
14241 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
14242 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
14243 	if (cpu_buf->fd >= 0) {
14244 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
14245 		close(cpu_buf->fd);
14246 	}
14247 	free(cpu_buf->buf);
14248 	free(cpu_buf);
14249 }
14250 
14251 void perf_buffer__free(struct perf_buffer *pb)
14252 {
14253 	int i;
14254 
14255 	if (IS_ERR_OR_NULL(pb))
14256 		return;
14257 	if (pb->cpu_bufs) {
14258 		for (i = 0; i < pb->cpu_cnt; i++) {
14259 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14260 
14261 			if (!cpu_buf)
14262 				continue;
14263 
14264 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
14265 			perf_buffer__free_cpu_buf(pb, cpu_buf);
14266 		}
14267 		free(pb->cpu_bufs);
14268 	}
14269 	if (pb->epoll_fd >= 0)
14270 		close(pb->epoll_fd);
14271 	free(pb->events);
14272 	free(pb);
14273 }
14274 
14275 static struct perf_cpu_buf *
14276 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
14277 			  int cpu, int map_key)
14278 {
14279 	struct perf_cpu_buf *cpu_buf;
14280 	int err;
14281 
14282 	cpu_buf = calloc(1, sizeof(*cpu_buf));
14283 	if (!cpu_buf)
14284 		return ERR_PTR(-ENOMEM);
14285 
14286 	cpu_buf->pb = pb;
14287 	cpu_buf->cpu = cpu;
14288 	cpu_buf->map_key = map_key;
14289 
14290 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
14291 			      -1, PERF_FLAG_FD_CLOEXEC);
14292 	if (cpu_buf->fd < 0) {
14293 		err = -errno;
14294 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
14295 			cpu, errstr(err));
14296 		goto error;
14297 	}
14298 
14299 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
14300 			     PROT_READ | PROT_WRITE, MAP_SHARED,
14301 			     cpu_buf->fd, 0);
14302 	if (cpu_buf->base == MAP_FAILED) {
14303 		cpu_buf->base = NULL;
14304 		err = -errno;
14305 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
14306 			cpu, errstr(err));
14307 		goto error;
14308 	}
14309 
14310 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
14311 		err = -errno;
14312 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
14313 			cpu, errstr(err));
14314 		goto error;
14315 	}
14316 
14317 	return cpu_buf;
14318 
14319 error:
14320 	perf_buffer__free_cpu_buf(pb, cpu_buf);
14321 	return (struct perf_cpu_buf *)ERR_PTR(err);
14322 }
14323 
14324 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14325 					      struct perf_buffer_params *p);
14326 
14327 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
14328 				     perf_buffer_sample_fn sample_cb,
14329 				     perf_buffer_lost_fn lost_cb,
14330 				     void *ctx,
14331 				     const struct perf_buffer_opts *opts)
14332 {
14333 	const size_t attr_sz = sizeof(struct perf_event_attr);
14334 	struct perf_buffer_params p = {};
14335 	struct perf_event_attr attr;
14336 	__u32 sample_period;
14337 
14338 	if (!OPTS_VALID(opts, perf_buffer_opts))
14339 		return libbpf_err_ptr(-EINVAL);
14340 
14341 	sample_period = OPTS_GET(opts, sample_period, 1);
14342 	if (!sample_period)
14343 		sample_period = 1;
14344 
14345 	memset(&attr, 0, attr_sz);
14346 	attr.size = attr_sz;
14347 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
14348 	attr.type = PERF_TYPE_SOFTWARE;
14349 	attr.sample_type = PERF_SAMPLE_RAW;
14350 	attr.wakeup_events = sample_period;
14351 
14352 	p.attr = &attr;
14353 	p.sample_cb = sample_cb;
14354 	p.lost_cb = lost_cb;
14355 	p.ctx = ctx;
14356 
14357 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14358 }
14359 
14360 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
14361 					 struct perf_event_attr *attr,
14362 					 perf_buffer_event_fn event_cb, void *ctx,
14363 					 const struct perf_buffer_raw_opts *opts)
14364 {
14365 	struct perf_buffer_params p = {};
14366 
14367 	if (!attr)
14368 		return libbpf_err_ptr(-EINVAL);
14369 
14370 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
14371 		return libbpf_err_ptr(-EINVAL);
14372 
14373 	p.attr = attr;
14374 	p.event_cb = event_cb;
14375 	p.ctx = ctx;
14376 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
14377 	p.cpus = OPTS_GET(opts, cpus, NULL);
14378 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
14379 
14380 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14381 }
14382 
14383 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14384 					      struct perf_buffer_params *p)
14385 {
14386 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
14387 	struct bpf_map_info map;
14388 	struct perf_buffer *pb;
14389 	bool *online = NULL;
14390 	__u32 map_info_len;
14391 	int err, i, j, n;
14392 
14393 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
14394 		pr_warn("page count should be power of two, but is %zu\n",
14395 			page_cnt);
14396 		return ERR_PTR(-EINVAL);
14397 	}
14398 
14399 	/* best-effort sanity checks */
14400 	memset(&map, 0, sizeof(map));
14401 	map_info_len = sizeof(map);
14402 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
14403 	if (err) {
14404 		err = -errno;
14405 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
14406 		 * -EBADFD, -EFAULT, or -E2BIG on real error
14407 		 */
14408 		if (err != -EINVAL) {
14409 			pr_warn("failed to get map info for map FD %d: %s\n",
14410 				map_fd, errstr(err));
14411 			return ERR_PTR(err);
14412 		}
14413 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
14414 			 map_fd);
14415 	} else {
14416 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
14417 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
14418 				map.name);
14419 			return ERR_PTR(-EINVAL);
14420 		}
14421 	}
14422 
14423 	pb = calloc(1, sizeof(*pb));
14424 	if (!pb)
14425 		return ERR_PTR(-ENOMEM);
14426 
14427 	pb->event_cb = p->event_cb;
14428 	pb->sample_cb = p->sample_cb;
14429 	pb->lost_cb = p->lost_cb;
14430 	pb->ctx = p->ctx;
14431 
14432 	pb->page_size = getpagesize();
14433 	pb->mmap_size = pb->page_size * page_cnt;
14434 	pb->map_fd = map_fd;
14435 
14436 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
14437 	if (pb->epoll_fd < 0) {
14438 		err = -errno;
14439 		pr_warn("failed to create epoll instance: %s\n",
14440 			errstr(err));
14441 		goto error;
14442 	}
14443 
14444 	if (p->cpu_cnt > 0) {
14445 		pb->cpu_cnt = p->cpu_cnt;
14446 	} else {
14447 		pb->cpu_cnt = libbpf_num_possible_cpus();
14448 		if (pb->cpu_cnt < 0) {
14449 			err = pb->cpu_cnt;
14450 			goto error;
14451 		}
14452 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
14453 			pb->cpu_cnt = map.max_entries;
14454 	}
14455 
14456 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
14457 	if (!pb->events) {
14458 		err = -ENOMEM;
14459 		pr_warn("failed to allocate events: out of memory\n");
14460 		goto error;
14461 	}
14462 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
14463 	if (!pb->cpu_bufs) {
14464 		err = -ENOMEM;
14465 		pr_warn("failed to allocate buffers: out of memory\n");
14466 		goto error;
14467 	}
14468 
14469 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
14470 	if (err) {
14471 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
14472 		goto error;
14473 	}
14474 
14475 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
14476 		struct perf_cpu_buf *cpu_buf;
14477 		int cpu, map_key;
14478 
14479 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
14480 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
14481 
14482 		/* in case user didn't explicitly requested particular CPUs to
14483 		 * be attached to, skip offline/not present CPUs
14484 		 */
14485 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
14486 			continue;
14487 
14488 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
14489 		if (IS_ERR(cpu_buf)) {
14490 			err = PTR_ERR(cpu_buf);
14491 			goto error;
14492 		}
14493 
14494 		pb->cpu_bufs[j] = cpu_buf;
14495 
14496 		err = bpf_map_update_elem(pb->map_fd, &map_key,
14497 					  &cpu_buf->fd, 0);
14498 		if (err) {
14499 			err = -errno;
14500 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
14501 				cpu, map_key, cpu_buf->fd,
14502 				errstr(err));
14503 			goto error;
14504 		}
14505 
14506 		pb->events[j].events = EPOLLIN;
14507 		pb->events[j].data.ptr = cpu_buf;
14508 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
14509 			      &pb->events[j]) < 0) {
14510 			err = -errno;
14511 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
14512 				cpu, cpu_buf->fd,
14513 				errstr(err));
14514 			goto error;
14515 		}
14516 		j++;
14517 	}
14518 	pb->cpu_cnt = j;
14519 	free(online);
14520 
14521 	return pb;
14522 
14523 error:
14524 	free(online);
14525 	if (pb)
14526 		perf_buffer__free(pb);
14527 	return ERR_PTR(err);
14528 }
14529 
14530 struct perf_sample_raw {
14531 	struct perf_event_header header;
14532 	uint32_t size;
14533 	char data[];
14534 };
14535 
14536 struct perf_sample_lost {
14537 	struct perf_event_header header;
14538 	uint64_t id;
14539 	uint64_t lost;
14540 	uint64_t sample_id;
14541 };
14542 
14543 static enum bpf_perf_event_ret
14544 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
14545 {
14546 	struct perf_cpu_buf *cpu_buf = ctx;
14547 	struct perf_buffer *pb = cpu_buf->pb;
14548 	void *data = e;
14549 
14550 	/* user wants full control over parsing perf event */
14551 	if (pb->event_cb)
14552 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
14553 
14554 	switch (e->type) {
14555 	case PERF_RECORD_SAMPLE: {
14556 		struct perf_sample_raw *s = data;
14557 
14558 		if (pb->sample_cb)
14559 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
14560 		break;
14561 	}
14562 	case PERF_RECORD_LOST: {
14563 		struct perf_sample_lost *s = data;
14564 
14565 		if (pb->lost_cb)
14566 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
14567 		break;
14568 	}
14569 	default:
14570 		pr_warn("unknown perf sample type %u\n", e->type);
14571 		return LIBBPF_PERF_EVENT_ERROR;
14572 	}
14573 	return LIBBPF_PERF_EVENT_CONT;
14574 }
14575 
14576 static int perf_buffer__process_records(struct perf_buffer *pb,
14577 					struct perf_cpu_buf *cpu_buf)
14578 {
14579 	enum bpf_perf_event_ret ret;
14580 
14581 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
14582 				     pb->page_size, &cpu_buf->buf,
14583 				     &cpu_buf->buf_size,
14584 				     perf_buffer__process_record, cpu_buf);
14585 	if (ret != LIBBPF_PERF_EVENT_CONT)
14586 		return ret;
14587 	return 0;
14588 }
14589 
14590 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14591 {
14592 	return pb->epoll_fd;
14593 }
14594 
14595 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14596 {
14597 	int i, cnt, err;
14598 
14599 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14600 	if (cnt < 0)
14601 		return -errno;
14602 
14603 	for (i = 0; i < cnt; i++) {
14604 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14605 
14606 		err = perf_buffer__process_records(pb, cpu_buf);
14607 		if (err) {
14608 			pr_warn("error while processing records: %s\n", errstr(err));
14609 			return libbpf_err(err);
14610 		}
14611 	}
14612 	return cnt;
14613 }
14614 
14615 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14616  * manager.
14617  */
14618 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14619 {
14620 	return pb->cpu_cnt;
14621 }
14622 
14623 /*
14624  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14625  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14626  * select()/poll()/epoll() Linux syscalls.
14627  */
14628 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14629 {
14630 	struct perf_cpu_buf *cpu_buf;
14631 
14632 	if (buf_idx >= pb->cpu_cnt)
14633 		return libbpf_err(-EINVAL);
14634 
14635 	cpu_buf = pb->cpu_bufs[buf_idx];
14636 	if (!cpu_buf)
14637 		return libbpf_err(-ENOENT);
14638 
14639 	return cpu_buf->fd;
14640 }
14641 
14642 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14643 {
14644 	struct perf_cpu_buf *cpu_buf;
14645 
14646 	if (buf_idx >= pb->cpu_cnt)
14647 		return libbpf_err(-EINVAL);
14648 
14649 	cpu_buf = pb->cpu_bufs[buf_idx];
14650 	if (!cpu_buf)
14651 		return libbpf_err(-ENOENT);
14652 
14653 	*buf = cpu_buf->base;
14654 	*buf_size = pb->mmap_size;
14655 	return 0;
14656 }
14657 
14658 /*
14659  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14660  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14661  * consume, do nothing and return success.
14662  * Returns:
14663  *   - 0 on success;
14664  *   - <0 on failure.
14665  */
14666 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14667 {
14668 	struct perf_cpu_buf *cpu_buf;
14669 
14670 	if (buf_idx >= pb->cpu_cnt)
14671 		return libbpf_err(-EINVAL);
14672 
14673 	cpu_buf = pb->cpu_bufs[buf_idx];
14674 	if (!cpu_buf)
14675 		return libbpf_err(-ENOENT);
14676 
14677 	return perf_buffer__process_records(pb, cpu_buf);
14678 }
14679 
14680 int perf_buffer__consume(struct perf_buffer *pb)
14681 {
14682 	int i, err;
14683 
14684 	for (i = 0; i < pb->cpu_cnt; i++) {
14685 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14686 
14687 		if (!cpu_buf)
14688 			continue;
14689 
14690 		err = perf_buffer__process_records(pb, cpu_buf);
14691 		if (err) {
14692 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14693 				i, errstr(err));
14694 			return libbpf_err(err);
14695 		}
14696 	}
14697 	return 0;
14698 }
14699 
14700 int bpf_program__set_attach_target(struct bpf_program *prog,
14701 				   int attach_prog_fd,
14702 				   const char *attach_func_name)
14703 {
14704 	int btf_obj_fd = 0, btf_id = 0, err;
14705 
14706 	if (!prog || attach_prog_fd < 0)
14707 		return libbpf_err(-EINVAL);
14708 
14709 	if (prog->obj->state >= OBJ_LOADED)
14710 		return libbpf_err(-EINVAL);
14711 
14712 	if (attach_prog_fd && !attach_func_name) {
14713 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14714 		 * the normal object/program load phase.
14715 		 */
14716 		prog->attach_prog_fd = attach_prog_fd;
14717 		return 0;
14718 	}
14719 
14720 	if (attach_prog_fd) {
14721 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14722 						 attach_prog_fd, prog->obj->token_fd);
14723 		if (btf_id < 0)
14724 			return libbpf_err(btf_id);
14725 	} else {
14726 		if (!attach_func_name)
14727 			return libbpf_err(-EINVAL);
14728 
14729 		/* load btf_vmlinux, if not yet */
14730 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14731 		if (err)
14732 			return libbpf_err(err);
14733 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14734 					 prog->expected_attach_type,
14735 					 &btf_obj_fd, &btf_id);
14736 		if (err)
14737 			return libbpf_err(err);
14738 	}
14739 
14740 	prog->attach_btf_id = btf_id;
14741 	prog->attach_btf_obj_fd = btf_obj_fd;
14742 	prog->attach_prog_fd = attach_prog_fd;
14743 	return 0;
14744 }
14745 
14746 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14747 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14748 {
14749 	int prog_fd, map_fd;
14750 
14751 	prog_fd = bpf_program__fd(prog);
14752 	if (prog_fd < 0) {
14753 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14754 			prog->name);
14755 		return libbpf_err(-EINVAL);
14756 	}
14757 
14758 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14759 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14760 		return libbpf_err(-EINVAL);
14761 	}
14762 
14763 	map_fd = bpf_map__fd(map);
14764 	if (map_fd < 0) {
14765 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14766 		return libbpf_err(-EINVAL);
14767 	}
14768 
14769 	if (!bpf_map__is_struct_ops(map)) {
14770 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14771 		return libbpf_err(-EINVAL);
14772 	}
14773 
14774 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14775 }
14776 
14777 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14778 {
14779 	int err = 0, n, len, start, end = -1;
14780 	bool *tmp;
14781 
14782 	*mask = NULL;
14783 	*mask_sz = 0;
14784 
14785 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14786 	while (*s) {
14787 		if (*s == ',' || *s == '\n') {
14788 			s++;
14789 			continue;
14790 		}
14791 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14792 		if (n <= 0 || n > 2) {
14793 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14794 			err = -EINVAL;
14795 			goto cleanup;
14796 		} else if (n == 1) {
14797 			end = start;
14798 		}
14799 		if (start < 0 || start > end) {
14800 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14801 				start, end, s);
14802 			err = -EINVAL;
14803 			goto cleanup;
14804 		}
14805 		tmp = realloc(*mask, end + 1);
14806 		if (!tmp) {
14807 			err = -ENOMEM;
14808 			goto cleanup;
14809 		}
14810 		*mask = tmp;
14811 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14812 		memset(tmp + start, 1, end - start + 1);
14813 		*mask_sz = end + 1;
14814 		s += len;
14815 	}
14816 	if (!*mask_sz) {
14817 		pr_warn("Empty CPU range\n");
14818 		return -EINVAL;
14819 	}
14820 	return 0;
14821 cleanup:
14822 	free(*mask);
14823 	*mask = NULL;
14824 	return err;
14825 }
14826 
14827 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14828 {
14829 	int fd, err = 0, len;
14830 	char buf[128];
14831 
14832 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14833 	if (fd < 0) {
14834 		err = -errno;
14835 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14836 		return err;
14837 	}
14838 	len = read(fd, buf, sizeof(buf));
14839 	close(fd);
14840 	if (len <= 0) {
14841 		err = len ? -errno : -EINVAL;
14842 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14843 		return err;
14844 	}
14845 	if (len >= sizeof(buf)) {
14846 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14847 		return -E2BIG;
14848 	}
14849 	buf[len] = '\0';
14850 
14851 	return parse_cpu_mask_str(buf, mask, mask_sz);
14852 }
14853 
14854 int libbpf_num_possible_cpus(void)
14855 {
14856 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14857 	static int cpus;
14858 	int err, n, i, tmp_cpus;
14859 	bool *mask;
14860 
14861 	tmp_cpus = READ_ONCE(cpus);
14862 	if (tmp_cpus > 0)
14863 		return tmp_cpus;
14864 
14865 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14866 	if (err)
14867 		return libbpf_err(err);
14868 
14869 	tmp_cpus = 0;
14870 	for (i = 0; i < n; i++) {
14871 		if (mask[i])
14872 			tmp_cpus++;
14873 	}
14874 	free(mask);
14875 
14876 	WRITE_ONCE(cpus, tmp_cpus);
14877 	return tmp_cpus;
14878 }
14879 
14880 static int populate_skeleton_maps(const struct bpf_object *obj,
14881 				  struct bpf_map_skeleton *maps,
14882 				  size_t map_cnt, size_t map_skel_sz)
14883 {
14884 	int i;
14885 
14886 	for (i = 0; i < map_cnt; i++) {
14887 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14888 		struct bpf_map **map = map_skel->map;
14889 		const char *name = map_skel->name;
14890 		void **mmaped = map_skel->mmaped;
14891 
14892 		*map = bpf_object__find_map_by_name(obj, name);
14893 		if (!*map) {
14894 			pr_warn("failed to find skeleton map '%s'\n", name);
14895 			return -ESRCH;
14896 		}
14897 
14898 		/* externs shouldn't be pre-setup from user code */
14899 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14900 			*mmaped = (*map)->mmaped;
14901 	}
14902 	return 0;
14903 }
14904 
14905 static int populate_skeleton_progs(const struct bpf_object *obj,
14906 				   struct bpf_prog_skeleton *progs,
14907 				   size_t prog_cnt, size_t prog_skel_sz)
14908 {
14909 	int i;
14910 
14911 	for (i = 0; i < prog_cnt; i++) {
14912 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14913 		struct bpf_program **prog = prog_skel->prog;
14914 		const char *name = prog_skel->name;
14915 
14916 		*prog = bpf_object__find_program_by_name(obj, name);
14917 		if (!*prog) {
14918 			pr_warn("failed to find skeleton program '%s'\n", name);
14919 			return -ESRCH;
14920 		}
14921 	}
14922 	return 0;
14923 }
14924 
14925 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14926 			      const struct bpf_object_open_opts *opts)
14927 {
14928 	struct bpf_object *obj;
14929 	int err;
14930 
14931 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14932 	if (IS_ERR(obj)) {
14933 		err = PTR_ERR(obj);
14934 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14935 			s->name, errstr(err));
14936 		return libbpf_err(err);
14937 	}
14938 
14939 	*s->obj = obj;
14940 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14941 	if (err) {
14942 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14943 		return libbpf_err(err);
14944 	}
14945 
14946 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14947 	if (err) {
14948 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14949 		return libbpf_err(err);
14950 	}
14951 
14952 	return 0;
14953 }
14954 
14955 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14956 {
14957 	int err, len, var_idx, i;
14958 	const char *var_name;
14959 	const struct bpf_map *map;
14960 	struct btf *btf;
14961 	__u32 map_type_id;
14962 	const struct btf_type *map_type, *var_type;
14963 	const struct bpf_var_skeleton *var_skel;
14964 	struct btf_var_secinfo *var;
14965 
14966 	if (!s->obj)
14967 		return libbpf_err(-EINVAL);
14968 
14969 	btf = bpf_object__btf(s->obj);
14970 	if (!btf) {
14971 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14972 			bpf_object__name(s->obj));
14973 		return libbpf_err(-errno);
14974 	}
14975 
14976 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14977 	if (err) {
14978 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14979 		return libbpf_err(err);
14980 	}
14981 
14982 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14983 	if (err) {
14984 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14985 		return libbpf_err(err);
14986 	}
14987 
14988 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14989 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14990 		map = *var_skel->map;
14991 		map_type_id = bpf_map__btf_value_type_id(map);
14992 		map_type = btf__type_by_id(btf, map_type_id);
14993 
14994 		if (!btf_is_datasec(map_type)) {
14995 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14996 				bpf_map__name(map),
14997 				__btf_kind_str(btf_kind(map_type)));
14998 			return libbpf_err(-EINVAL);
14999 		}
15000 
15001 		len = btf_vlen(map_type);
15002 		var = btf_var_secinfos(map_type);
15003 		for (i = 0; i < len; i++, var++) {
15004 			var_type = btf__type_by_id(btf, var->type);
15005 			var_name = btf__name_by_offset(btf, var_type->name_off);
15006 			if (strcmp(var_name, var_skel->name) == 0) {
15007 				*var_skel->addr = map->mmaped + var->offset;
15008 				break;
15009 			}
15010 		}
15011 	}
15012 	return 0;
15013 }
15014 
15015 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
15016 {
15017 	if (!s)
15018 		return;
15019 	free(s->maps);
15020 	free(s->progs);
15021 	free(s->vars);
15022 	free(s);
15023 }
15024 
15025 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
15026 {
15027 	int i, err;
15028 
15029 	err = bpf_object__load(*s->obj);
15030 	if (err) {
15031 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
15032 		return libbpf_err(err);
15033 	}
15034 
15035 	for (i = 0; i < s->map_cnt; i++) {
15036 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15037 		struct bpf_map *map = *map_skel->map;
15038 
15039 		if (!map_skel->mmaped)
15040 			continue;
15041 
15042 		if (map->def.type == BPF_MAP_TYPE_ARENA)
15043 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
15044 		else
15045 			*map_skel->mmaped = map->mmaped;
15046 	}
15047 
15048 	return 0;
15049 }
15050 
15051 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
15052 {
15053 	int i, err;
15054 
15055 	for (i = 0; i < s->prog_cnt; i++) {
15056 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15057 		struct bpf_program *prog = *prog_skel->prog;
15058 		struct bpf_link **link = prog_skel->link;
15059 
15060 		if (!prog->autoload || !prog->autoattach)
15061 			continue;
15062 
15063 		/* auto-attaching not supported for this program */
15064 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
15065 			continue;
15066 
15067 		/* if user already set the link manually, don't attempt auto-attach */
15068 		if (*link)
15069 			continue;
15070 
15071 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
15072 		if (err) {
15073 			pr_warn("prog '%s': failed to auto-attach: %s\n",
15074 				bpf_program__name(prog), errstr(err));
15075 			return libbpf_err(err);
15076 		}
15077 
15078 		/* It's possible that for some SEC() definitions auto-attach
15079 		 * is supported in some cases (e.g., if definition completely
15080 		 * specifies target information), but is not in other cases.
15081 		 * SEC("uprobe") is one such case. If user specified target
15082 		 * binary and function name, such BPF program can be
15083 		 * auto-attached. But if not, it shouldn't trigger skeleton's
15084 		 * attach to fail. It should just be skipped.
15085 		 * attach_fn signals such case with returning 0 (no error) and
15086 		 * setting link to NULL.
15087 		 */
15088 	}
15089 
15090 
15091 	for (i = 0; i < s->map_cnt; i++) {
15092 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15093 		struct bpf_map *map = *map_skel->map;
15094 		struct bpf_link **link;
15095 
15096 		if (!map->autocreate || !map->autoattach)
15097 			continue;
15098 
15099 		/* only struct_ops maps can be attached */
15100 		if (!bpf_map__is_struct_ops(map))
15101 			continue;
15102 
15103 		/* skeleton is created with earlier version of bpftool, notify user */
15104 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
15105 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
15106 				bpf_map__name(map));
15107 			continue;
15108 		}
15109 
15110 		link = map_skel->link;
15111 		if (!link) {
15112 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
15113 				bpf_map__name(map));
15114 			continue;
15115 		}
15116 
15117 		if (*link)
15118 			continue;
15119 
15120 		*link = bpf_map__attach_struct_ops(map);
15121 		if (!*link) {
15122 			err = -errno;
15123 			pr_warn("map '%s': failed to auto-attach: %s\n",
15124 				bpf_map__name(map), errstr(err));
15125 			return libbpf_err(err);
15126 		}
15127 	}
15128 
15129 	return 0;
15130 }
15131 
15132 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
15133 {
15134 	int i;
15135 
15136 	for (i = 0; i < s->prog_cnt; i++) {
15137 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15138 		struct bpf_link **link = prog_skel->link;
15139 
15140 		bpf_link__destroy(*link);
15141 		*link = NULL;
15142 	}
15143 
15144 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
15145 		return;
15146 
15147 	for (i = 0; i < s->map_cnt; i++) {
15148 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15149 		struct bpf_link **link = map_skel->link;
15150 
15151 		if (link) {
15152 			bpf_link__destroy(*link);
15153 			*link = NULL;
15154 		}
15155 	}
15156 }
15157 
15158 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
15159 {
15160 	if (!s)
15161 		return;
15162 
15163 	bpf_object__detach_skeleton(s);
15164 	if (s->obj)
15165 		bpf_object__close(*s->obj);
15166 	free(s->maps);
15167 	free(s->progs);
15168 	free(s);
15169 }
15170